diff --git a/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql index e69de29bb2d1..f1a142a44e28 100644 --- a/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.2.0/mysql/schemaChanges.sql @@ -0,0 +1,133 @@ +-- Shapes: SHACL node shapes of an ontology, each targeting one class and listing constraints on +-- its properties. They are working content, sealed into releases as SHAPE members. +-- ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints +CREATE TABLE IF NOT EXISTS ontology_shape_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, + ontologyId varchar(36) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.ontology.id'))) STORED NOT NULL, + updatedAt bigint unsigned GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.updatedAt'))) STORED NOT NULL, + updatedBy varchar(256) GENERATED ALWAYS AS (json_unquote(json_extract(json, '$.updatedBy'))) STORED NOT NULL, + deleted tinyint(1) GENERATED ALWAYS AS (json_extract(json, '$.deleted')) STORED, + PRIMARY KEY (id), + UNIQUE KEY ontology_shape_fqn_hash_unique (fqnHash), + KEY ontology_shape_name_index (name), + KEY ontology_shape_listing_index (ontologyId, deleted, name, id), + KEY ontology_shape_deleted_index (deleted) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- A table binding of an ontology class can say how its table takes part in the class's records: +-- its role, the ordered columns that identify one record, and one row filter. A row written +-- before these columns existed keeps NULL in all three and reads back as an unassigned binding +-- (ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records). +SET @ontology_concept_binding_role_ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 'ontology_concept_binding' + AND column_name = 'bindingRole' + ), + 'SELECT 1', + 'ALTER TABLE ontology_concept_binding ADD COLUMN bindingRole VARCHAR(16) NULL, ADD COLUMN subjectKey JSON NULL, ADD COLUMN rowFilter JSON NULL' + ) +); +PREPARE ontology_concept_binding_role_stmt FROM @ontology_concept_binding_role_ddl; +EXECUTE ontology_concept_binding_role_stmt; +DEALLOCATE PREPARE ontology_concept_binding_role_stmt; + +-- Definitions a person declined to add to an ontology. A later draft that proposes the same +-- definition, with the same content, is matched against these rows. The key is the ontology, the +-- operation type, the SHA-256 of the definition's IRI and the SHA-256 of its canonical content. +-- ADR:2026-11-22-a-declined-definition-is-remembered-by-content +CREATE TABLE IF NOT EXISTS ontology_declined_definition ( + ontologyId VARCHAR(36) NOT NULL, + operationType VARCHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + iri TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, + iriHash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + payloadDigest CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + declinedBy VARCHAR(256) NOT NULL, + declinedAt BIGINT NOT NULL, + reason TEXT NULL, + changeSetId VARCHAR(36) NOT NULL, + operationId VARCHAR(36) NOT NULL, + PRIMARY KEY (ontologyId, operationType, iriHash, payloadDigest), + KEY ontology_declined_definition_listing_index (ontologyId, declinedAt) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- Generated tests and the suggestion tasks that propose a test case are looked up by the class +-- that generated them. The class is a stored column of its own, filled from the JSON of every +-- existing row, so each lookup reads an index instead of every row. +-- ADR:2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index +SET @test_case_generated_by_class_ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 'test_case' + AND column_name = 'generatedByClassId' + ), + 'SELECT 1', + 'ALTER TABLE test_case ADD COLUMN generatedByClassId VARCHAR(36) GENERATED ALWAYS AS (CASE WHEN char_length(json_unquote(json_extract(`json`, _utf8mb4''$.generatedBy.class.id''))) = 36 THEN json_unquote(json_extract(`json`, _utf8mb4''$.generatedBy.class.id'')) END) STORED NULL' + ) +); +PREPARE test_case_generated_by_class_stmt FROM @test_case_generated_by_class_ddl; +EXECUTE test_case_generated_by_class_stmt; +DEALLOCATE PREPARE test_case_generated_by_class_stmt; + +SET @test_case_generated_by_class_idx_ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.statistics + WHERE table_schema = DATABASE() + AND table_name = 'test_case' + AND index_name = 'idx_test_case_generated_by_class' + ), + 'SELECT 1', + 'ALTER TABLE test_case ADD KEY idx_test_case_generated_by_class (generatedByClassId)' + ) +); +PREPARE test_case_generated_by_class_idx_stmt FROM @test_case_generated_by_class_idx_ddl; +EXECUTE test_case_generated_by_class_idx_stmt; +DEALLOCATE PREPARE test_case_generated_by_class_idx_stmt; + +-- A task that proposes a test case carries a test case proposal, written as JSON text, in its +-- payload. The column holds the class that generated the proposal, and stays NULL for every other +-- task, for a payload that is not JSON and for a class id that is not 36 characters. +SET @task_entity_test_case_class_ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 'task_entity' + AND column_name = 'testCaseClassId' + ), + 'SELECT 1', + 'ALTER TABLE task_entity ADD COLUMN testCaseClassId VARCHAR(36) GENERATED ALWAYS AS (CASE WHEN json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestionType'')) = ''TestCase'' AND json_valid(json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestedValue''))) AND char_length(json_unquote(json_extract(CAST(json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestedValue'')) AS JSON), _utf8mb4''$.generatedBy.class.id''))) = 36 THEN json_unquote(json_extract(CAST(json_unquote(json_extract(`json`, _utf8mb4''$.payload.suggestedValue'')) AS JSON), _utf8mb4''$.generatedBy.class.id'')) END) STORED NULL' + ) +); +PREPARE task_entity_test_case_class_stmt FROM @task_entity_test_case_class_ddl; +EXECUTE task_entity_test_case_class_stmt; +DEALLOCATE PREPARE task_entity_test_case_class_stmt; + +SET @task_entity_test_case_class_idx_ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.statistics + WHERE table_schema = DATABASE() + AND table_name = 'task_entity' + AND index_name = 'idx_task_test_case_class' + ), + 'SELECT 1', + 'ALTER TABLE task_entity ADD KEY idx_task_test_case_class (testCaseClassId)' + ) +); +PREPARE task_entity_test_case_class_idx_stmt FROM @task_entity_test_case_class_idx_ddl; +EXECUTE task_entity_test_case_class_idx_stmt; +DEALLOCATE PREPARE task_entity_test_case_class_idx_stmt; diff --git a/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql index e69de29bb2d1..a58dd6839f75 100644 --- a/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.2.0/postgres/schemaChanges.sql @@ -0,0 +1,92 @@ +-- Shapes: SHACL node shapes of an ontology, each targeting one class and listing constraints on +-- its properties. They are working content, sealed into releases as SHAPE members. +-- ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints +CREATE TABLE IF NOT EXISTS ontology_shape_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, + ontologyId VARCHAR(36) GENERATED ALWAYS AS (json -> 'ontology' ->> 'id') STORED NOT NULL, + updatedAt BIGINT GENERATED ALWAYS AS ((json ->> 'updatedAt')::bigint) STORED NOT NULL, + updatedBy VARCHAR(256) GENERATED ALWAYS AS (json ->> 'updatedBy') STORED NOT NULL, + deleted BOOLEAN GENERATED ALWAYS AS ((json ->> 'deleted')::boolean) STORED, + PRIMARY KEY (id), + CONSTRAINT ontology_shape_fqn_hash_unique UNIQUE (fqnHash) +); +CREATE INDEX IF NOT EXISTS ontology_shape_name_index ON ontology_shape_entity (name); +CREATE INDEX IF NOT EXISTS ontology_shape_listing_index ON ontology_shape_entity (ontologyId, deleted, name, id); +CREATE INDEX IF NOT EXISTS ontology_shape_deleted_index ON ontology_shape_entity (deleted); + +-- A table binding of an ontology class can say how its table takes part in the class's records: +-- its role, the ordered columns that identify one record, and one row filter. A row written +-- before these columns existed keeps NULL in all three and reads back as an unassigned binding +-- (ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records). +ALTER TABLE ontology_concept_binding + ADD COLUMN IF NOT EXISTS bindingRole VARCHAR(16), + ADD COLUMN IF NOT EXISTS subjectKey JSONB, + ADD COLUMN IF NOT EXISTS rowFilter JSONB; + +-- Definitions a person declined to add to an ontology. A later draft that proposes the same +-- definition, with the same content, is matched against these rows. The key is the ontology, the +-- operation type, the SHA-256 of the definition's IRI and the SHA-256 of its canonical content. +-- ADR:2026-11-22-a-declined-definition-is-remembered-by-content +CREATE TABLE IF NOT EXISTS ontology_declined_definition ( + ontologyId VARCHAR(36) NOT NULL, + operationType VARCHAR(32) COLLATE "C" NOT NULL, + iri TEXT COLLATE "C" NOT NULL, + iriHash CHAR(64) COLLATE "C" NOT NULL, + payloadDigest CHAR(64) COLLATE "C" NOT NULL, + declinedBy VARCHAR(256) NOT NULL, + declinedAt BIGINT NOT NULL, + reason TEXT, + changeSetId VARCHAR(36) NOT NULL, + operationId VARCHAR(36) NOT NULL, + PRIMARY KEY (ontologyId, operationType, iriHash, payloadDigest) +); + +CREATE INDEX IF NOT EXISTS ontology_declined_definition_listing_index + ON ontology_declined_definition (ontologyId, declinedAt); + +-- Generated tests and the suggestion tasks that propose a test case are looked up by the class +-- that generated them. The class is a stored column of its own, filled from the JSON of every +-- existing row, so each lookup reads an index instead of every row. A value a column cannot read +-- (a class id that is not 36 characters, a proposal that is not JSON) leaves it NULL and never +-- fails the write. +-- ADR:2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index +ALTER TABLE test_case + ADD COLUMN IF NOT EXISTS generatedbyclassid VARCHAR(36) + GENERATED ALWAYS AS ( + CASE WHEN char_length(json -> 'generatedBy' -> 'class' ->> 'id') = 36 + THEN json -> 'generatedBy' -> 'class' ->> 'id' + END + ) STORED; + +CREATE INDEX IF NOT EXISTS idx_test_case_generated_by_class + ON test_case (generatedbyclassid) WHERE generatedbyclassid IS NOT NULL; + +-- A task that proposes a test case carries a test case proposal, written as JSON text, in its +-- payload. A generated column cannot catch a cast error, so the function does: it drops the +-- escape of a NUL character, which jsonb refuses, reads the class, and returns NULL for text +-- that is not JSON or a class id that is not 36 characters. +CREATE OR REPLACE FUNCTION test_case_proposal_class_id(proposal text) RETURNS varchar(36) +LANGUAGE plpgsql IMMUTABLE AS $$ +DECLARE + class_id text; +BEGIN + class_id := replace(proposal, '\u0000', '')::jsonb -> 'generatedBy' -> 'class' ->> 'id'; + RETURN CASE WHEN char_length(class_id) = 36 THEN class_id END; +EXCEPTION WHEN others THEN + RETURN NULL; +END +$$; + +ALTER TABLE task_entity + ADD COLUMN IF NOT EXISTS testcaseclassid VARCHAR(36) + GENERATED ALWAYS AS ( + CASE WHEN json -> 'payload' ->> 'suggestionType' = 'TestCase' + THEN test_case_proposal_class_id(json -> 'payload' ->> 'suggestedValue') + END + ) STORED; + +CREATE INDEX IF NOT EXISTS idx_task_test_case_class + ON task_entity (testcaseclassid) WHERE testcaseclassid IS NOT NULL; diff --git a/docs/decisions/2026-10-14-ontology-definitions-have-independent-entity-storage.md b/docs/decisions/2026-10-14-ontology-definitions-have-independent-entity-storage.md index 59cc73f98382..f8a7d5af34ce 100644 --- a/docs/decisions/2026-10-14-ontology-definitions-have-independent-entity-storage.md +++ b/docs/decisions/2026-10-14-ontology-definitions-have-independent-entity-storage.md @@ -1,7 +1,7 @@ # Ontology definitions use independent entity storage - **Status:** Accepted -- **Revisions:** v1 2026-10-14 (initial) · v2 2026-10-14 (semantic identity) · v3 2026-10-14 (native IRI creation) · v4 2026-10-14 (client IRI fidelity) · v5 2026-10-15 (native axiom ownership) · v6 2026-10-15 (derived reference index) · v7 2026-10-15 (unreleased 2.1.0 migrations and scoped axiom reset) · v8 2026-10-15 (metadata usage search by concept UUID) · v9 2026-10-15 (shared search and CSV definitions) · v10 2026-10-15 (release-only review and affected-definition validation) · v11 2026-10-15 (metadata annotations moved to a follow-up) +- **Revisions:** v1 2026-10-14 (initial) · v2 2026-10-14 (semantic identity) · v3 2026-10-14 (native IRI creation) · v4 2026-10-14 (client IRI fidelity) · v5 2026-10-15 (native axiom ownership) · v6 2026-10-15 (derived reference index) · v7 2026-10-15 (unreleased 2.1.0 migrations and scoped axiom reset) · v8 2026-10-15 (metadata usage search by concept UUID) · v9 2026-10-15 (shared search and CSV definitions) · v10 2026-10-15 (release-only review and affected-definition validation) · v11 2026-10-15 (metadata annotations moved to a follow-up) · v12 2026-11-21 (2.1.0 has shipped) - **Deciders:** Harsha - **Guard:** `OntologyEntityDAOTest`, `OntologyDefinitionTest`, `CollectionDAOCompositionTest`, `IndependentOntologyAxiomIT`, `OntologyReferencesTest`, `OntologyReferenceDAOTest`, `OntologyReleaseCaptureTest`, `IndependentOntologyReferenceIT` - **Related:** [Organizational ontology design](../plans/2026-10-14-organizational-ontology-design.md) @@ -136,3 +136,12 @@ through the reference index. These reads share the ontology state lock; MySQL re recently committed changes use locking reads, including both sides of the reference/axiom join. Cycle detection identifies every member of a strongly connected component without recursion. An invalid unrelated draft does not prevent repairs. Capture still validates the complete model. + +## Amendment: 2.1.0 has shipped + +The "unreleased 2.1.0 migrations" of v7 no longer hold. 2.1.0 shipped as the final release +`2.1.0-release` on 2026-11-20, so its migration folder is closed: a database that has run it never +reads an earlier folder again, and a statement added to it would run only on a database that +upgrades from before 2.1.0. Ontology tables and indexes added after that date go in the next +folder that has not shipped, starting with `2.2.0`, and a data change to a seeded row needs its +own `runOnce` step in that release. The shape table is the first to follow this. diff --git a/docs/decisions/2026-10-14-ontology-releases-seal-canonical-sql-members.md b/docs/decisions/2026-10-14-ontology-releases-seal-canonical-sql-members.md index 41ef9341b0bc..c4e5c9e5eb7e 100644 --- a/docs/decisions/2026-10-14-ontology-releases-seal-canonical-sql-members.md +++ b/docs/decisions/2026-10-14-ontology-releases-seal-canonical-sql-members.md @@ -1,9 +1,9 @@ # Ontology releases seal canonical SQL members - **Status:** Accepted -- **Revisions:** v1 2026-10-14 (initial); v10 2026-10-15 (single-ontology releases, captured comparison baseline, active-only projection); v11 2026-10-30 (SKOS, SKOS-XL and CSV export, export options and the SHACL gate); v12 2026-11-06 (50,000 members, batched capture, cached and unlocked reads); v13 2026-11-08 (account for parsed release cache heap) +- **Revisions:** v1 2026-10-14 (initial); v10 2026-10-15 (single-ontology releases, captured comparison baseline, active-only projection); v11 2026-10-30 (SKOS, SKOS-XL and CSV export, export options and the SHACL gate); v12 2026-11-06 (50,000 members, batched capture, cached and unlocked reads); v13 2026-11-08 (account for parsed release cache heap); v14 2026-12-05 (member listings keep viewable members) - **Deciders:** Harsha -- **Guard:** `OntologyReleaseManifestTest`, `OntologyReleaseDAOTest`, `OntologyReleaseCaptureTest`, `NativeOntologyCapacityPerfIT`, `OntologyWorkingStateTest`, `OntologyReleaseProjectionTest`, `OntologyStructureValidatorTest`, `OntologyReleaseComparisonTest`, `OntologyReleaseComparisonStorageTest`, `IndependentOntologyReleaseDiffIT`, `IndependentOntologyReleaseIT`, `IndependentOntologyReleaseExportIT`, `IndependentOntologyRetentionIT`, `OntologySkosProjectionTest`, `OntologyReleaseExporterTest`, `OntologyBoundAssetLinksTest`, `OntologyExportGateTest`, `IndependentOntologyReleaseExportFormatsIT`, `IndependentOntologyReleaseExportAssetsIT`, `IndependentOntologyReleaseExportGateIT` +- **Guard:** `OntologyReleaseManifestTest`, `OntologyReleaseDAOTest`, `OntologyReleaseCaptureTest`, `NativeOntologyCapacityPerfIT`, `OntologyWorkingStateTest`, `OntologyReleaseProjectionTest`, `OntologyStructureValidatorTest`, `OntologyReleaseComparisonTest`, `OntologyReleaseComparisonStorageTest`, `IndependentOntologyReleaseDiffIT`, `IndependentOntologyReleaseIT`, `IndependentOntologyReleaseMemberReadIT`, `IndependentOntologyReleaseExportIT`, `IndependentOntologyRetentionIT`, `OntologySkosProjectionTest`, `OntologyReleaseExporterTest`, `OntologyBoundAssetLinksTest`, `OntologyExportGateTest`, `IndependentOntologyReleaseExportFormatsIT`, `IndependentOntologyReleaseExportAssetsIT`, `IndependentOntologyReleaseExportGateIT` - **Related:** [Organizational ontology design](../plans/2026-10-14-organizational-ontology-design.md) ## Context @@ -182,3 +182,21 @@ that size is read and verified from SQL on every call. The v12 warm-read timings releases that fit this smaller payload budget; they do not describe larger uncached releases. `OntologyReleaseCaptureTest` verifies that a 23 MB release remains readable without staying cached on both MySQL and PostgreSQL, alongside cache reuse and authorization for smaller releases. + +## Amendment: a member listing keeps the members the caller may view (2026-12-05) + +`GET /v1/ontologyReleases/{id}/members/{kind}` answers with the members of that kind the caller may +view, decided per member as `GET .../members/{kind}/{memberId}` decides it (`ViewAll` on the member's +definition, loaded with the attributes a condition reads). A deny rule that covers one class or +property no longer refuses the whole kind. A caller who may not view the release itself still gets +403, and the by-id read of a member the caller may not view still gets 403. + +The page, its `after` cursor and `paging.total` are computed over the viewable members only, so +neither a short page, a cursor nor a count reveals a hidden member. The live definition lists keep +the total of every row and refill from following pages; a release is sealed and bounded to 50,000 +members, so each request scans the kind in key order once and counts the viewable ones. Whole-release +readers (`OntologyReleaseReader`: export, SPARQL, comparison, validation) are unchanged: they still +authorize every member and fail for a caller who may not view one, because a partial release would +produce a wrong result rather than a smaller one. + +`IndependentOntologyReleaseMemberReadIT` guards the listing. diff --git a/docs/decisions/2026-10-19-native-concept-bindings-remain-operational-metadata.md b/docs/decisions/2026-10-19-native-concept-bindings-remain-operational-metadata.md index 3cd4d4bbd46d..c6e96a4c6c18 100644 --- a/docs/decisions/2026-10-19-native-concept-bindings-remain-operational-metadata.md +++ b/docs/decisions/2026-10-19-native-concept-bindings-remain-operational-metadata.md @@ -2,6 +2,8 @@ - **Status:** Accepted - **Revisions:** v1 2026-10-19 (initial) · v2 2026-10-23 (binding rows, bounded paging, the ontology data graph) · v3 2026-10-24 (write confirmation and complete read recovery) · v4 2026-10-26 (paged cleanup under the lock, lineage between returned assets) · v5 2026-10-26 (stateless combined graph pages) · v6 2026-10-30 (Data mode bindings page size and stale reload budget) · v7 2026-11-15 (UI guards moved to Collate) · v8 2026-11-17 (bindings projected into the serving knowledge graph) + · v9 2026-11-21 (a table binding carries a role, a subject key, a row filter and joins) + · v10 2026-11-22 (a change set operation also writes a binding) - **Deciders:** Ontology Studio implementation review - **Guard:** OntologyConceptBindingsIT, OntologyConceptBindingCleanupIT, NativeOntologyDataGraphIT, NativeOntologyDataGraphEdgeScanIT, NativeOntologyDataGraphBindingScanIT, NativeOntologyDataGraphPageIT, NativeOntologyDataGraphContextIT, NativeOntologyDataGraphPagerTest, NativeOntologyDataGraphPagerRequestTest (including #aTokenTheServerKeySealedGetsTheRandomBytesRefusalBeforeAnyRead and #withoutAServerKeyAContinuedTopologyIssuesACursorTheNextRequestAccepts), NativeOntologyTopologyCursorCodecTest (including #aCursorKeyIsTheHmacOfItsServerKeyAndTheCursorLabel, #aCursorSealedUnderTheDerivedSecondKeyOfARotatedListStillOpens, #withoutAServerKeyOneKeyHeldForTheProcessSealsAndOpensCursors and #withoutAServerKeyACursorSealedWithAnotherKeyGetsTheSameRefusal), OntologyPrefixLineageDaoTest, OntologyBindingRulesTest, OntologyConceptBindingMigrationTest, ontologyAPI.test.ts, useOntologyConceptBindings.test.tsx *(openmetadata-collate)*, OntologyConceptAssets.test.tsx *(openmetadata-collate)*, OntologyColumnBindingEditor.test.tsx *(openmetadata-collate)*, OntologyPropertyBindings.test.tsx *(openmetadata-collate)*, OntologyConceptDataGraph.test.tsx, OntologyConceptInspector.test.tsx *(openmetadata-collate)* - **Related:** ADR:2026-10-17-glossaries-do-not-own-ontology-models, @@ -116,3 +118,25 @@ work. Guarded by `RdfConceptBindingProjectionTest`, `RdfConceptBindingWriteTest` `OntologyActiveGraphStorageTest#aWriteBeingDeliveredQueuesTheBoundAssetsItRefreshesAfterItself` and, against the Fuseki image, `RdfEntityDiffWriteIT#conceptBindingEdgesFollowTheBindingsAndLeaveTheReleaseGraphAlone`. + +## Amendment 2026-11-21. A table binding carries a role, a subject key, a row filter and joins + +ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records extends this record in three places. + +The binding row gains three nullable columns, `bindingRole`, `subjectKey` and `rowFilter`, and a column assignment gains an optional `join`. They are operational metadata like the rest of the row. They stay out of concept JSON, semantic working revisions, release digests and RDF import and export. + +Writes still require concept `EditAll` and target `ViewBasic`. A write that sets or changes a row filter also requires `ViewSampleData` on the table. A write that adds or changes a join also requires `ViewBasic` on the join target. + +The decision above describes a column assignment as a data-property UUID. The API also accepts an OBJECT property, and a column assignment to one that a write adds or changes must now carry a join. Once the ontology names a mapping source, a table binding that a write adds or changes must sit in that database. + +The identical-retry rule is unchanged. A write that repeats the stored row is a no-op and is checked against none of these rules, so a row written before them stays as it is until someone changes it. The tests that the new record names guard this amendment. + +## Amendment 2026-11-22. A change set operation also writes a binding + +The Decision gives the concept bindings API as the writer of bindings. An `UPSERT_BINDING` operation of a change set now writes one too (ADR:2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes). + +The operation writes through the step that checks and saves a binding row for the API, under the same ontology lock, and as the caller who applies the change set. Every rule of this record and of ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records therefore holds for it: the rights on the concept and the target, the single revision increment for each write that changes something, the cleanup of links to deleted assets, and the identical retry that is a no-op. + +Two things differ from the API. An operation proves what it read with the binding revision it carries, where the API takes `expectedRevision`. A stale operation is a 412 that names the binding, where the API answers 409. And the join that an operation writes is always stored as `inferred`. Only the API stores `confirmed`. + +Bindings stay operational metadata. A binding operation changes no definition, so applying it does not move the semantic working revision, and bindings stay out of concept JSON, release digests and RDF import and export. The tests that the new record names guard this amendment. diff --git a/docs/decisions/2026-11-03-ontology-working-draft-reads-require-edit-rights.md b/docs/decisions/2026-11-03-ontology-working-draft-reads-require-edit-rights.md index 9d4825318621..9da586cf61f6 100644 --- a/docs/decisions/2026-11-03-ontology-working-draft-reads-require-edit-rights.md +++ b/docs/decisions/2026-11-03-ontology-working-draft-reads-require-edit-rights.md @@ -1,9 +1,9 @@ # Reading an ontology's working draft requires EditAll on the ontology - **Status:** Accepted -- **Revisions:** v1 2026-11-03 (initial); v2 2026-11-03 (change sets); v3 2026-11-05 (rows of an unscoped list); v3 amended 2026-11-05 (glossary scopes taken from the page) +- **Revisions:** v1 2026-11-03 (initial); v2 2026-11-03 (change sets); v3 2026-11-05 (rows of an unscoped list); v3 amended 2026-11-05 (glossary scopes taken from the page); v4 2026-11-21 (shapes) - **Deciders:** Ontology Studio program -- **Guard:** `OntologyResourceAccessTest`, `ListFilterTest`, `IndependentOntologyDraftReadIT`, `IndependentOntologyAuthorizationIT` +- **Guard:** `OntologyResourceAccessTest`, `ListFilterTest`, `IndependentOntologyDraftReadIT`, `IndependentOntologyAuthorizationIT`, `OntologyShapeResourceIT` - **Related:** ADR:2026-11-02-ontology-reviewers-vote-without-edit-rights, `OntologyResourceAccess.requireDraftRead`, `useOntologyStudioModel.ts`, `OntologyMemoryReviewPanel.tsx` ## Context @@ -20,7 +20,8 @@ endpoints and not others. release, its members, release export, release-scoped SPARQL) keep view access. - The rule covers `POST /v1/ontologies/{id}/sparql?scope=draft`, `GET .../working/diff`, `GET .../working/validation`, `GET .../export`, `GET .../references`, and the lists - `GET /v1/ontologyConcepts`, `/v1/ontologyProperties` and `/v1/ontologyAxioms`. + `GET /v1/ontologyConcepts`, `/v1/ontologyProperties`, `/v1/ontologyAxioms` and + `/v1/ontologyShapes`. - A change set holds operations that no release has published, so reading one needs the edit right on its scope, the right `authorizeScope` checks for submit. That covers `GET /v1/ontologyChangeSets/{id}`, `GET .../{id}/versions`, `GET .../{id}/versions/{version}` @@ -44,7 +45,7 @@ endpoints and not others. not filtered, for the reason above. - The existing per-definition view check on the snapshot stays in place after the new check. - Reading one definition by id or name is unchanged: any viewer reads the working version of a - concept, property or axiom, including one no release contains. This is an exception to the rule, + concept, property, axiom or shape, including one no release contains. This is an exception to the rule, kept because deep links and the Studio's concept panel read a single definition this way, and because gating it would need a release-membership lookup on every read. It exposes one definition at a time to a caller who already knows its id or name; it exposes no listing, diff, @@ -66,3 +67,13 @@ endpoints and not others. - Closing the by-id exception needs a membership lookup against the active release and a published-version fallback for the single-definition read. - To revert to view access for a read, change `requireDraftRead` and the Viewer IT together. + +## Amendment: shapes + +A shape (ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints) is working-draft +content, so the rules above cover it. Listing `GET /v1/ontologyShapes`, the draft SHACL export +(`GET /v1/ontologies/{id}/export?format=shacl`) and `POST /v1/ontologyShapes/import` need `EditAll` +on the ontology, as the concept, property and axiom lists do. Reading one shape by id, by name, by +version list or by one version stays open to any viewer, which is the single-definition exception +above applied to shapes. A sealed release exports its shapes as SHACL with the release read rule. +`OntologyShapeResourceIT` and `IndependentOntologyShapeReleaseIT` guard it. diff --git a/docs/decisions/2026-11-21-a-class-has-at-most-one-display-name-property.md b/docs/decisions/2026-11-21-a-class-has-at-most-one-display-name-property.md new file mode 100644 index 000000000000..29a5c1413878 --- /dev/null +++ b/docs/decisions/2026-11-21-a-class-has-at-most-one-display-name-property.md @@ -0,0 +1,36 @@ +# A class has at most one display-name property, marked by om:displayNameIntent + +- **Status:** Accepted +- **Revisions:** v1 2026-11-21 (initial) +- **Deciders:** Ontology maintainers +- **Guard:** `OntologyStructureValidatorTest#aClassHasAtMostOneDisplayNameProperty`, + `OntologyReleaseContentDigestTest` and + `OntologyPropertyResourceIT#aDataPropertyCanBeItsClassDisplayNameAndEachClassHasOne` +- **Related:** ADR:2026-11-07-ontology-property-hierarchies-are-superproperty-fields + +## Context +A data property can say it is an identifier (`isIdentifier`). Clients also need to know which data +property holds the human-readable name of a class's instances, and exactly one answer per class, +or they have to guess. Release digests seal every property, so a new field must not change the +digest of a property that never sets it. + +## Decision +`ontologyProperty` gains `isDisplayName`, a boolean that only a data property may set. It has no +schema default: an unset flag is absent, so a property that never sets it seals the same content +and digest as before. `false` and absent mean the same to every reader, so a write that states `false` stores it as absent. +The CSV format has no column for the flag, so a CSV import keeps the stored flag and a Turtle import +takes it from the file. + +The RDF term is the annotation property `https://open-metadata.org/ontology/displayNameIntent`, +written as `"true"^^xsd:boolean` only when the flag is set, and read like `identifierIntent`: any +other value is a 400, and a missing statement imports as no flag. + +Within one ontology, two undeleted data properties that share a domain class cannot both set the flag. +The ontology structure check enforces it on every write, on import apply and on release capture, +and reports `DUPLICATE_DISPLAY_NAME` at `/isDisplayName` naming both properties. The second write +is refused instead of moving the flag, so no write changes a property its author did not touch. + +## Consequences +Moving the flag to another property takes two writes: clear it, then set it. A property with +several domain classes conflicts with any other flagged property on any of them. Revisit the +refusal if an author needs an atomic swap. diff --git a/docs/decisions/2026-11-21-a-table-binding-says-how-its-rows-become-records.md b/docs/decisions/2026-11-21-a-table-binding-says-how-its-rows-become-records.md new file mode 100644 index 000000000000..c8365dd4e509 --- /dev/null +++ b/docs/decisions/2026-11-21-a-table-binding-says-how-its-rows-become-records.md @@ -0,0 +1,119 @@ +# A table binding says how its rows become records + +- **Status:** Accepted +- **Revisions:** v1 2026-11-21 (initial) · v2 2026-11-22 (a row filter value is parsed as the data type of its column) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyBindingRulesTest`, `OntologyMappingHealthRulesTest`, `OntologyConceptBindingDaoIT`, `OntologyReleaseManifestTest#theMappingSourceOfAnOntologyIsNotCapturedDefinitionContent`, `IndependentOntologyTableBindingIT`, `IndependentOntologyMappingSourceIT`, `IndependentOntologyMappingHealthIT` +- **Related:** ADR:2026-10-19-native-concept-bindings-remain-operational-metadata (amended by this + record), ADR:2026-10-14-ontology-releases-seal-canonical-sql-members + +## Context + +A binding links a class to a catalog asset, and a column binding links a property to a column +(ADR:2026-10-19-native-concept-bindings-remain-operational-metadata). That tells a reader which +tables hold data about a class. It does not tell a reader how one row of such a table becomes one +record of the class. The binding did not say which columns identify a record, which of several +bound tables decides that a record exists, which rows belong to the class, or which table a +foreign-key column points at. Every consumer of a binding had to guess, and two consumers could +guess differently. + +A class can also be bound to tables in several databases. One SQL statement cannot be relied on to +join tables across databases, so such a class has no single query that reads its records. + +## Decision + +**An ontology may name one database as its mapping source.** `mappingSource` on the ontology is a +reference to one `database` entity. The server stores it as a `MAPPED_TO` relationship from the +ontology to the database, not in the ontology JSON, and returns it when a request asks for +`fields=mappingSource`. Setting, changing or clearing it requires `EditAll` on the ontology. A PUT +that names no mapping source keeps the stored one. A PATCH removes it. Setting it never reads, +changes or rejects the bindings that already exist, and a deleted database cannot become one. + +**A table binding may carry a role, a subject key and a row filter.** All three are absent on a +binding nobody has assigned, which includes every binding written before they existed. The server +never fills in a default. + +- `role` is `identity` or `contributing`. The identity table decides which records of the class + exist. A contributing table adds columns to those records. A class has at most one identity table. +- `subjectKey` is an ordered list of 1 to 16 column paths. A role and a subject key are set + together, and each key column must exist in the bound table when the key is set or changed. +- `rowFilter` is `{column, operator, value}`. `operator` is one of `equals`, `notEquals`, + `lessThan`, `lessThanOrEquals`, `greaterThan`, `greaterThanOrEquals`, `in`, `isNull` and + `isNotNull`. A comparison takes a string of at most 1024 characters, a number or a boolean. `in` + takes a list of 1 to 100 of them. `isNull` and `isNotNull` take no value. The server stores the + value as given. It does not compare the value with the column's data type and renders no SQL + from it. + +Only a table binding takes these fields. The native 2.2.0 migration adds three nullable columns to +`ontology_concept_binding` (`bindingRole`, `subjectKey` and `rowFilter`) and backfills nothing. +Each statement adds the columns only where they are missing, so running it again changes nothing. + +**A column bound to an OBJECT property carries a join.** `join` is +`{targetAssetId, status, on: [{child, parent}]}` with 1 to 16 pairs. Each `child` is a column of +the bound table and each `parent` is a column of the target table. `status` is `inferred` or +`confirmed`. The target is a table that the writer may view and that sits in the database of the +bound table. A column bound to a DATA property takes no join. + +**One step checks every binding write.** The step that saves a binding row runs under the ontology +lock and applies these rules, so no write path can skip them. + +- A write that sets or changes a row filter requires `ViewSampleData` on the table, on top of + `EditAll` on the class and `ViewBasic` on the table. A filter is a question about the rows of a + table, so it takes the right that reads those rows. Removing a filter requires no extra right, + because deleting the binding and writing it again without one already reaches that state. +- Once the ontology names a mapping source, a table binding that a write adds or changes must sit + in that database. A change of the mapping source takes the same lock. +- A write that repeats the stored row stays a no-op and is checked against no rule. A binding + written before a rule existed therefore stays as it is until someone changes it, and it can + always be deleted. + +**`GET /v1/ontologies/{id}/mappingHealth` lists what an editor still has to fix.** It requires view +access to the ontology and reads catalog metadata only. It never queries a bound table. It pages +the ontology's table bindings in class, then table id order, with a `limit` of at most 100 (default +50) and an opaque `after` cursor. It names only the classes, tables and properties that the caller +may view. The entry types are `noIdentityTable`, `unassignedBinding`, `relationColumnWithoutJoin`, +`joinNotConfirmed`, `keyLengthMismatch`, `keyTypeMismatch`, `joinTypeMismatch`, +`outsideMappingSource` and `multipleDatabases`. + +Two columns hold the same kind of data when their data types are equal or both belong to one of +four groups: numbers, character strings, timestamps, and binary strings. The key and join type +entries report a pair that fails this test. + +## Consequences + +Existing bindings read back unchanged and appear in mapping health as unassigned. An ontology whose +bindings span databases is reported and never migrated. An editor chooses a mapping source and +rebinds or deletes the bindings outside it. + +A key that differs from the identity table's key in length or type is a mapping health entry, not a +rejected write. The answer depends on another binding of the class, and an editor may write the two +in either order. + +The bindings PUT still replaces one whole asset association. A client that does not send `role`, +`subjectKey` or `rowFilter` clears them, and a client that adds an OBJECT property column without a +join gets a 400. + +The mapping source and the three binding fields stay out of release content. A release digest also +binds the version of every member, the ontology among them. A change of the mapping source therefore +writes its relationship row and records no field change. The ontology keeps its version and its +working revision, the release digest stays the same, and the change leaves no entry in the version +history and no change event. + +The mapping health cursor remembers one table for each of the first 8 databases it finds. An +ontology bound across more than 8 databases gets `multipleDatabases` again on later pages. + +Revisit the single mapping source if a class must be read across databases. The rule would then +name a set of databases, and every consumer of a join would have to handle a join that crosses +them. + +## Amendment 2026-11-22. A row filter value is parsed as the data type of its column + +A write that sets or changes a row filter now parses each value as the data type of the filter +column (ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text). A value that does not +parse is a 400 that names the column, the data type, and what the data type expects. The write +answers it before it checks `ViewSampleData`. A column whose data type has no written form takes +`isNull` and `isNotNull` only. A string value holds no control character. + +The server still stores the value as given. The Decision says that the server renders no SQL from a +row filter. That no longer holds: the generated statement of a class applies the row filter of +every table it reads, and it parses the stored value again when it does. diff --git a/docs/decisions/2026-11-21-graph-table-assets-carry-latest-profile-facts.md b/docs/decisions/2026-11-21-graph-table-assets-carry-latest-profile-facts.md new file mode 100644 index 000000000000..797c1aee8d60 --- /dev/null +++ b/docs/decisions/2026-11-21-graph-table-assets-carry-latest-profile-facts.md @@ -0,0 +1,43 @@ +# Table assets in a native graph page carry the facts of their latest stored profile + +- **Status:** Accepted +- **Revisions:** v1 2026-11-21 (initial); v2 2026-11-21 (pages of a concept's bindings carry the same facts) +- **Deciders:** Ontology Studio team +- **Guard:** `TableProfileFactsTest`, `NativeOntologyDataGraphProfileIT` + +## Context +A cluster asset in a native graph page named its table and column count, so a client that wanted a +table's size or the age of its profile made one profile request per table. A page holds up to 12 +clusters of several assets each, and profile reads are guarded by `ViewDataProfile`, a narrower +right than viewing the table. + +## Decision +Each table asset gains `rowCount`, `profiledAt` and `sampled`, read from the latest stored table +profile of every table on the page with one batched query. They are returned only for a table the +caller holds `ViewDataProfile` on; otherwise the table is returned without them. A table with no +stored profile has none of the three, so a missing profile is never reported as zero rows. +`rowCount` is returned only when the profile holds an exact non-negative whole number. + +`sampled` describes the stored profile, not the table's current profiler settings: it is true when +the profile records a percentage below 100, or a row sample smaller than the table (or a row sample +on a profile with no row count). A profile that records no sample is not sampled. `rowCount` itself +is always measured on the whole table, whatever `sampled` says. `sampled` reads only +`profileSample` and `profileSampleType`, so a profile computed on a partition or a custom query +reports `false`. A row sample is compared with the stored row count as it is, whole number or not. + +When one table has several latest profiles with the same timestamp, the one with the larger row +count wins (a missing count is smallest), then a sampled one over a whole one, so the result does +not depend on read order. Sampled wins the last tie because a sampled claim made when the server +cannot tell which profile is current only warns the client that the metrics may be partial. + +Each table of a page of a concept's bindings carries the same three values (`rowCount`, +`profiledAt`, `sampled`) on its hydrated asset binding, under the same rules: the same stored-profile +reading, the same per-table `ViewDataProfile` check and the same tie rule. A page reads them with +the same single batched query, issued only when the page holds a table the caller may view the +profile of. They are filled on pages of the graph page endpoint only. The concept's own bindings +endpoint returns the same asset type and leaves the three fields absent, so its cost does not change. + +## Consequences +One extra read per page, constant in the number of tables. A client tells "no profile" from "not +permitted" only by not needing to: both leave the three fields absent. Changing a table's profiler +settings does not alter `sampled` for profiles already stored. diff --git a/docs/decisions/2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints.md b/docs/decisions/2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints.md new file mode 100644 index 000000000000..99d15fde0724 --- /dev/null +++ b/docs/decisions/2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints.md @@ -0,0 +1,91 @@ +# Ontology shapes hold eight SHACL constraints, and report every other construct instead of refusing the file + +- **Status:** Accepted +- **Revisions:** v1 2026-11-21 (initial) · v2 2026-11-21 (deletes, import bounds and atomicity, reported constructs, size, upgrade) +- **Deciders:** Ontology Studio team +- **Guard:** `OntologyShapeRulesTest`, `OntologyShaclRoundTripTest`, `OntologyShapeValidationTest`, `OntologyShapeResourceIT`, `IndependentOntologyShapeReleaseIT`, `IndependentOntologyShapeDeleteImpactIT`, `IndependentOntologyShapeStatusIT`, `OntologyShapePolicyMigrationIT`, `OntologyShaclReaderTest`, `OntologyReferencesTest` +- **Related:** ADR:2026-10-14-ontology-definitions-have-independent-entity-storage, ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights + +## Context +An ontology states what exists, not what a well-formed instance of a class looks like. SHACL is the +standard way to say the second, and ontology files in the wild carry SHACL node shapes next to the +OWL. The ontology release already reserved the member kind `SHAPE`, but nothing wrote it. Importing +a SHACL file whole is out of reach: SHACL has logical combinations, SPARQL constraints, property +paths and recursion, and a stored model that held all of that would need a validator of its own. + +## Decision +- A shape is a native ontology entity, `ontologyShape`, owned by one ontology and living in its + working draft like an axiom. It has a `targetConcept` (the full IRI of one class), a `severity` + (`Violation`, `Warning` or `Info`, as SHACL defines them) and an ordered list of constraints. +- A constraint has an `id` that is unique inside its shape and does not change when the constraint + is edited, a `path` that is the full IRI of one property, and any of `minCount`, `maxCount`, + `classIri` (SHACL `sh:class`), `datatypeIri` (`sh:datatype`), `minInclusive`, `maxInclusive`, + `in` and `pattern`. At least one must be present. These eight are the supported constraints. +- A shape is sealed in a release as a `SHAPE` member with the fields `targetConcept`, `severity` + and `constraints`, and the release digest covers it. A release without shapes has the digest it + had before. +- Release validation fails a shape whose target class or constraint path is not declared in the + release (`UNDECLARED_CLASS`, `UNDECLARED_PROPERTY`), whose `classIri` names a class that is not + declared (`UNDECLARED_CLASS`), whose `minCount` is above its `maxCount` + (`SHAPE_CARDINALITY_CONFLICT`), whose `in` list is empty (`SHAPE_EMPTY_VALUE_LIST`), or that is + otherwise malformed, such as a repeated constraint id or a pattern that does not compile + (`SHAPE_INVALID_CONSTRAINT`). Saving a shape applies the checks that need no other definition; + the checks that name other definitions wait for the release, because the class or property may + be declared a moment later. +- SHACL is a Turtle export of the shapes (`format=shacl`) and an import (`POST + /v1/ontologyShapes/import`). Each shape is an `sh:NodeShape` named by `sh:name`, with one + `sh:property` node per constraint. The node is named by its shape's IRI, `#` and the constraint + id, so a re-import reads every id back, and `sh:order` keeps the authored order. A node that is + not named that way, such as a blank node in a file from elsewhere, gets `c1`, `c2` and so on in + the order the constraints are held. +- Import takes every shape with one IRI `sh:targetClass` and the supported constraints of its + property nodes with a single-IRI `sh:path`. Every other SHACL construct, such as `sh:or`, + `sh:sparql`, `sh:qualifiedValueShape`, `sh:closed`, a path that is not a single IRI, or a + second kind of target, is named in the response and left out. It is a report, not an error. A + shape the rules above would refuse fails the whole request before anything is written. +- Shapes are left out of the OWL graph projection. They do not change what the ontology means, so + the graph and its disjointness and hierarchy checks stay as they were. + +## Consequences +A file with constructs the model does not hold still gives its owner the supported part at once, +and the response lists what to do by hand, which refusing the file would not. The cost is that the +imported shape can be weaker than the file's: the report is the only record of the difference, and +exporting does not bring the lost constructs back. Widening the model later adds fields and +reports fewer constructs; it does not change a stored id. A literal written with no datatype and +one written as `xsd:string` are the same RDF term, so an export and an import give the first form. + +## Amendment + +A shape names classes and properties, so the reference index holds them: the `targetConcept` and +each `classIri` as `CLASS_EXPRESSION` references and each constraint `path` as a `PROPERTY` +reference. A class or property that a live shape names cannot be deleted. The request returns 400 +and names up to three of the shapes, and `GET /v1/ontologyConcepts/{id}/deleteImpact` lists each +such shape under `blockers`. Deleting or editing the shape first lifts the refusal. Saving stays +lenient: a shape may name a class or property that is declared a moment later, and declaring or +editing a definition never validates the shapes that name it, because one shape with a second +missing reference would then block an unrelated declaration. Capture still fails a dangling shape. + +Shapes import through their own endpoint until change sets carry shape operations. The native +import (ADR:2026-10-19-native-ontology-imports-use-working-drafts) returns a change set for review +before anything is written. This endpoint writes the working draft directly, as saving one shape +does, and takes the same bounds as that import: at most 1,000 shapes, 100,000 statements and +10 MiB, and 30 seconds of parsing, with no relative identifiers or named graphs. It checks every +shape against the entity name rules and the shape rules before it writes anything, and refuses the +whole file with 400 if one fails; a name is never cut to fit, except that the suffix which tells +two equal names apart is fitted to the 256-character limit. The writes then run in one transaction +under the ontology's lock, so a failing request leaves the draft as it was. A `dryRun` request +writes nothing. + +Reading a file reports, rather than guesses at, more than it did. A predicate that holds more than +one value (`sh:class`, `sh:datatype`, `sh:pattern`, `sh:minCount`, `sh:in`, `sh:name` and the +others) is reported under its own name, and the value first in lexical order is kept so the same +file always reads the same. A language-tagged literal in `sh:in`, `sh:minInclusive` or +`sh:maxInclusive` is reported and its constraint left out, because the model holds no language +tag. An `sh:in` list is read cell by cell, at most 1,000 of them, and a list that loops, ends +without `rdf:nil`, lacks a link or is longer is reported and its constraint left out. + +A shape holds at most 200 constraints and at most 1 MiB of JSON, the member limit every other +definition meets, and both are checked when it is saved. A shape beyond either was already unable +to be captured. The table is created by the 2.2.0 migration, because 2.1.0 has shipped. A step in +that release adds `ontologyShape` to the seeded author and reviewer rules of an installed +catalog, since a seeded policy is created only when it is missing. diff --git a/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md b/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md new file mode 100644 index 000000000000..2344f4fc5ef9 --- /dev/null +++ b/docs/decisions/2026-11-22-a-count-is-exact-or-absent.md @@ -0,0 +1,153 @@ +# A record or link count comes from the stored profiles when they are exact, and is absent when they are not + +- **Status:** Accepted +- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-22 (a class cut by the first read is read again, a deleted table holds no join, a distinct count taken after a transform is not exact); v3 2026-11-23 (a table profiled through a dataframe or from catalog statistics, including SAS, gives no exact count, and the second-read and limit paragraphs say what they do) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyCountRulesTest`, `NativeOntologyDataGraphCountIT`, `NativeOntologyDataGraphCountBoundIT`, `IndependentOntologyTableBindingIT` +- **Related:** ADR:2026-11-21-graph-table-assets-carry-latest-profile-facts (the profile facts this record does not reuse), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, subject key and joins that a count reads), ADR:2026-11-22-record-statements-start-from-the-identity-table (the identity table and the join that a count follows) + +## Context + +The graph of an ontology draws a class for each bound concept and an edge for each relation. A +reader wants to know how many records a class has and how many links a relation has. A number that +is wrong is worse than no number, so the number must come from stored facts that settle it, and +nothing may be sent to the database that a bound table lives in. + +A table profile has a `rowCount`, but it is not always counted. Where an engine's catalog holds a +row count, the profiler stores that figure and runs no `COUNT(*)`. On Postgres it is `reltuples` +and on MySQL `TABLE_ROWS`, and both are estimates. The column metrics `valuesCount`, `nullCount` +and `distinctCount` are different: the profiler counts them with a query over the rows it read. +Those rows are the whole table, a sample, a partition window or the result of a custom query. A +connector can also write a profile of its own, from the catalog's statistics, and a count in it is +not a count over the rows. + +## Decision + +**`rowCount` is never used.** Every count comes from the metrics of columns. + +**The response carries a count or the reason for none.** `NativeOntologyCount` has a `state`, and +`value` and `profiledAt` exactly when the state is `exact`. A cluster has `records` and an edge has +`links`. + +| State | Meaning | +|---|---| +| `exact` | the stored profiles give the number | +| `noIdentityTable` | the class binds tables and none is its identity table | +| `identityTableHidden` | the identity table is deleted, or the reader may not view it; one state answers both, so it says no more than a statement about the class does | +| `noProfile` | the reader may not view the data profile of the table, or the table has no stored profile; the two are not told apart | +| `joinNotConfirmed` | the relation has a join onto the identity table of the related class and it is only inferred; this wins over `noJoin` | +| `noJoin` | the relation has no join onto it | +| `notDerivable` | any other rule below fails: the stored profiles cannot give the exact number and a query over the table could | + +A class that binds no table has no `records`. An edge whose first class the page does not hold has +no `links`. A name, id or column path of a hidden table is never in a count. + +**A column's metrics covered the whole table** when the latest table profile and the latest column +profile have one timestamp, and the table profile records no sample, a `PERCENTAGE` of 100 or more, +or a `ROWS` cap that the column's `valuesCount` plus `nullCount` stays below, and the table has no +`tablePartition`, and its profiler configuration names no `profileQuery` and enables no +partitioning. + +**A declared key counts only on an engine that checks it.** Postgres, Timescale, Cockroach, +Greenplum, MySQL, MariaDB, SingleStore, SQL Server, Azure SQL, Oracle, Db2 and SQLite check a +declared primary or unique key. Snowflake, BigQuery, Redshift, Databricks, Unity Catalog, Synapse +and Fabric store one and do not, so a duplicate row would make a count wrong with nothing to say +so. The list is in `OntologyCountRules`. + +**A key is unique** when its column is alone in the key, its metrics covered the whole table, and +`distinctCount` equals `valuesCount`; when those metrics exist the catalog is not asked, and a +difference means not unique. Otherwise it is unique when the catalog declares a primary or unique +table constraint whose columns are all in the key, or a primary or unique column constraint on one +of them, on an engine that checks it. **A key column has no nulls** by the same order: its metrics +when they covered the table (`nullCount` of 0), otherwise a `NOT_NULL` column constraint, or a +primary key on an engine that checks it. + +**Records of a class** need an identity binding with no row filter on a table the reader may view +and may view the data profile of. A key of one column counts `distinctCount` of that column when +its metrics covered the table and the profiler did not count its distinct values after a transform +(next paragraph). A key of several columns needs the key to be unique, every key +column's metrics to have covered the table and at most one key column to hold nulls. The count is +`valuesCount` of that column, or of any key column when none holds nulls. + +**A distinct count taken after a transform is not exact.** The profiler counts +`count(distinct(CountFn(column)))`, and `CountFn` changes the value first for some column types. On +SQL Server, Azure SQL, Synapse and Fabric (one `mssql` dialect) a `TEXT`, `MEDIUMTEXT` or `NTEXT` +column is cast to `nvarchar` with no length, which keeps 30 characters, and an `IMAGE` column is +cast to `varbinary` with no length, which keeps 30 bytes, so two values that share that prefix +count once. On Oracle a `BYTES`, `BYTEA`, `BINARY`, `VARBINARY` or `BLOB` column is counted as +`DBMS_LOB.GETLENGTH(column)`, so the count is the number of distinct lengths. The records of a key +of one column of such a type on such an engine are `notDerivable`. The list is in +`OntologyCountRules`, with the profiler functions it comes from. On the SQL path only, +`valuesCount` and `nullCount` are not changed by any transform, because a cast or a length of a +null is null and of a value is never null, so a link count, which reads those two and asks +`distinctCount` to equal `valuesCount`, and a count of a key of several columns, which reads +`valuesCount`, are as exact as before on that path. + +**A table profiled through a dataframe gives no exact count.** Datalake and BurstIQ tables are read +in chunks, and the profiler casts every chunk to the column types of the catalog before it counts. +A null in a string column becomes the text `'None'` or `'nan'`, in a bytes column `b'None'` and in +a boolean column `True`, so `nullCount` falls to 0 and `valuesCount` and `distinctCount` count the +nulls. Every records or links count that reads a profile of a table of these service types, which +is a key on the identity table or a child column of a join, is `notDerivable`. The service types are the ones whose profiler is +`PandasProfilerInterface` or a subclass of it, and the list is in `OntologyCountRules` with the +profiler code it comes from. + +**A table whose counts can come from a catalog's statistics gives no exact count.** Trino and +StarRocks tables are profiled by a profiler that, when the pipeline sets `useStatistics`, takes +`distinctCount` and `nullCount` from the engine's statistics: `SHOW STATS`, a rounded null +fraction, and a HyperLogLog estimate. The SAS connector writes the column profiles itself, from the +SAS catalog (`ingestion/source/database/sas/metadata.py:468-488`): `missingCount` becomes +`nullCount`, `cardinalityCount` becomes `distinctCount`, and the table's `rowCount` becomes +`valuesCount`, so `valuesCount` counts the null rows. The stored profile does not say which path +made it, a pipeline's setting can change after a run, and a run can come from outside a pipeline, +so no table of these service types gives an exact count, whatever the setting. The rule is the one above, with +its own list in `OntologyCountRules`. A stored marker of where a count came from would let these +tables give exact counts again. + +**Links of a relation** need the join that `OntologyRelationPath.lookup` finds for the relation +onto the identity table of the related class, confirmed and held by the identity binding of the +first class. A join held by a contributing table gives no count, and a contributing table that does not exist +holds no join, as in the statements of the mapping. The join's parent columns are the +related class's subject key in order. A join target must sit in the bound table's database +(`IndependentOntologyTableBindingIT`), so one service type covers both tables. Neither identity binding has a row filter. The key of the +first class is unique and holds no nulls. The metrics of every child column covered the whole table +and at most one holds nulls. The count is `valuesCount` of that child column, or of any child +column when none holds nulls. It counts non-null references, so a reference that matches no row of +the related table still counts. The reader needs the data profile right on the first class's table +and the right to view the related class's table. + +**The counts are read again for each response, with one read for each kind.** One statement reads +the binding rows of all classes of the response, with the identity row of each class first and at +most five rows for each class. The +identity tables come from one batch read with their columns, constraints, partition and profiler +configuration. One statement reads their latest table profiles, and one reads the latest column +profiles of their key columns and join columns. A page of 60 classes and 500 edges runs those four +reads and no query for a class or an edge. + +A class whose first read reached five rows may bind more tables, and a table not read could hold +the join of a relation. When a relation's first class is cut that way, its identity table is +visible and has a profile, and the rows read hold no confirmed join for the relation, the class is +read again as the statements of the mapping read it: its identity row and its contributing rows, at +most 33, in one statement for each group of 14 such classes, so that no scan maps more than 500 +rows. A class whose identity binding has a row filter is read again in the same way, because the +state of its join does not depend on the filter, and reading it keeps that state independent of the +number of tables the class binds. A page where no class is cut runs no such statement. A page of 60 +classes of which every one is cut runs five. A class over the 32 contributing tables that a +statement accepts has no state for its join and its links are `notDerivable`. Its records, and its +links when its identity table holds a confirmed join, keep the counts its identity table gives, +although the statements of the mapping refuse the class: that limit bounds a statement and does not +change what the identity table holds. Because of this read, the state of `links` never depends on +how many tables the first class binds. Nothing is stored and nothing is cached. The counts are +not part of `contextDigest`, so a count changing between two pages never refuses a cursor. + +## Consequences + +A client shows a number only when the state is `exact`, and shows what is missing otherwise. + +A profile taken by a workflow that runs outside the platform can use a partition or a query that +neither the table nor the profile records. A count from such a profile covers that window. This is +a known limit of reading stored profiles. + +A class with a row filter, a sampled or partitioned table, or a key that no metric or enforced +constraint proves unique has no count here. A query over the table is the way to count it, and that +is not part of this record. diff --git a/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md b/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md new file mode 100644 index 000000000000..cedc1b46eedb --- /dev/null +++ b/docs/decisions/2026-11-22-a-declined-definition-is-remembered-by-content.md @@ -0,0 +1,139 @@ +# A declined definition is remembered by its content, and narrowing a draft keeps its classes + +- **Status:** Accepted +- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-26 (canonical form stated in full and made stable for set order, empty lists and server-derived fields; narrowing checks every kept operation; a permanent delete removes the rows; declining asks the draft read right); v3 2026-12-05 (a table binding and a shape can be declined); v4 2026-12-05 (a binding is keyed by its table, role, key and row filter, not its columns) +- **Deciders:** Ontology maintainers +- **Guard:** `OntologyDefinitionDigestTest`, `OntologyDeclinedDefinitionsTest`, + `OntologyDeclinedDefinitionDaoIT`, `OntologyDraftNarrowingTest`, + `OntologyDeclinedDefinitionRightsTest`, `OntologyDeclinedBindingShapeKeysTest`, + `OntologyDeclinedDefinitionIT`, `OntologyDeclinedBindingShapeIT`, + `OntologyDeclinedDefinitionReadIT` and `OntologyRolesMigrationIT` +- **Related:** ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights + +## Context +A tool that proposes definitions builds a draft change set, and a person keeps some of its +operations and discards the rest. Discarding keeps the draft's operations, but nothing reads them, +so the next draft proposes the same definition again. A tool cannot tell a definition that was +declined from one that was never proposed. + +A person can also narrow a draft to a subset of its operations. Nothing checked the subset, so a +property kept without the class that only a removed operation creates was accepted, and the failure +came when the draft was applied. + +## Decision +**A record of declined definitions.** Table `ontology_declined_definition` holds one row per +declined definition. Its key is the ontology id, the operation type, the SHA-256 of the +definition's IRI and the payload digest. A row also keeps who declined, when, an optional reason, +the change set and the operation the definition came from. + +**The digest.** The payload digest is the lower-case hexadecimal SHA-256 of the UTF-8 bytes of the +definition's canonical JSON, built by `OntologyDefinitionDigest` in these steps, in this order: + +1. **Round trip and defaults.** Write the definition to JSON without its null fields, read that + back into its own type, and write it again. A field that was `null` or left out takes the + schema's default, so the two give one digest. The defaults that carry a value are, for a + concept: `deleted` false, `provider` "user", `abstract` false, `deprecated` false and + `conceptType` "BOTH"; for a property: `deleted` false, `provider` "user", `isIdentifier` false + and `deprecated` false; for an axiom: `deleted` false, `provider` "user" and `provenance` + "Manual". Every list a schema defaults has the default `[]`. +2. **Dropped fields.** Remove these top-level fields: `id`, `version`, `updatedAt`, `updatedBy`, + `href`, `changeDescription`, `incrementalChangeDescription`, `impersonatedBy`, + `lifecycleStatus`, `superClasses` and `subClasses`. A tool makes a fresh id on every run, and + the server sets the next five on every write. The last three are `readOnly` in the schema and + derived from other rows: the superclasses and subclasses from the subclass axioms, the lifecycle + status from the ontology's releases. A parent class a person sets stays in the digest through + the axiom's `targetIri`, and a property's `superProperties` is a field a person sets, so both + stay. +3. **References.** Reduce the `ontology` reference and each entry of `owners` to its `id` and + `type`, because the other fields of a reference (name, display name, description, `href`) change + when something is renamed or served by another route. +4. **Empty values.** Remove every field whose value is `null` and every field whose value is an + empty array, at any depth, so `owners: []` and a missing `owners` agree. +5. **Order.** Sort object keys by their code points at every depth. An array keeps its order, + except the arrays the schema marks `uniqueItems`, which are sets: at the top level of a concept + `synonyms`; of a property `domain`, `range`, `enumValues`, `characteristics`, `disjointWith` and + `superProperties`; of an axiom none. Sort the elements of a set by the compact JSON text of each + element and drop duplicates. `propertyChain` and an axiom's `expressions` are ordered, and keep + their order. +6. **Numbers.** Write a number as its decimal value with trailing zeros removed, in the form of + Java's `BigDecimal.toString`: `1.50` is `1.5`, and `10` is `1E+1`. +7. **Text.** Write compact JSON, with no space after `:` or `,`, strings in UTF-8 with no `\u` + escapes except where JSON requires them, and hash those bytes. + +The canonical text of the class `Order` in the unit test is +`{"abstract":false,"conceptType":"OWL_CLASS","deleted":false,"deprecated":false,"description":"A purchase a customer placed","displayName":"Order","fullyQualifiedName":"sales.Order","iri":"https://example.org/sales/Order","name":"Order","ontology":{"id":"00000000-0000-0000-0000-0000000000a1","type":"ontology"},"provider":"user"}` +and its digest is `d1bef0ebba86898d77e8b761c7d6c1c67a6de316a2d48a8e1595a714077b991b`. The data +property `total` of the same test gives +`dede90b4844e19579b0fc16accf3937493626d37d4cc668960eb95bdece30d10`. + +Only the server computes digests. A client never canonicalizes JSON. A definition that changes in +any other field gets a new digest, so it no longer matches and is proposed again. + +**The IRI of a definition.** A concept or a property uses its `iri`. An axiom has none of its own, +so it uses its `subjectIri`, and several axioms of one subject differ by digest. An operation that +carries no definition, such as a delete, cannot be declined. + +**A table binding and a shape.** An `UPSERT_BINDING` operation stands under the binding's class +IRI, and an `UPSERT_SHAPE` operation under the shape's `targetConcept`. A binding's digest is the +SHA-256 of the canonical JSON of the binding's table, role, `subjectKey` and row filter. The class +stays out, because a record keeps it as its IRI, and so do the columns and their joins. A reviewer +who rejects a binding rejects mapping that class to that table with that key and filter, and a +declined binding must stay declined when the same review declines one of its columns: a tool +that cuts the declined property or relation builds the binding without that column, and a digest +over the columns would then no longer match. A binding that differs only in which columns it maps +is the same declined binding. Another table, role, key or filter is another binding. The steps 1, 4, +6 and 7 above apply, with keys sorted. A binding with no role and one whose role is `null` or whose +`subjectKey` is empty give one digest. The `subjectKey` keeps its order, because a contributing +table pairs its key with the identity table's by position. A shape's digest is the SHA-256 of the canonical +JSON of its constraints alone, in authored order, so a fresh id, name or description does not +change it and another constraint does. A changed binding or shape does not match. The digests of +the test fixtures are pinned in `OntologyDeclinedBindingShapeKeysTest`. + +**Endpoints**, under `/v1/ontologies/{id}/declinedDefinitions`: + +- `POST` declines operations of one change set, named by change set id and operation ids, with an + optional reason. The server reads the stored operations and writes one row each. A definition + declined before keeps its first row, so declining twice changes nothing. It answers with the IRI + and digest of each operation, so it asks the same right as reading the draft, in this order: + edit on the change set, then edit on the ontology that owns the change set (the draft read + right), and only then does it read the operations or write a row. The check that the change set + belongs to the ontology in the path comes after the read right, so a caller who may not read the + draft is refused as the read is and learns nothing from a mismatch. +- `GET` lists rows oldest first, in pages of at most 1000 with an opaque `after` cursor. It needs + the right that reads the ontology's working-draft change sets, which is edit on the ontology + (ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights), asked on the ontology in the + path. +- `POST .../match` takes up to 1000 candidate operations and returns, for each in order, whether a + row matches its type, IRI and digest, with the digest and the row. It asks the same right as + `GET`, edit on the ontology. + +**Narrowing.** `PUT /v1/ontologyChangeSets/{id}/operations` refuses a native draft with a 400 when +an operation it keeps needs a class that only a removed operation of the same draft creates. The +message names the class IRIs. The needs are the class positions preflight computes, plus the IRIs +in `requiresConceptIris`. Every kept operation is checked, not only the ones before the undo cursor, +because a redo moves the cursor forward and makes a kept operation active. The operation at index +`i` of the kept list is active together with `kept[0 .. max(i + 1, cursor))`, so each class it needs +must be created in that prefix, be a vocabulary class or a datatype, or be one the ontology already +declares. A class that a stored operation created and the prefix does not create is refused. When no +kept operation creates it, the message says that only removed operations create it. When a kept +operation creates it past the prefix, the message says that only kept operations past the undo +cursor create it, and asks to move the cursor past that operation. A class that nothing in the draft +creates is left to the check at apply, as before. + +## Consequences +A tool matches its next draft against the rows and leaves out what a person declined, and brings a +changed definition back. The rows do not expire, and no endpoint removes one, so a definition can be +proposed again only by changing it. A later change can add removal if people need it. + +The digest covers server defaults too: a field that gains a default in a later release changes the +digest of every definition declined before it. Revisit the canonical form before adding such a +default. + +A permanent delete of an ontology removes its rows in the same transaction, after the check for +retained releases. A soft delete keeps them, and a restore serves them again. + +Narrowing costs one read of the ontology's declared classes when a stored operation created a class +that a kept operation needs and its prefix lacks, and one scan of the kept operations for each +distinct prefix length, which the limit of 1000 operations bounds. The undo and redo endpoints move +the cursor by one operation and are not checked, because a narrowing that passed leaves every +cursor a redo can reach applicable. diff --git a/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md b/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md new file mode 100644 index 000000000000..5dd2f02ad773 --- /dev/null +++ b/docs/decisions/2026-11-22-an-ontology-change-set-can-carry-table-bindings-and-shapes.md @@ -0,0 +1,182 @@ +# An ontology change set can carry table bindings and shapes + +- **Status:** Accepted +- **Revisions:** v1 2026-11-22 (initial); v2 2026-11-22 (every path that returns operations asks for the draft read right, and a save is refused when the writer's sight changed since its read); v3 2026-11-22 (every endpoint that acts on a change set asks that right, and a stored change event holds no operations, and records that a masked field changed without its values) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyBindingAndShapeOperationTest`, `OntologyDraftPreflightTest`, `OntologyBindingChangeExecutorTest`, `OntologyChangeApplicationServiceTest`, `OntologyChangeEvidenceViewTest`, `OntologyChangeSetBindingIT`, `OntologyChangeSetEvidenceIT`, `OntologyChangeSetEvidenceMcpIT`, `OntologyChangeSetDraftReadIT`, `OntologyChangeSetDraftReadMcpIT`, `OntologyChangeSetSaveSightIT`, `RdfOntologyChangeSetViewIT`, `RdfExcludedEntitiesTest`, `PatchEntityToolTest`, `OntologyChangeSetCommandReadIT`, `OntologyChangeSetEventDeliveryIT`, `OntologyChangeSetEndpointRightsTest`, `OntologyChangeSetReadAccessTest`, `ChangeEventMaskingTest`, `OntologyChangeEventPublisherTest` +- **Related:** ADR:2026-10-19-native-concept-bindings-remain-operational-metadata (amended by this + record), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records, + ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints, + ADR:2026-10-26-masked-fields-stay-out-of-change-events-and-version-history, + ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights + +## Context + +A change set carries classes, properties and axioms, and a person reviews and applies it as one +draft. A table binding and a shape were each written through their own API, one request at a time +and outside any draft. A draft that proposed a class could therefore not show, beside it, the table +that holds its records or the constraints those records should meet. Whoever applied the draft +wrote those afterwards, and a refusal then left the class in place without them. + +A reviewer also could not see what a proposed operation rests on. Whatever names the tables behind +a proposal must not name a table to a reader who may not view it. + +## Decision + +**Two operation types, `UPSERT_BINDING` and `UPSERT_SHAPE`.** Neither has a delete type. + +- `UPSERT_BINDING` carries `binding`, which is + `{classIri, tableId, role, subjectKey, rowFilter, columns: [{propertyIri, columnPath, join}]}`. + It names its class and each property by IRI, so it can name a definition that the same change + set creates, and it names its table by id. `role`, `subjectKey`, `rowFilter` and the columns mean + what they mean on a stored binding + (ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records). Applying it adds or replaces + that one table's binding of the class and keeps the other bindings of the class. A change set + writes each pair of class and table once. +- A `join` in a binding operation is `{targetAssetId, on}` and has no status. The server stores it + as `inferred`, also when it replaces a join that a person had confirmed. Only the bindings API + stores `confirmed`. +- `UPSERT_SHAPE` carries `shape`, a shape as the shape API stores it, and may carry `basis`, which + is `declared` or `observed`. +- A binding operation needs its class and a shape operation needs its target class. + `requiresConceptIris` orders both after the class operations they need, as it orders a property. + +**Any operation may carry evidence.** `evidence` is a list of at most 20 entries. Each entry is +`{tableId, columns, kind}`: one table, optionally up to 32 column paths of it, and a `kind` out of +`declaredKey`, `storedJoinCount`, `testCase`, `lineage`, `profile`, `name`, `sampleData` and +`measured`. Evidence is what the author says the operation rests on. The server never acts on it +and checks only that its author may view the table. + +**Evidence passes through the view of the caller in both directions.** Every response that carries +operations leaves out each entry whose table its caller lacks `ViewBasic` on, and sets +`withheldEvidenceCount` on every operation that stores evidence. A deleted table is withheld from +every caller. The stored operation keeps every entry. "Every response" means every endpoint of the +change set resource, the versions it serves and the MCP tool that reads an entity. + +The paths that return the operations of a change set, or act on one, and the right each asks. +`OntologyChangeSetEndpointRightsTest` lists every endpoint of the resource, inherited ones included, +so a new endpoint fails it until its right is written down. + +- The draft read right is `EditAll` on the ontology the change set targets, or on each glossary it + targets. It is asked by: get, list (for every row), versions and one version; the history + listing, which keeps only the snapshots of change sets the caller may read and drops the rest + with a 200; undo, redo, discard and the save of operations (with or without operations), each + before the edit right on the change set and before the lease; soft delete, hard delete and + restore, before their own rights; and the endpoints of the lease (take, renew, read, release), + because a holder who may not read the draft could otherwise block its editors. Submit and apply + ask `EditAll` on the same scope. The AI context endpoints ask `ViewAll` and answer with no + operations. A refusal is a 403 with the text the get gives, and nothing is written. +- The audit log, read for one change set: the same draft read right, asked after `ViewBasic`, and + the rows returned are those whose entity id is the change set that holds the name now, because a + name freed by a hard delete can be taken by another draft. A change set that is deleted is still + checked, and one that cannot be loaded leaves only the audit-log permission. A request that names + the change set type and a service name is treated the same way, because the events of a change + set carry its own name as their service name. A caller who holds the audit-log permission reads + every row. The export needs the audit-log permission. +- The MCP tool that reads an entity, in each call shape: the same draft read right, then the + evidence masked per reader. +- The RDF view and the knowledge graph: a change set is not in them. It is excluded from the + projection and from its relationship edges, and the RDF endpoint for one entity refuses the type. + A graph built before this record can still hold change sets. A full recreate of the RDF index + removes them, and a reindex without a recreate does not. +- Change events, recorded changes and stored versions: a stored change event holds no operations, + neither in its entity nor in the old and new value of a recorded field change. An event reaches + every subscriber, every destination and the audit log, and when the server stores it, it cannot + know who will read it. The operations stay readable through the get and the versions, which ask + the draft read right. A stored version is masked when it is read. + +No other endpoint returns the operations of a change set. Entity versions, feed and activity, +lineage, search and the generic entity readers carry no operations of a change set. + +The MCP tool that patches an entity refuses a change set. A JSON Patch can copy a stored entry into +a member that every reader is shown, and the change set resource itself offers no patch. + +A save through the change set resource stores the entries its writer sends about tables the writer +may view, and keeps the stored entries the writer was not shown, each in its place. It stores no +entry about a table the writer may not view. Storing one would repeat a withheld entry, and merging +the repeat would tell the writer what is withheld. + +A client sends back the `withheldEvidenceCount` that it read on each operation. When it is present +and differs from the number the stored operation withholds from that writer now, the save is a 412 +that names the operation and tells the writer to read the change set again. Without this, a writer +who read an operation while a table was hidden from it, and saved after the table became visible, +would send an operation that omits an entry it could now see, and the save would remove that entry. +An operation that sends no count is not checked. One case is not caught: a table becomes visible to +the writer while another becomes hidden, so the two counts agree. The save then stores the entries +the writer sent about tables it can view and keeps those it cannot, and the entry that became +visible stays in the draft as the stored operation holds it. + +`operations`, `evidence` and `withheldEvidenceCount` are masked fields +(ADR:2026-10-26-masked-fields-stay-out-of-change-events-and-version-history), so no stored change +event holds them. A stored event records that a masked field changed and never its values: the +recorded field change of a field masked as a whole, or of a path under it, keeps its entry and its +`name` and loses its `oldValue` and `newValue`, for every entity type, in the event and in the +entity it carries. An alert that matches on a field name, and a workflow trigger that does, keep +working. The versions of a change set keep `operations`, because they are its content and +the endpoints that serve them ask the draft read right, and the recorded change of `operations` in +a version holds the operations without their evidence. A save that changes evidence alone is stored +without a new version. + +**A save checks what an operation names, and an apply checks what its caller may do.** + +- Creating a change set and replacing its operations check, with nobody's rights, that every IRI + is absolute, that the class of a binding and each property it names is declared in the ontology + or created by an earlier operation, that the target class of a shape is declared, created by an + earlier operation or a class of a standard vocabulary, that the table, each join target and every + column a binding names exist, and that the binding passes the binding rules that read only its + own fields. A failure is a 400 that names the operation. +- Applying runs every check of a binding write again as the caller who applies: `EditAll` on the + class, `ViewBasic` on the table, `ViewSampleData` for a row filter the write sets or changes, the + right to view a join target, the mapping source of the ontology, and the data type of a row + filter value. The rights of whoever built the change set play no part. A refusal answers with the + status of the check that failed, rolls back every write of the change set and leaves the change + set in the state it was in. +- A background job that applies a change set has no caller, so it refuses a binding operation. + +**A binding operation says which binding revision it was built against.** `baseVersion` holds the +binding revision of the class that the author read. It is absent when the table was not bound to +the class. Under the ontology lock, an apply refuses with a 412 an operation that carries no +revision while the table is bound, and an operation whose revision is not the one the class had +before this apply wrote its first binding. The message names the class, the table and the +operation, so a client can rebuild that one operation. Every operation of a change set is judged +against the revision before the apply, so two of them can change two tables of one class that the +author read together. An operation that repeats the stored binding writes nothing and is not +judged. + +A binding operation writes through the step that checks and saves every binding row, inside the +transaction of the apply, which already holds the ontology lock. It takes no other lock. + +## Consequences + +A draft can propose a class, its properties, the table that holds it and the shapes it should meet, +and a reviewer applies or discards all of it at once. Discarding writes nothing. + +A binding write changes no definition, so it does not move the working revision of the ontology, +and a change set stays applicable while others edit bindings. `baseVersion` alone guards its +binding operations. That revision counts every binding of the class, so a change to another table +of the same class also makes an operation stale. The cost is a rebuild that the author did not +need. A revision for each table would remove that cost and needs a migration. + +The save checks read the catalog with nobody's rights. An author who knows the id of a table can +therefore learn from a refusal whether the table and a named column exist. The alternative is a +draft that only someone who may view every table it names can save. That rule would tie a review +to the rights of the author. + +The fields of a binding operation are part of the operation, and every reader who holds the draft +read right sees them, the table id, the key columns and the row filter among them. They are not +masked, for this reason: the same draft declares the classes and properties that were made from +those tables, so it already says what the columns are, and the bindings API hides a stored binding +and not a proposal. The table id is opaque. Applying still checks the rights of whoever applies. +Every endpoint that returns them or acts on the change set asks for the draft read right +(ADR:2026-11-03-ontology-working-draft-reads-require-edit-rights), and no stored event holds them, +so a user who may only view change sets, or who subscribes to events, learns none of it. + +An author cites only tables it may view. A service that drafts with wider rights than the person it +drafts for therefore saves the draft itself, and that person then reads it through their own view. + +A person's confirmation of a join is lost when a later operation writes that join again. Revisit +the rule when operations rewrite bindings that people maintain by hand. An operation could then +keep the status of a join it does not change. + +A binding or a shape is still removed through its own API. Add delete operation types when a draft +has to retire one. diff --git a/docs/decisions/2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text.md b/docs/decisions/2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text.md new file mode 100644 index 000000000000..45a0ec875d06 --- /dev/null +++ b/docs/decisions/2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text.md @@ -0,0 +1,178 @@ +# Generated SQL keeps typed values apart from its text + +- **Status:** Accepted +- **Revisions:** v1 2026-11-22 (initial) · v2 2026-11-22 (finished text comes in a form to read and a form to run) · v3 2026-11-24 (statement text takes the tilde) · v4 2026-11-24 (how a pattern is written into the statement) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologySqlValueCasesTest`, `SqlEngineFamilyTest`, `TypedValuesTest`, `TypedStatementTest`, `OntologyConceptSqlGeneratorTest`, `OntologySqlLiteralIT`, `OntologyRowFilterValueIT`, `OntologyConceptQueryIT` +- **Related:** ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension (two of its rules + are replaced here), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (amended by + this record) + +## Context + +The server writes the `SELECT` that the table bindings of a concept describe +(ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension). That statement held names +only. A table binding can carry a row filter +(ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records), so a statement now compares a +column with a value that a person typed. A statement can also compare a column with a record key or +with search text. + +A value concatenated into SQL text is how SQL injection happens. One escaping rule cannot prevent +it here, for three reasons. + +- Engines read a string differently. MySQL, BigQuery, and Snowflake read a backslash as an escape. + Trino and SQL Server read it as a backslash. Postgres reads it either way, depending on a server + setting. Spark and BigQuery do not read two quotes as one quote. +- The six dialects of the response are too coarse. Postgres, Redshift, and Trino share `ansi` and + need three string rules. ClickHouse shares `mysql` and reads a backslash inside a backtick name. +- A consumer can pass the finished text to a library that reads `:name` as a bind parameter. A + colon in a value or in a name would then start a parameter. + +A value of the wrong type is a separate problem. `1 OR 1=1` is not a number, and no escaping rule +should decide what an integer column does with it. + +## Decision + +**A value reaches generated SQL only as a `TypedValue`.** `TypedValues` is the only code that makes +one. It parses a value as the data type of its column. A value that does not parse is a 400 that +names the column, the data type, and what the data type expects. A `TypedValue` holds the data type +of the column, the parsed value, and the text that the value arrived as. SQL is written from the +parsed value only. + +| Data types | A value is | Written as | +|---|---|---| +| `TINYINT`, `BYTEINT`, `SMALLINT`, `INT`, `BIGINT`, `LARGEINT` | ASCII digits with a leading minus sign when negative, no leading zeros, inside the range of the type | the digits | +| `DECIMAL`, `NUMERIC`, `NUMBER`, `FLOAT`, `DOUBLE` | the same with at most one decimal point and no exponent | the digits | +| `VARCHAR`, `CHAR`, `STRING`, `TEXT`, `MEDIUMTEXT`, `ENUM` | a string or a number | a string of the engine family | +| `BOOLEAN`, `BIT` | JSON `true` or `false` | `TRUE` or `FALSE` | +| `DATE` | `YYYY-MM-DD`, a real calendar day | `DATE '…'` | +| `TIME` | `hh:mm:ss` with at most six fraction digits | `TIME '…'` | +| `TIMESTAMP`, `TIMESTAMPZ`, `DATETIME` | a date, then `T` or a space, then a time, with no offset | `TIMESTAMP '…'`, the date and the time separated by a space | +| `UUID` | 32 hexadecimal digits in groups of 8, 4, 4, 4, and 12 | a string in lowercase | + +A column of any other data type takes no value. The request is a 400, "SQL generation does not +support column type of column ". A value takes at most 1,024 characters, whether it +arrives as a string or as a number. A list takes at most 100 values, and search text at most 256 +characters. No value holds an ISO control character. + +**A statement is a `TypedStatement`.** It is an ordered list of parts of four kinds: text that the +code wrote, names that the catalog holds, typed values, and text to search for. Statement text +takes only letters, digits, spaces, line breaks, and `_ , . ( ) * = < >`. It can therefore open no +string, quoted name, parameter, or comment, and no code path can put a value into it. + +**An `SqlEngineFamily` writes the statement, and it is the one place where a value becomes text.** +`inline` returns finished text. `bind` returns a `BoundStatement`: the text with `:p0`, `:p1`, and +so on where the values go, and the values in that order. A family is the set of engines that read a +name, a string, and a `LIKE` pattern the same way. Every service type keeps its dialect, and a +service type that no family lists is still a 400. + +| Family | Service types | Dialect | Name | String | `LIKE` pattern | +|---|---|---|---|---|---| +| `postgres` | Postgres, Timescale | `ansi` | `"…"` with a `"` doubled, when the name is not lowercase `[a-z_][a-z0-9_]*` or is a reserved word | `'…'` with the quote doubled. `E'…'` with the backslash doubled too when the text holds a backslash | `!` before `!`, `%`, and `_`, then `ESCAPE '!'` | +| `redshift` | Redshift | `ansi` | as `postgres` | the backslash and the quote doubled | as `postgres` | +| `trino` | Trino, Presto, Athena | `ansi` | as `postgres` | the quote doubled | as `postgres` | +| `mysql` | Mysql, MariaDB, SingleStore, Doris, StarRocks | `mysql` | backticks, a backtick doubled | the backslash and the quote doubled | `\` before `\`, `%`, and `_`, no clause | +| `clickhouse` | Clickhouse | `mysql` | backticks, a backslash doubled, a backtick as `` \` `` | as `mysql` | as `mysql` | +| `bigquery` | BigQuery | `bigquery` | as `clickhouse` | the backslash doubled, the quote as `\'` | as `mysql` | +| `snowflake` | Snowflake | `snowflake` | `"…"` with a `"` doubled, always | the backslash and the quote doubled | as `postgres` | +| `spark` | Databricks, UnityCatalog, Hive, Impala, Iomete | `spark` | as `mysql` | as `bigquery` | as `mysql` | +| `tsql` | Mssql, AzureSQL, Synapse, MicrosoftFabric | `tsql` | `[…]`, a `]` doubled | `N'…'` with the quote doubled | as `postgres`, with `!` before `[` too | + +Three families write a value another way. T-SQL has no typed literal, so `tsql` writes a boolean as +`1` or `0`, a date as `CAST(N'…' AS date)`, a time as `CAST(N'…' AS time)`, and a timestamp as +`CAST(N'…T…' AS datetime2)`. `bigquery` writes the value of a `DATETIME` column as `DATETIME '…'`. +`trino` writes a UUID as `UUID '…'`. + +**Four rules hold for every family.** + +- Finished text writes every colon as `\:`, inside a name and inside a string too. The bound form + writes every colon as `\:` except the colon that starts a parameter. +- A name that holds a control character is a 400 when the statement is built. +- A relation label is never part of a statement. The `JOIN` lines carry no comment, and the + response returns each label in `hops`. +- A statement applies the row filter of every table it reads. + +**This record replaces two rules of +ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension.** That record says that each +`JOIN` is commented with the relation label, and that the dialect decides the quoting. The label +rule and the family table above replace them. Where that record says that the SQL comment names a +relation, read the label of the hop. Its rules for joins, authorization, and batched reads are +unchanged. + +**A row filter value is parsed twice.** A write that sets or changes a row filter parses each value +as the data type of the filter column. A value that does not parse is a 400, and the write answers +it before it checks `ViewSampleData`. The server stores the value as given. Every statement over +the binding parses the stored filter again, because the column can change its data type or leave +the table after the write. A stored filter that no longer parses is a 400 that names the table. + +## Consequences + +No code path concatenates a value into SQL. A new comparison is a new part of a `TypedStatement`. +A new engine is a row in `SqlEngineFamily` with cases in `ontology/sql-value-cases.json`. Each case +gives a value, the data type of its column, and the exact text or the refusal that one family must +produce. `OntologySqlLiteralIT` sends each string case to MySQL and to Postgres and reads the same +characters back. On Postgres it does so with `standard_conforming_strings` on and off. + +A MySQL server that runs with `NO_BACKSLASH_ESCAPES` reads a doubled backslash as two backslashes. +A value that holds a backslash then compares as a different value there, and a search for text +that holds `\`, `%`, or `_` does not find that text. Each value and each pattern still stays inside +its string, and `OntologySqlLiteralIT` asserts that. + +Finished text is written for a consumer that reads `\:` as a colon. A person who copies a statement +into a console sees `\:` wherever a name or a value holds a colon, as every timestamp does, and has +to remove the backslash. + +A column whose data type is outside the table cannot be compared with a value until someone adds +the written form of that type and its cases. Unsigned, interval, JSON, array, struct, and binary +types are outside it today. A null test takes no value, so it applies to a column of any type. + +A row filter written before this record is not parsed until someone changes it. A statement over a +binding whose stored value does not parse is a 400 until someone fixes or removes the filter. + +Revisit the single finished form if a consumer must send a statement straight to a driver. That +consumer needs the text without the backslashes, and the two forms must not be confused. + +## Amendment + +v2 (2026-11-22): finished text comes in two forms, and `SqlEngineFamily.finish` returns both from +one pass over the statement. `sql` writes every colon as a colon and is the form a person reads. +`escapedSql` writes every colon as `\:`. It is the only form to pass to a library that reads `:name` +as a bind parameter, such as a SQLAlchemy `text()` call. `inline` returns `escapedSql`. Where this +record says that finished text writes every colon as `\:`, read `escapedSql`. + +Only `SqlEngineFamily` writes either form, so the colon rule has one owner. A caller passes both +forms on and never rewrites a statement. + +Every response that carries a statement returns both forms under those two names. The `sql` of +`POST /v1/ontologyConcepts/{id}/query` writes every colon as a colon again, and that response gains +`escapedSql`. A person who copies `sql` into a console no longer removes a backslash. A consumer +that passed `sql` to a reader of `:name` parameters must pass `escapedSql` instead. A consumer that +sends a statement straight to a driver sends `sql`, which answers the last consequence above. The +statements that return both forms are in +ADR:2026-11-22-record-statements-start-from-the-identity-table. + +v3 (2026-11-24): statement text also takes `~`, the operator that matches a regular expression. +Where this record lists the characters of statement text, add `~`. A tilde opens no string, quoted +name, parameter, or comment, so the rule that text can put no value into a statement still holds. +The pattern that the operator matches is a typed value like any other. The one statement that uses +the operator is in ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered. + +v4 (2026-11-24): how a pattern is written into the statement. The pattern of a shape check is a +typed text value, and the family `postgres` writes it with the rule for its strings, which does +not change with the pattern: + +- Text with no backslash is written as `'…'`, with each quote doubled. `^O'Brien$` is + `'^O''Brien$'`. +- Text with a backslash is written as `E'…'`, with each backslash doubled and each quote doubled. + The server reads the string literal first and gets the original pattern back, so the regular + expression engine sees the pattern as the shape states it, whether `standard_conforming_strings` + is on or off. `^a\tb$` is `E'^a\\tb$'`, and the `.` that the check rewrites as `[^\n\r]` is + `E'^a[^\\n\\r]b$'`. `^x'\); DROP TABLE t; --$` is `E'^x''\\); DROP TABLE t; --$'`, so the + quote, the semicolon and the dashes stay inside the string. +- The `E` prefix is the only difference between the two forms. Code does not choose the form by + the pattern's meaning, only by whether the text holds a backslash. +- `escapedSql` also writes each colon of the pattern as `\:`, as it does for any value. A reader of + `:name` parameters removes that backslash before the server sees the statement, so the pattern + that runs holds the colon. + +The pattern is never part of statement text. `~` is, and the pattern follows it as the one value. diff --git a/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md new file mode 100644 index 000000000000..08623366d911 --- /dev/null +++ b/docs/decisions/2026-11-22-record-statements-start-from-the-identity-table.md @@ -0,0 +1,275 @@ +# A statement about the records of a class starts from its identity table + +- **Status:** Accepted +- **Revisions:** v1 2026-11-22 (initial) · v2 2026-11-22 (the aggregate statement gains the link count of a relation) · v3 2026-11-26 (the expand statement orders by the related key and starts after a given key) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyStatementGoldenTest`, `OntologyRecordStatementTest`, `OntologyExpandStatementTest`, `OntologyAggregateStatementTest`, `OntologyLinkCountIT`, `OntologyExpandPagingIT`, `OntologyMappingReaderTest`, `OntologyConceptSqlGeneratorTest`, `OntologyRecordStatementIT`, `OntologyStatementRefusalIT`, `OntologyStatementReleaseDeleteIT`, `OntologyStatementValueIT`, `OntologyConceptQueryIT` +- **Related:** ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles and the subject key that a statement reads), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (amended by this record), ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension (three of its rules are replaced here), ADR:2026-11-21-a-class-has-at-most-one-display-name-property + +## Context + +The server writes the `SELECT` that the table bindings of a concept describe and never runs it. +One endpoint did that, for search-around hops. It started from the first bound table that the +reader may view, so two readers could get rows of different tables for one concept, and a row had +no id that another statement could name. + +A table binding now says how its rows become records +(ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records). One table of a class is its +identity table, and the subject key of that table identifies a record. A client that lists +records, opens one, follows a relation from one, or counts them needs the same record id in every +statement. It also needs to know what each result column holds without reading the SQL. + +## Decision + +**Four endpoints each return one statement about the records of a class.** Each takes its own +request and returns an `OntologyStatementPlan`: one `SELECT` and a column plan. + +| Endpoint under `POST /v1/ontologyConcepts/{id}/statements` | Request | Result columns | Rows | +|---|---|---|---| +| `/find` | optional `matchText` | the key, the display name, then the other bound columns of the identity table | 25 | +| `/open` | `key` | the same, then the bound columns of each contributing table | 100, and one more | +| `/expand` | `key`, `relation`, `direction`, optional `after` | the key of the start record, then the key and the display name of each related record | 25, and one more | +| `/aggregate` | nothing | the number of records | 1 | +| `/aggregate` | `relation`, `direction` | the key and the display name of the records that relate to the most records, each with its count | 8 | + +**A record is a row of the identity table.** Its subject key holds no null, and the row filter of +the binding keeps it. Its id is the class IRI with the key values in key order. A request names a +record by a `key`, a list with one JSON value for each key column. Two rows with one key are one +record, so the class count counts distinct keys. + +**Each of the four statements starts from the identity table of its class.** A class without one is +a 409 that names the class. A reader who may not view the identity table gets a 403 that names the +class and never the table. A statement never starts from another table because of who asks, so the +id of a record does not depend on the reader. Every table a statement reads is in the database of +that identity table, and a table in another database is a 409. + +**`open` joins each contributing table on the subject key.** The keys pair by position. The join +is a `LEFT JOIN` that also carries the row filter of the contributing table, so a record with no +contributing row still opens. Several contributing rows for one key give several result rows. A +contributing table that the reader may not view leaves the statement and the plan, and no response +names it. A contributing table that adds no result column is not joined either, so a table that +only links two classes never repeats the rows of `open`. A class that binds more than 32 +contributing tables is a 409. + +**`expand` and the relation count follow the stored join of the relation.** The class that binds +the relation stores the join, on its identity table or on a contributing table that links the two +classes. The join names the identity table of the other class. The server follows only a join with +the status `confirmed`. A join that is only `inferred` is a 409 that says the join is not +confirmed, and no join is a 409 that says so. Which join the server follows never depends on the +reader. The identity table of the other class and the link table follow the rule of the start +table: a reader who may not view one gets a 403 that names the classes and never the table. A +related record takes its key from the identity table of its class and never from the join column. +`forward` goes from a record of the class that binds the relation to the records it names, and +`inverse` goes back. A request can name `relatedClass`. Without it, the related class is the one +class in the range of the relation going forward, or in its domain going back. When the relation +names several classes on that side, or none, a request without `relatedClass` is a 400. + +**Values reach the text only as typed values.** `TypedValues.key` parses a key and +`TypedValues.searchText` parses match text +(ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text). Nothing else that a client +sends reaches the text. Match text with no uppercase letter matches the display name without regard +to case. Match text with an uppercase letter is compared as the engine compares the column, because +the pattern is written once from the parsed text and never rewritten. No label, comment, or name of +an ontology term is part of a statement. + +**A statement applies the row filter of each table it reads, and parses only those filters.** A +stored filter that no longer parses is a 400 only for a statement that reads its table. + +**Each statement carries its own row limit.** T-SQL writes `SELECT TOP n` and every other dialect +writes `LIMIT n`. The plan gives the limit as `rowCap` and `extraRow`. `open` and `expand` ask for +one row more than `rowCap`, and that row says only that more rows exist. + +**A request names the version to read.** `release` is the default and reads the active release. +`draft` reads the working draft and takes `EditAll` on the ontology. The class, its properties, the +display name flag, and the relations come from that version. A class or a relation that the active +release lacks is a 404 that names its IRI, and an ontology with no active release is a 404 that +says so. Bindings sit outside versions and are always current. The server checks `ViewBasic` on +each definition the statement reads, as that version holds it. + +**The plan says what the statement is and what it was built from.** `sql` is the statement for a +person to read and `escapedSql` is the form to run through a reader of `:name` parameters. `columns` +gives each result column its index, its kind (`key`, `displayName`, `property`, or `count`), its +class IRI, and its key part or its property IRI. The plan also gives the engine family, the dialect, +the tables in join order, the version it read, and the binding revision of each class whose +bindings it read. The server reads the binding revisions, then the binding rows, then the revisions +again. A binding write commits its rows and its revision in one transaction, so two equal reads mean +that the rows belong to those revisions. After three unequal reads the request is a 409 that asks +the client to send it again. + +**The table bindings of a concept pick where `POST /v1/ontologyConcepts/{id}/query` starts.** That +endpoint is older than the roles, and a binding made before them has no role. The server guesses no +role for such a binding, and a concept with one table binding keeps the answer it had. + +- A concept with one table binding starts from that table, whatever the role of the binding. A + reader who may not view the table gets the 400 of a concept with no viewable table, as before. +- A concept with several table bindings starts from its identity table. A reader who may not view + that table gets a 403 that names the concept and never the table. +- A concept with several table bindings and no identity table is a 409 that names the concept and + asks for its identity table. The server never picks one of several tables for a reader. + +A binding whose table no longer exists does not count for this rule, whatever its role, as the +list of the bindings of a concept leaves it out. + +One generator writes the statement of this endpoint and the four above. Its `sql` writes every +colon as a colon again, and it gains `escapedSql`. + +**This record replaces three rules of +ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension, for a start concept that binds +several tables.** + +- That record reads the first 100 table bindings of the concept and keeps the first ten tables that + the reader may view. The statement started from one of those ten. It now starts from the identity + table, which the server reads by its role. +- That record treats a bound table that the caller may not view as unbound. A reader who may not + view the identity table now gets a 403. +- That record answers a concept without a viewable bound table with a 400. A concept that binds + several tables never gets that 400. Without an identity table it is a 409 for every reader. + +Its rules for a start concept that binds one table or none, for the concepts that a hop reaches, +for joins, labels, directions, batched reads, and the hop limit are unchanged. + +## Consequences + +A client builds a record id from the plan, and the id is the same in every statement and for every +reader. A client reads a result by column index, because two result columns can have one name. + +A concept whose bindings carry no role has no identity table. Each of the four statements about +its records is a 409 until one of its table bindings takes the `identity` role. The search-around +statement still starts from its table when it binds one. + +A concept that binds several tables and has no identity table got a search-around statement +before, and now gets a 409. That request works again once someone picks its identity table. A hop +still reaches such a concept, because the rules for a hop are unchanged. + +Only `topRecords` and the `expand` statement order their rows (amendment v3). A page of +`find` is any 25 records, and `find` reads no second page. + +A statement counts and lists joined rows. A link table that repeats one pair shows it twice in +`expand` and counts it twice. Two contributing tables that each hold several rows for one key +multiply the rows of `open`. + +A key column whose data type takes no value cannot be compared with a key, so `open` and `expand` +are a 400 for that class. `find` and the class count still work. + +The relation count groups over the whole join. On a large table that is expensive, and a narrower +statement is a later change that must keep the row filters and the null rule of both classes. + +A read of the active release does not depend on later deletions in the working draft. The class, +the relation, the related class and the properties come from the members of the release, read by +id, so a plain delete in the draft changes no answer of the release. Only the ontology of a class is +found from its working row, deleted or not, and that ontology must still be live. A request for a +class or relation that the release lacks is a 404, or a 400 when the working row belongs to another +ontology. The caller needs `ViewBasic` on each released definition, checked on the definition with +the owners, tags and domains the catalog holds now for its id, the way a read of a release +authorizes its members. A property the caller may not view leaves the plan. The right is never +`ViewAll`. A read of the draft keeps reading live working rows, so a deleted class or relation is a +404 there and a deleted property leaves the plan. + +The one class that a relation names in its range or its domain is found by IRI among the working +rows, deleted ones too, and kept when the release holds a member with that id and that IRI. A class +deleted for good and made again with the same IRI has a new id that the release lacks, and the +request is a 404 that names the IRI. A hard delete of a class also removes its bindings. A statement +on it is a 404 when no working row is left, and a 409 that the class has no identity table when the +request still names a class that the release holds. Both are right, because bindings sit outside +versions. A request for a deleted class that names an ontology which is itself deleted is a 404, +checked before the right to the class, since the ontology comes from the working row. + +## Amendment v2: the aggregate statement counts the links of a relation + +A client that needs one number, how many links a relation has between the records of two classes, +had only the class count and the 8 records with the most links. The request of `/aggregate` +gains `measure`, one of `topRecords`, which is the default and the answer it always gave, and +`linkCount`. A measure belongs to a relation. `linkCount` needs a relation and a direction, as +`topRecords` does, and a class count that names any measure is a 400. The plan names the measure of +an aggregate over a relation, the binding revision of both classes, and one column of the kind +`count`. + +**The link count is the number of distinct links of the relation.** The statement returns one row +with one column. + +- A link is a pair of a record of the class that binds the relation and an object key with no null + part. The record passes the row filter of the binding class and has a whole key. Over a link + table or another contributing table, the row of that table joins the record on the subject key + and passes the table's own row filter. +- The object need not be a record. A key that no row of the object class holds still counts. +- Forward from the binding class, the count is every link. The statement starts at the identity + table of the binding class and reads the object key from the columns that hold the join. +- Inverse from the other class, the count is the links whose object is a record of the start class. + The statement starts at the identity table of the start class and joins the identity table of the + binding class, through the link table when one holds the join. It applies the row filter and the + whole-key rule of the binding class, and the row filter of the link table. +- The row filter of the object class applies only when the count starts from it. +- Two rows that give one pair count once, so a link table that repeats a pair does not count it + twice. + +**The refusals are those of the records that relate to the most.** An inferred join or none is a +409, a table the reader may not view is a 403 that names the class, and the version rules are the +ones above. The count form has no `ORDER BY` and no row limit, and the plan gives `rowCap` 1. + +**A forward count and an inverse count of one relation can differ.** They differ by the links whose +object key is no record of the object class: forward counts them, and inverse never does, because +the start class is the object class. A stored profile counts a reference in the same way as the +forward count, so the agreement with the stored-profile count holds for the forward count only. A +client that wants the links of the relation as a whole asks forward from the class that binds it. + +Guard: `OntologyAggregateStatementTest`, `OntologyStatementGoldenTest` and `OntologyLinkCountIT`. + +## Amendment v3: the expand statement pages by the key of the related record + +**The statement orders and can start after a key.** `expand` ends with `ORDER BY` the key columns +of the identity table of the related class, ascending, in key order. The request gains `after`, the +key of the last related record the client holds, in the key order of the related class, with the +shape and the typing of `key`. Without `after`, or with an empty one, the statement starts at the +first related record. With it, the statement keeps the related records whose key comes after it: + + (k1 > v1) OR (k1 = v1 AND k2 > v2) OR ... + +The comparison is written out and not as a row-value comparison, because several engines have no +row-value comparison. Each value goes through the escapers of ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text, +typed by its key column. The statement still asks for 26 rows, so the 26th row says that a next page +exists, and a client reads the next page with the key of the 25th row. + +**The plan says which columns hold the key.** `orderedBy` lists the indexes of the result columns +that hold the related key, in key order. Only an `expand` statement sets it, and only when its +related key takes values, as the next paragraph says. Every other statement leaves it empty, +`topRecords` too, though it orders by its count. An empty list means the statement takes no +`after`. A client sends the values of those columns in the last row it keeps as `after`. + +**A related key that takes no value is not ordered.** An `expand` statement whose related key has a +column of a type the generator writes no value for, such as JSON, has no order, an empty `orderedBy` +and no `after`, as before this revision. No `after` could follow its first page, and several engines +cannot order such a type. One predicate decides both, so the order and the 400 on `after` cannot +disagree: the statement orders by the related key only when every column of that key has a type +that takes a value. A start key keeps its rule, and a column without such a type is a 400 there, as +for `open`. + +**A bad `after` is a 400, as a bad `key` is.** A value of the wrong type for its column names the +column, the data type and the problem. A number of values other than the key has says how many the +key has. A request that leaves `after` out reads as an empty list, so an empty `after` cannot be a +400 and means no `after`. + +**The engine compares and orders.** The statement carries no collation, so a page boundary agrees +with the order the engine gives for its own columns. Two engines can order the same text +differently, and so can two collations of one engine: MySQL's default collation puts `x`, `Y` and +`z` in that order, and a binary one puts `Y` first. Two keys that the engine's collation holds equal +compare as one key, such as `x` and `X`, or `e` and `é`, under MySQL's default collation, which +ignores case and accents. A page that ends on one of them starts after both, so the other is +skipped, as for two rows with one key. A client must not merge pages that came from two +connections, and must not pass an `after` from one engine to another. + +**Two related rows with one key are a data fault.** A related key that more than one row holds, or +a link table that repeats a pair, gives the same key on two rows. A page that ends between them +starts the next page after that key, and the second row is skipped. A client folds rows by key. + +**A related record whose key has a null part stays out**, as before, so no page holds it and no +`after` can name it. + +**`find` has no order.** A `find` over a whole table with `ORDER BY` makes each request scan and +sort that table on a warehouse, and a first page of any 25 records is enough +to see what a class holds. `expand` is different: the rows of one record are few, they are found +through the join, and a client needs the second page of them. + +Guard: `OntologyExpandStatementTest` (including a related key of three columns, and a related key +with a JSON, BLOB or ARRAY column), `OntologyStatementGoldenTest` (the forward statements with +`after` too), `OntologyExpandPagingIT` (including the three-column pages and the JSON key) and +`OntologyRecordStatementIT`. diff --git a/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md new file mode 100644 index 000000000000..212395947675 --- /dev/null +++ b/docs/decisions/2026-11-23-a-shape-check-is-exact-or-it-is-not-offered.md @@ -0,0 +1,417 @@ +# A shape check is exact or it is not offered + +- **Status:** Accepted +- **Revisions:** v1 2026-11-23 (initial) · v2 2026-11-24 (every check is a generated query, a pattern is checked on Postgres only, a datatype is held by engine family, and a shape or a property the caller may not view is not shown) · v3 2026-11-24 (a class that a `class` part names is masked when the caller may not view it, the pattern subset is what XPath reads, and a draft authorizes the rows it read) · v4 2026-11-25 (the statements do not grow with the classes a `class` part names, a filtered one included) · v5 2026-11-26 (the subclass question walks the ancestors of all the sharing classes together, and its bound leaves the sharing classes out) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyShapeCheckCompilerTest` (the rule), `OntologyPortablePatternTest` (the patterns), `OntologyShapeCheckGoldenTest` and `OntologyShapeCheckSqlTest` (the queries), `OntologyShapeCheckAnswerTest` (the answer and the masking), `OntologyShapeCheckReaderTest` (the revision a check names, what a caller may view, the pages of a release, and the classes that get no answer), `OntologyShapeCheckValueCasesTest` (a listed value as each engine writes it), `OntologyShapeCheckIT` (each query on rows that satisfy and rows that break it), `OntologyShapeCheckPatternIT` (a pattern on Postgres rows), `OntologyShapeCheckAnswerIT` (the answer for each outcome, and the version read), `OntologyShapeCheckRightsIT` (who is answered), `OntologyShapeCheckDefinitionRightsIT` (the shapes and the properties a caller may not view), `OntologyShapeCheckReadsIT` (the reads, the cost of the subclass question, and a sharing class whose second parent leads to the named class, read second and first), `OntologyConceptBindingFirstRowsIT` (the cap of the first rows is per table), `OntologyConceptBindingStoreAncestorsTest` (both halves of the bound of the walk, the classes above the starts and the axioms read, the level of more than 10,000 classes, a first level of more starts than one chunk holds and the bound across its chunks, the statements of chains that meet, and a class under two classes), `OntologyConceptBindingsIT` (a property of a class reached only through a second parent is applicable) +- **Related:** ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints (the constraints that are compiled), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, the subject key and the row filter), ADR:2026-11-22-record-statements-start-from-the-identity-table (the record, and the statement builders that are reused), ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text (how a value reaches the text of a query) + +## Context + +A shape says what the records of a class must satisfy: how many values a property has, which class +or datatype a value has, and which values are allowed. A table binding says which rows of which +tables are those records. A data quality test runs on one table and counts rows. + +A row is not always a record. A binding can keep only some rows of a table, two rows can share a +key, a key column can hold a null, and a value can sit in a second table. A test that counts rows +then reports a violation that no record has, or misses one that a record has. A person who reads +the result cannot tell which of the two happened, so a test of that kind is worse than no test. + +A built-in column test does not read the whole table either. The test runner builds the data of +such a test from the profile sample of the table, and the server that offers the test does not +read how that sample is set. + +## Decision + +**The server says how each constraint of a class's shapes is checked, and creates nothing.** +`GET /v1/ontologyConcepts/{id}/shapeChecks` compiles every shape that targets the class in the +release or the draft. A constraint is answered part by part: `minCount`, `maxCount`, `class`, +`datatype`, `range` (`minInclusive` and `maxInclusive` together), `in` and `pattern`. Each part gets +one of five outcomes. + +| Outcome | Meaning | +|---|---| +| `check` | A test counts the records that break the part. One check for each table that holds the property. | +| `heldByMapping` | No record can break the part, because of how the class is mapped. | +| `notMapped` | No identity table and no contributing table of the class binds the property, or the version has no such property. | +| `notEnforceable` | No exact test exists. A `reason` from a closed list says why. | +| `hidden` | The caller may not view a table that the answer rests on, or the property the constraint is about. | + +**A check is exact.** Its number is the number of records that break the part, so it is 0 exactly +when every record satisfies the part. Where no such test exists the part is `notEnforceable`. The +server never offers a test that is close. + +**What is checked.** + +- A record of a class is a row of its identity table that the row filter of the binding keeps and + whose subject key columns are all non-null. Rows with the same key are one record. Only records + are checked. A row of a contributing table or a link table whose key matches no record is not + checked. +- A data property has a value on a record in each bound column that is not null. A relation has a + value where the columns of its confirmed join are all non-null. Whether that value is a record of + some class is what `class` asks, so a key that matches no row still counts as a value for + `minCount` and `maxCount`. +- Only the bindings of the class that the shape targets are read. A shape is not compiled for the + subclasses of its target, because a statement about a class does not read their rows. +- Two values are equal when the source says so, its collation included. A source that compares + text without regard to case counts `a` and `A` as one value, and finds `A` in a list that holds + `a`. The check and the source agree, which is what a person who reads the table expects. + +**Every check is a generated query.** A check is a `tableCustomSQLQuery` test whose statement the +server writes. The built-in column tests `columnValuesToBeNotNull`, `columnValuesToBeInSet`, +`columnValuesToBeBetween` and `columnValuesToMatchRegex` are not offered, for two reasons. + +- A column test counts rows. A row that the filter drops is no record, and a column test still + reads it. Two rows with one key are one record: when one row holds a null and the other a value, + the record has a value and a test for nulls fails. A value in a contributing table belongs to a + record only when its key matches one, and a column test cannot ask. +- A column test reads a sample. The test runner builds the data of a built-in test from the profile + sample of the table (`create_data_quality_interface` in + `ingestion/src/metadata/data_quality/runner/base_test_suite_source.py`). A sample that is set on + the table, its schema or its database comes before the sample of the pipeline, and the partition + and the sample query of the table apply too. The compile does not read those settings, and no + binding revision moves when one of them changes. A column test that is exact today can therefore + stop being exact while the shape and the mapping stay as they are. + +A `tableCustomSQLQuery` test runs its statement on the session as it is written and never reads the +sample. The statement starts from the records, so it is exact on every table of the class, and it +returns 0 for an empty table. + +**A table is simple for the class** when it is the identity table of the class, the binding has no +row filter, and the columns of its declared primary key are exactly the subject key. On a simple +table each row is one record and each record is one row. A simple table matters only for +`maxCount`, where it is one of the tables that the next rule covers. + +**A declared key is trusted.** A declared primary or unique key whose columns all lie inside the +subject key columns of a table says that the table holds at most one row for each key. A record +then has at most one value there, so `maxCount n` is `heldByMapping` for n of at least 1. A key +with a column outside the subject key says nothing, because two rows can share the subject key and +differ there. A primary key is declared by a `PRIMARY_KEY` table constraint, or by the column +constraint `PRIMARY_KEY` when exactly one column carries it. A unique key is declared by a `UNIQUE` +table constraint or by the column constraint `UNIQUE`. The declaration in the catalog is taken at +its word on every engine, whether the database or a person declared it, and whether or not the +engine enforces it. + +**The rule.** "Generated" is a check whose statement counts the records that the row names. The +table is read for a property that an identity table or a contributing table of the class binds. Two +answers come before it. + +- A property that the version does not have is `notMapped`. A property that no identity table and + no contributing table of the class binds is `notMapped` too, with two exceptions that the table + of reasons names: `noIdentityTable` when the class binds it in a table with no role and has no + identity table, and `boundOnInverse` when the class binds a relation in no table and another + class binds the inverse. +- For every part but `minCount 0`, a class whose records cannot be read is `notEnforceable`: + `noIdentityTable` when it has no identity table, `columnMissing` when the subject key is empty or + when one of its columns or the column of the row filter is not in the identity table, and + `valueDoesNotFitColumn` when the stored row filter no longer parses. + +| Part | Answer | +|---|---| +| `minCount 0` | `heldByMapping` | +| `minCount 1`, a property whose value columns are all subject key columns of the identity table | `heldByMapping` | +| `minCount 1`, one column | generated: records with no value | +| `minCount 1`, a relation of several columns | generated: records with no value, where a value has every column of the join non-null | +| `minCount n`, n above 1 | generated: records with fewer than n distinct values | +| `maxCount n`, n at least 1, a value on a simple table, or on any table where a declared primary or unique key lies inside the subject key columns | `heldByMapping` | +| `maxCount n` otherwise, `maxCount 0` included | generated: records with more than n distinct values | +| `in`, literals | generated: records with a value outside the list | +| `range` | generated: records with a value outside the bounds | +| `pattern` | generated on the `Postgres` service type: records with a value that the pattern does not match. `notEnforceable` with `engineNotSupported` on every other service type | +| `class` | generated: records with a value that is no record of that class | +| `datatype` | `heldByMapping` when every value that the engine stores in the column's type is a value of the datatype, else `notEnforceable` with `datatypeMismatch` | + +A null is no value, so it breaks none of `in`, `range`, `pattern` and `datatype`. A generated check +needs a service type that statements are written for, every table of its statement in one database, +and every column that it names still in its table. `minCount` on a contributing table and `class` +keep the records with no matching row. The `CLICKHOUSE` family gets no such statement, because an +unmatched row there holds a default value and no null. + +A literal is parsed by the type of the column it is compared with, and the datatype of the literal +is not read. A range needs a column whose values have an order the server knows: a whole number, a +decimal, a date, a time or a timestamp. A list needs a column type that takes a value. + +**A check counts in the source.** It runs with the strategy `COUNT`, the operator `<=` and the +threshold `0`, so the statement returns one number and the test passes exactly when the number is +0. The strategy `ROWS` would bring one row for each violation to the runner. The count statement +has no `ORDER BY` and no row limit. A second statement, `inspectionQuery`, lists the keys of the +records in violation for a person to read, and every check carries one. It has no order and no row +limit either, so a person who runs it on a large table adds a limit. Every column in both is +qualified with its table alias, every table is in one database, and no label, comment or name of an +ontology term reaches the text. A value reaches the text only as a typed value +(ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text). + +**A pattern is checked on Postgres, the way XPath reads it.** SHACL reads `pattern` as the +`matches` function of XPath does with no flag. Postgres is the one engine that was run against +every construct a pattern may hold, so a pattern gets a check on the `Postgres` service type only. +Every other service type answers `engineNotSupported`, Timescale included, until an engine run +shows that it reads each construct the same way. + +- The column is a text column of any table of the class. A `CHAR` column is refused, because the + engine pads its values with spaces and nothing says whether the pattern is asked of the padding. +- The pattern starts with `^` and ends with an unescaped `$`. Between them it holds only ASCII + letters, digits, spaces and punctuation, `.`, character classes, groups with no prefix, + alternation inside a group, and the quantifiers `?`, `*`, `+`, `{n}`, `{n,}` and `{n,m}` with + counts up to 255. No control character and no character outside ASCII is taken. +- An ASCII punctuation character that is not a metacharacter stands for itself, outside a character + class and inside one. The metacharacters are `.`, `\`, `?`, `*`, `+`, `{`, `}`, `(`, `)`, `[`, + `]`, `|`, `^` and `$`, and inside a class also `-`. So `^O'Brien$`, `^a:b$`, `^[^@ ]+@[^@ ]+$` and + `^[A-Z]{2}-[0-9]{4}$` are taken. +- A backslash is taken only before a character of the single-character escape set of XPath (XPath + and XQuery Functions and Operators 3.1, section 5.6.1): `n`, `r`, `t`, `\`, `|`, `.`, `?`, `*`, + `+`, `(`, `)`, `{`, `}`, `-`, `[`, `]`, `^` and `$`. `\n`, `\r` and `\t` are a line feed, a + carriage return and a tab, which Postgres reads the same way, in a class and outside one. Every + other escape is an error in XPath, so the pattern is `patternNotPortable`, `\:`, `\'`, `\@`, + `\;` and `\=` among them. The class escapes `\d`, `\s`, `\w`, `\i`, `\c`, `\p{...}` and their + capitals are refused as well. A character class holds the same literal characters and escapes, + and ranges of two digits or of two letters of one case, and may be negated. +- An alternation outside a group is refused, because `^a|b$` means something else on an engine that + anchors a pattern by itself. A back reference, a look-around, a lazy or possessive quantifier, an + anchor in the middle and a flag are refused too. A refused pattern is `patternNotPortable`. +- Postgres reads one construct of that core in another way. Its `.` matches a line feed and a + carriage return, and the `.` of XPath matches neither. The statement therefore holds + `[^\n\r]` in place of each `.`. Refusing every pattern with a `.` was the other choice, and it + would leave every pattern that uses a wildcard without a check. +- The statement is `NOT (CAST( AS text) COLLATE "C" ~ )`, with the pattern as a + typed text value. Under the collation `C` a range in a class goes by code point whatever the + collation of the column or of the database, which is how XPath reads a range. The cast makes one + rule for every text type: a `citext` column would fold case, an enumerated type has no match + operator, and a nondeterministic collation refuses a regular expression. +- `$` matches at the very end only, so a value that ends with a line break does not match + `^[0-9]+$`. + +**`class` reads the confirmed join of a relation.** The class of the constraint must have its +identity table where the join arrives. The query counts the records with a value that matches no +record of that class, so it carries the row filter of that binding and its non-null key. When a +subclass of that class has its identity table on the same table and the binding of the class has a +row filter, the filter may leave out records of the subclass, and the part is `notEnforceable`. The +subclass steps are the named ones of the version that is read, so a release answers as it was +sealed. + +**`datatype` is settled by the column's type on the engine that stores it.** It reads `xsd:string`, +`xsd:boolean`, `xsd:integer`, `xsd:decimal`, `xsd:double`, `xsd:float`, `xsd:date`, `xsd:time` and +`xsd:dateTime`. A part is `heldByMapping` only where every value that the engine stores in a column +of that type is a value of the datatype. The catalog gives one name to types that differ between +engines, so the table is by engine family +(ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text). A column of a service type +with no family is held for nothing. + +| Datatype | Column type | Engine families | Why no stored value breaks it | +|---|---|---|---| +| `xsd:boolean` | `BOOLEAN` | all but `MYSQL` and `TSQL` | The type stores true and false only. | +| `xsd:integer` | `TINYINT`, `BYTEINT`, `SMALLINT`, `BIGINT`, `LARGEINT` | all | Every source type that gets one of these names is a whole-number type. | +| `xsd:integer` | `INT` | all but `SPARK` | The same. | +| `xsd:integer` | `DECIMAL` or `NUMERIC` with a scale of 0 | all but `POSTGRES` | A fixed-point value with no fraction digit is a whole number, and the type stores no `NaN` on these engines. | +| `xsd:decimal` | the six whole-number types | all | A whole number is a decimal. On `SPARK` a column named `INT` can be a `decimal` column, whose values are decimals too. | +| `xsd:decimal` | `DECIMAL`, `NUMERIC` | all but `POSTGRES` | A fixed-point value is a decimal, and the type stores no `NaN` and no infinity on these engines. | +| `xsd:double` | `FLOAT` | all | Every source type that gets the name is a binary floating-point type of 32 or 64 bits. Each of its values is a 64-bit value, and `xsd:double` has `NaN` and both infinities. | +| `xsd:date` | `DATE` | `BIGQUERY`, `TSQL` | The type stores calendar days from year 1 to year 9999 and nothing else. | +| `xsd:time` | `TIME` | `BIGQUERY`, `TSQL` | The type stores a time of day below 24 hours and nothing else. | +| `xsd:dateTime` | `DATETIME` | `BIGQUERY`, `TSQL` | Every source type that gets the name stores a calendar day from year 1 to year 9999 with a time of day. | +| `xsd:dateTime` | `TIMESTAMP` | `BIGQUERY` | The same. | + +Every other pair is `datatypeMismatch`, and each is left out for a value that the type stores. + +- `xsd:float` is held nowhere. A `FLOAT` column has 64 bits on SQL Server and on Snowflake, and a + 64-bit value need not be a 32-bit value. +- `xsd:double` is not held on `DOUBLE`, because a decimal floating-point type gets that name too. +- `xsd:string` is held nowhere. Every text type stores the control characters below U+0020, and an + XML string holds none of them but the tab, the line feed and the carriage return. +- On the `MYSQL` family a `BOOLEAN` column can be a `TINYINT(1)`, which stores -128 to 127. The + date types of that family store the zero date `0000-00-00`, and its `TIME` stores `25:00:00` and + `-01:00:00`. The `TSQL` family has no type that gets the name `BOOLEAN`. +- On the `POSTGRES` family a fixed-point column stores `NaN`, and a date or a timestamp stores + `infinity`. +- On the `SPARK` family the Databricks source reads a `decimal` column as a type that the catalog + names `INT`. +- A `TIMESTAMP` column of the `TSQL` family is a row version. +- The date and time types of the other families are held for nothing until someone reads what + their engines store. + +**What is not enforceable, and why.** + +| Reason | When | +|---|---| +| `noIdentityTable` | The class has no identity table, so it has no records. | +| `severalTables` | `minCount` above 0 or `maxCount` on a property that the class binds in several places. The count would run over all of them at once. | +| `boundOnInverse` | The class binds the relation in no table, and a class binds the inverse that the relation declares, in an identity table or a contributing table. | +| `noJoin`, `joinNotConfirmed` | The relation has no join, or one that is only inferred. Only a confirmed join is read. | +| `notARelation`, `notADataProperty` | `class` on a data property, or `datatype`, `range`, `in` or `pattern` on a relation. | +| `targetClassNotOnJoin` | The class of the constraint has no identity table where the join arrives. | +| `subclassOnJoinTable` | A subclass shares the filtered identity table of the class of the constraint. | +| `valuesAreRecords` | An `in` list names a record by IRI. | +| `valueDoesNotFitColumn` | A literal does not parse as a value of the column's type, or carries a language tag. A stored row filter that no longer parses gives the same reason. | +| `tooManyValues` | An `in` list of more than 1,000 values. | +| `columnTypeNotSupported` | The column's type has no values the part can be compared with: a range on a type with no order, a list on a type that takes no value, or a pattern on a column that is not text or is `CHAR`. | +| `datatypeNotSupported`, `datatypeMismatch` | The datatype is not one of the nine, or the engine can store a value in the column's type that the datatype does not have. | +| `patternNotPortable` | The pattern is outside the common core, or it is longer than a statement takes once it is written. | +| `columnMissing` | A bound column, a key column or a join column left the table. | +| `otherDatabase` | A table of the check is in another database than the identity table. | +| `engineNotSupported` | A statement on a service type that none is written for, a pattern on any service type but `Postgres`, or a statement on the `CLICKHOUSE` family that keeps the records with no matching row. | + +A property bound in several tables is checked once for each table for `in`, `range`, `class`, +`datatype` and `pattern`. When the tables do not agree, each answer is its own part entry. + +**A check has an identity that survives an edit of its bound.** It is the lowercase hex SHA-256 of +the shape id, the constraint id, the part, the class id, the table id and the column path, joined +by a separator that none of them can hold. A check also lists the class, the table and the binding +revision of every binding it read. A check belongs to the table whose binding holds the property, +the link table included. + +**A check never names a stale revision.** A binding write commits its rows and its revision in one +transaction. The answer reads the revisions of the class and of every class a `class` part names, +then their binding rows, then the revisions again. When the two reads differ it starts over, and +after three attempts it answers 409. So every row that a check was compiled from belongs to the +revision the check names. A binding that does not exist has no revision to name: a subclass that +binds the filtered table later changes the answer, and a caller sees it when it asks again. + +**Each kind of input is read once.** After the class and the version, one request reads the +shapes that target the class, the properties their constraints name, the classes their `class` +parts name, the binding rows, and the tables those rows name. It checks the caller's right to view +once for the shapes, once for the properties and once for the tables. The number of statements does +not grow with the number of shapes, of constraints, of tables or of named classes. An +administrator's request runs 48 `SELECT` statements from the draft and 56 from a release, and no +statement locks the rows it reads. A `class` part whose class has a row filter on its identity +binding adds one statement that reads the binding rows of every such table together, with the +first 101 rows of each table, so those requests run 49 and 57 whether the parts name 1 class or 8. +When another class has its identity binding on one of those tables, one more question asks the +version once for all the classes that have a subclass there. On a draft that question reads the +sharing classes in one statement and then walks the subclass steps above all of them together, one +statement for each level of the hierarchy and one more that finds nothing above the top. So a draft +runs 52 statements when the sharing classes are one step below the named class and 54 when they are +three, whether one class shares the table or eight, and whether the classes of the named parts are +1 or 8. A release runs 57 in every case, because it answers the question from its members, which it +reads through the cache that every sealed release shares. + +`OntologyShapeCheckReadsIT` counts those numbers for 1, 40 and 80 constraints on a class of 6 +tables, for 40 constraints on a class of 3 tables and of 12, and for `class` parts that name 1 +class and 8 classes, with and without a row filter on the identity bindings of those classes. It +finds no locking read in any request. + +A draft reads the shapes once and the properties once, and authorizes the rows it read, with no +second read of them. The check of the right to view loads the owners, the domains, the reviewers +and the certification of the rows it checks, where the repository supports them, and the compile +reads none of the other fields that the check clears. A second read would let a row that changed +between the two be compiled from one version and authorized from the other. A server setting whose +cached value has lapsed is read on top of the statements. Two questions cost further reads, and +only when a constraint asks them: the declared inverse of a relation that the class binds nowhere, +and a subclass on a filtered identity table that a `class` part arrives at. + +**An answer is whole or it is refused.** A class that binds more than 100 tables, and a draft +class that more than 1,000 shapes name, get 409. The draft cap counts every live shape that names +the class, including shapes the caller may not view, so a caller who may edit learns that more than +1,000 exist. Counting only the shapes the caller may view would read every row the cap exists to +bound. An answer built from a part of them would leave a +constraint unchecked or a count short. + +**What a caller may not view is left out or masked.** A shape that the caller may not view is not +in the answer, and nothing is read for it. The compile of the other shapes is the same for every +caller, and one step after it masks the rest. A constraint about a property the caller may not view +keeps its id, has no `path`, and has every part `hidden`. A constraint that a `class` part ties to +a class the caller may not view has every part `hidden` too and keeps its `path`, and nothing of +that class is in the answer: no id, binding revision, table, key column or row filter. May not +view means `VIEW_BASIC` on `ontologyConcept`, judged on the class as this version holds it. +`OntologyShapeCheckDefinitionRightsIT` guards it for a draft and a release, and +`OntologyShapeCheckAnswerTest` and `OntologyShapeCheckReaderTest` guard the masking. A constraint +whose answer rests on a +table the caller may not view has every part `hidden` too, with no check, no reason and no column. +Such a table is the identity table, a table that binds the property in whatever role, or the table +a join arrives at. A hidden constraint has one entry for each part, so it does not tell how many +tables answered. No name, id or IRI of such a shape, property or table appears anywhere in the +response. A draft asks about the working rows. A release asks about the definitions as it holds +them, so a shape whose working row was deleted after the release still answers. + +## Consequences + +A person is shown a test only when its result means what the shape says. Everything else comes with +a reason that names what to change: declare the key, confirm the join, pick an identity table. + +Every check is one kind of test, and its result is read one way. Each check costs one statement on +the source for each run. + +A declared key can be wrong where the engine does not enforce it. Several engines accept a primary +key and do not enforce it, BigQuery, Snowflake, Redshift and Databricks among them, and a person +can declare a key in the catalog on any table. Where two rows share such a key, a record can have +two values. The answer for `maxCount` is `heldByMapping` all the same, and no test is written that +would find those rows. That is the cost of taking a declaration at its word. + +A pattern has a check on Postgres only. A pattern on another engine, a pattern outside the common +core, and a count over a property bound in several places have none. Each needs its own exact form +before it can be offered, and a new record when it gets one. A Postgres database whose encoding is +`SQL_ASCII` counts bytes where XPath counts characters, and the server cannot see the encoding of a +database. A pattern check there can differ on a value that holds a character outside ASCII. + +A `datatype` part is `heldByMapping` on fewer columns than a reader may expect: `xsd:string` on +none, and a date on two engine families. The table gains a line when someone reads what an engine +stores in a type. + +The answer is computed for each request from the shapes, the bindings and the catalog as they are. +The type of a column is the name that the last read of its table wrote, so a table that an older +source read keeps the older name until it is read again. Nothing is stored, so a check has no state +here. Creating tests from this answer is a separate step that keys on the identity of a check and +compares the binding revisions it read. + +## Amendment + +v2 (2026-11-24): the text above is the amended rule. Four things changed from the first version. + +- Every check is a generated query. The first version offered the built-in column tests + `columnValuesToBeNotNull`, `columnValuesToBeInSet`, `columnValuesToBeBetween` and + `columnValuesToMatchRegex` on a simple table. The reason `tableNotSimple` left the closed list. +- A pattern is checked on the `Postgres` service type only, with `[^\n\r]` in place of each `.`. + The first version sent a pattern to the regex test of every engine. +- A datatype is held by engine family. The first version held it by the name of the column's type + alone, and so counted `NaN`, `infinity`, the zero date and a time above 24 hours as values of a + datatype. +- A shape that the caller may not view is left out, and a constraint about a property that the + caller may not view is hidden. The first version showed both to every caller who could read the + class. The two checks add 10 statements to a draft and 8 to a release. + +v3 (2026-11-24): three things changed. + +- A `class` part whose class the caller may not view is masked. Each of its parts is `hidden`, the + `path` stays, and no id, binding revision, table, key column or row filter of that class is in + the answer. +- The portable pattern subset takes what XPath reads (XPath Functions 3.1, section 5.6.1). A + backslash is taken only before one of `n r t \ | . ? * + ( ) { } - [ ] ^ $`, inside a class and + outside one. Any other escape, the multi-character escapes `\d \s \w \i \c \p` and their + capitals, and a backslash before a character outside ASCII are `patternNotPortable`. ASCII + punctuation that is no metacharacter stands for itself, so `^a_b$`, `^O'Brien$` and `^a:b$` are + taken and `^a\:b$` is refused. Postgres 15 reads each of these as XPath does. +- A draft authorizes the shape, property and class rows it read and reads none of them again. The + statements are 48 from a draft and 56 from a release, where they were 46 and 52. + +v4 (2026-11-25): the statements of a request do not grow with the number of classes that `class` +parts name. The first read of the filtered identity tables ran one statement for each such class, +and another for each class that shared the table. It now reads the binding rows of all those tables +in one statement and asks the version once for every class that may have a subclass there. A +request with filtered identity bindings runs 49 statements from a draft and 57 from a release, +for 1 named class and for 8. + +v5 (2026-11-26): the subclass question walks the ancestors of every sharing class together. The +first form of it walked each sharing class on its own, which cost one statement for each level of +each class, so 8 sharing classes three steps deep cost 82 statements. A draft now reads the sharing +classes once and runs one statement for each level of the hierarchy over the whole frontier, and it +decides each named class in memory, as a release does. It never reads every subclass axiom of the +ontology to answer, because that would read the whole hierarchy for each answer. The same walk gives +a class its ancestors for binding inheritance. The reads test asserts 52 and 54 statements from a +draft for 1 and for 8 sharing classes at depths 1 and 3, 57 from a release, and 52 for 8 named +classes with one sharing class each. `OntologyConceptBindingFirstRowsIT` guards that the cap of 101 +rows counts the rows of one table and not of all the tables a call reads, and +`OntologyShapeCheckAnswerIT` guards it on a draft and a release where one table is crowded and +another holds one subclass. + +The walk is bound once for all the sharing classes together, at 10,000. It counts the classes it +finds above the sharing classes and the axioms it reads, whichever is larger. It does not count the +sharing classes themselves, so the bound does not shrink with the number of them. The first level +reads its starts in chunks of one IN list, so that Postgres, which refuses more than 65,535 +parameters in a statement, and MySQL answer the same draft the same way, and the bound counts the +chunks together. A level of more than 10,000 classes is refused at once, before the next statement. +Binding inheritance counts as it did: the class and the classes above it, 10,000 at most, and it +also refuses more than 10,000 axioms read. A draft whose sharing classes have more than 10,000 +classes or axioms above them together answers 400, where its release answers, because a release +holds no such bound. The reads test asserts 53 statements from a draft where a sharing class +reaches the named class both directly and through a longer chain, because the class that both +chains reach is asked for once, and where it reaches the named class only through its second +parent, read second and read first, and 50 where the only class on the table is one of another +ontology, which is no candidate and leaves nothing to walk. diff --git a/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md new file mode 100644 index 000000000000..0b9d9e33a58e --- /dev/null +++ b/docs/decisions/2026-11-26-a-suggestion-task-can-carry-a-table-constraint.md @@ -0,0 +1,121 @@ +# A suggestion task can carry a table constraint, and approving it adds the constraint as the approver + +- **Status:** Accepted +- **Revisions:** v1 2026-11-26 (initial); v2 2026-11-27 (a resolution keeps the suggestion type; the whole constraint set is validated before approving); v3 2026-11-27 (only a suggestion task adds a constraint; the type check is exact); v4 2026-11-27 (no task form changes what approving a constraint needs or does); v5 2026-11-27 (a constraint suggestion's payload holds only the keys of the suggestion payload schema); v6 2026-11-28 (a resolution of any type cannot write a key outside that schema; approving is authorized for the task's current type); v7 2026-11-30 (the key rule names the keys a configured workflow writes; the resolution's payload holds the constraint added; an approval's comment names that constraint; the task tab sends only declared keys; the suggestion lists skip types they cannot show); v8 2026-11-30 (the comment is posted after the change is applied; the constraint added is read from the resolution's payload only when it carries one; the lists leave out a constraint suggestion only on the pages they fetched); v9 2026-11-30 (the record says what a failed apply does for each task type, and the order of the comment and the resolution); v10 2026-12-01 (a description update task is named among the task types whose failed apply still resolves with its comment); v11 2026-12-06 (the task list takes a `suggestionType` filter, and the suggestion lists use it instead of adjusting the total) +- **Deciders:** OpenMetadata maintainers +- **Guard:** `TableConstraintSuggestionTest` (what approving does under any form, the type check on a resolution and its exact comparison, the gate on the task type, the validation before approving, the equal-constraint and referred-column rules, the rethrow on a failed apply, a new value under a value field outside the schema, a stored key that does not stop a rejection, the comment an approval leaves), `SuggestionTypeRoutingTest`, `TaskRepositoryConstraintPermissionTest` (the right asked for under a form that names a narrower one), `TaskTableConstraintSuggestionIT` (the right and the effect under forms bound to the task's category; the keys refused when filing by POST or PUT, patching, resolving and voting, a vote refused without storing its key, a patch that changes the type of a task; a task that carries every declared key; the comment of an approval whose payload carries another constraint; an approval whose apply fails leaves no comment; the `suggestionType` filter counts and pages only the types asked for) +- **Related:** ADR:2026-11-18-suggestion-task-form-schemas-resolve-by-stamped-id-then-suggestion-type + +## Context + +A suggestion task proposed a description, tags, an owner, a tier, a domain or a custom property. A +table's primary, unique and foreign keys were editable only by a person with write access, with no +way for a connector, an agent or a colleague to propose one and have it reviewed. A proposal needs +the reviewer's rights and a record, so a client does not propose the same key again after it was +declined. + +## Decision + +- `SuggestionPayload.suggestionType` has the value `TableConstraint`. Its `fieldPath` is + `tableConstraints`, and its `suggestedValue` is one `tableConstraint` of `table.json` written as + JSON: `constraintType`, `columns`, and for a foreign key `referredColumns` (full column names) + and `relationshipType`. A seeded task form `TableConstraintSuggestion` (task type `Suggestion`, + category `MetadataUpdate`) carries it, and `TaskFormSchemaRepository` maps the type to that form. +- Filing the task is refused with a 400 unless the task is about a table, the value parses as one + `tableConstraint`, its type is `PRIMARY_KEY`, `UNIQUE` or `FOREIGN_KEY` (`SORT_KEY`, `DIST_KEY` + and `CLUSTER_KEY` are refused), its columns are columns of the table, and each referred column + is a column of an existing table. A foreign key has one referred column for each column, and + another type has none. Approving repeats these checks on the payload the approver resolved with. +- Approving needs `EditAll` on the table. A PATCH of `tableConstraints` maps to no narrower + operation in `ResourceRegistry`, so `TaskRepository#getOperationForTask` returns `EDIT_ALL` for a + constraint suggestion, before it reads any task form, and the task's own authorization check + runs before anything is written. +- No task form changes what approving a constraint suggestion needs or does. Approving needs + `EditAll` on the table and adds the constraint, whatever form the task's category matches. + A form's permission, handler and actions apply to other tasks as before. +- Apart from a key that a configured workflow writes (the next bullet), a constraint suggestion's + payload holds only the keys of the suggestion payload schema, so no other key decides what + approving it needs or does. Filing by POST or PUT, patching, and a + resolution of any type whose payload or new value would add a key are refused with a 400 that + names each key the schema does not declare, before anything is recorded or stored. A new value + adds the key that the task form names as its value field, so it is refused when that key is + not declared. The seeded suggestion forms name no value field. A key the task already stores + does not refuse a rejection that adds none, and approving checks the merged payload. Keys are + compared exactly. The names come from the generated `SuggestionPayload`, so the rule follows + the schema. +- A workflow that an administrator configures to write a key into a task's payload, such as a + lifecycle move, makes a constraint suggestion bound to it impossible to approve, because + approving checks the merged payload. The suggestion can still be rejected, and the table stays + unchanged. +- The constraint that approving adds is the one in the merged payload: the task's payload with the + resolution's payload laid over it. When the resolution's payload carries a + `suggestedValue`, that is the constraint added, and the task's payload keeps the filed one; + otherwise the task's payload holds it. An approver who resolves with another valid + `suggestedValue` therefore adds that one. A new value never changes the constraint, because the + merge never overwrites a key the payload already has, and `suggestedValue` is always there. The + comment that an approval leaves on the task names the constraint that was added (its type, its + columns and, for a foreign key, its referred columns), or says the table already had it; it never + repeats a new value, and a rejection leaves none. The text is decided on the table as it was + before the change, and the comment is posted only after the change returns, and before the task + is resolved. A change that throws therefore leaves no comment and the task stays open. That + covers a table constraint suggestion whose apply fails, and a memory conflict decision or a + metadata completion check that refuses. A suggestion of another type, or another task type such + as a description update, logs a failed apply and resolves with its comment, as before. Another + user can change the table between the read and the + apply, and then the comment can say "Added" for a constraint the other user added, or "already + has" for one this approval added. A comment that cannot be written does not fail a resolution + that was applied. +- The task tab of the UI sends a constraint suggestion's resolution with the approver's comment as + the resolution's own comment, and with a payload of only the keys the form of that transition + declares, or none when the form declares none, because the form's data can hold a key the schema + does not declare. The suggestion lists of the UI leave out a suggestion whose type they have no + card for, so a constraint suggestion shows neither as a description nor as a tag, and it is + not counted in the pages the lists have fetched. A constraint suggestion on a page not yet + fetched stays in the server's total until that page is fetched. +- Applying patches the table as the approver through the table repository, so its own validation + runs. A constraint equal to one already on the table (same type, columns and referred columns) + writes nothing and the task still resolves. A second primary key is refused with a 400 naming + the existing one, before anything is written, and the task stays open. A failure while applying + a constraint is raised to the caller, unlike the other suggestion types, so a task is never + `Approved` for a constraint that was not added. +- A resolution cannot change a suggestion task's type to or from `TableConstraint`. Approving is + authorized for the task's current type, which a PATCH of an open task can change, so a resolution + payload that names another type would add a constraint on the right to edit something + narrower. Such a resolution is refused with a 400 before the workflow moves, and a change + between the other types is as it was. +- Before the workflow moves, approving runs the table repository's own validation on the table's + constraints with the new one added, so a constraint set the write would refuse (for example a + foreign key to a table that was deleted) is refused with a 400 while the task is still open and + can still be rejected. +- Only a task of type `Suggestion` adds a table constraint. A task of another type whose payload + names one is handled as before this change and adds nothing, whatever form it is bound to. +- The suggestion type is compared exactly. A resolution that spells `TableConstraint` with another + case or with a space around it is refused like any other change of type. +- Rejecting leaves the table unchanged and the task `Rejected`. +- A timer that an administrator adds to a workflow can close a task without applying it, as for + every task type. +- A client finds the suggestions already made for a table, and the ones declined, by listing the + tasks about that table with type `Suggestion` and a status, and reading `payload.suggestionType` + and `payload.suggestedValue`. The amendment below adds a filter on the type. +- The change summary covers `description`, `owners` and `columns.description` only, so an agent's + constraint suggestion is not recorded in it. + +## Consequences + +- A client that sees a `suggestionType` it does not know must skip it or show the raw value. A + server that predates this value rejects the payload as an unknown enum value. +- Replacing a primary key takes two steps: remove the old one, then approve the new suggestion. +- Revisit the `EditAll` requirement if a narrower operation for table structure is added. + +## Amendment: the task list filters on the suggestion type (2026-12-06) + +`GET /v1/tasks` takes `suggestionType`, a comma-separated list of suggestion types such as +`Description,Tag`. It keeps the tasks whose `payload.suggestionType` is one of them, and a value +outside the schema's enum is a 400. The filter reads the stored task JSON on MySQL and PostgreSQL, as +the ontology review filter does, so no column or migration was added. + +The suggestion lists of the UI send `Description,Tag`, the types that have a card. The server's +`paging.total` then counts only those tasks. The lists no longer subtract the tasks they leave out +of a page: that subtraction fed the next `limit` and the pending count a window that still held the +left-out tasks, so with two constraint tasks ahead of eight description suggestions the refetch +returned six of the eight and the pending count never reached zero. diff --git a/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md new file mode 100644 index 000000000000..5eb86fc41745 --- /dev/null +++ b/docs/decisions/2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test.md @@ -0,0 +1,161 @@ +# A shape check reaches its table as a proposed test, and the server keeps the proposals and the accepted tests in step + +- **Status:** Accepted +- **Revisions:** v1 2026-12-01 (initial) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyCheckReconciliationTest` (the decision of the reconcile: every branch, a refused compile, an empty run and a second run), `TestCaseSuggestionTest` (the proposal, its digest and the rules it shares with a table constraint suggestion), `GeneratedTestScopeTest` (the read-only rule), `OntologyShapeCheckProposalIT` (a proposal accepted, rejected and kept in step, a test the reconcile deleted as the governance bot that comes back, a hard delete, and a CSV import that changes a generated test's threshold or its test definition, refused by the dry run and by the real import with the same message, on MySQL and Postgres), `OntologyShapeCheckReadsIT` (the statements per read), `OntologyShapeProposalAskIT` (who is asked, who may approve or reject, and that the owner whose activation filed the task finds it under assigned and not under created), `OntologyCheckReconcileCostIT` (a second run writes nothing) and `TaskResourceIT` (`testListGivesReviewersAndDomainsInTheOrderAGetDoes`: a list of tasks gives the reviewers and domains in the order a GET gives, from a list that asks for both fields, including a task with none, and from a list that asks for `domains` alone and one that asks for `reviewers` alone; `testCreatorWhoIsAlsoAssigneeCannotApprove`: a non-administrator who files a task and is also its assignee is refused when they approve it, while another assignee may approve it) +- **Related:** ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered (the checks that are compiled), ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint (the rules a suggestion task of a fixed shape follows) + +## Context + +The compile of a class's shapes (`GET /v1/ontologyConcepts/{id}/shapeChecks`) says which data quality +tests would count the records that break a part of a constraint, and creates nothing. A test on a +table runs on a schedule, reads every row, costs the owner of the warehouse money and can fail a +pipeline, so it must not appear on a table because a shape was released. The person who owns the +table decides. + +A test also goes stale. The statement of a check depends on the release (a bound of a constraint) and +on the table bindings (a row filter, a bound column). Someone who changes either would otherwise have +to find every test they made and change it by hand. + +## Decision + +**A check is proposed before it is a test.** The server files one suggestion task for each check +(`suggestionType` `TestCase`, `fieldPath` `testCases`), about the table the check belongs to. +Approving it creates the test case as the approver, and rejecting it creates nothing. A resolve of +either kind needs the right to resolve the task, which the assignees, the owners of the table and +the administrators have. As for any task that changes an entity, the server also asks on every +resolve for the right to make the change, here `CreateTests` or `EditAll` on the table +(`TaskRepository.validateUnderlyingEntityPermission`). A denial of `CreateTests` refuses that check +whatever else is allowed (`DefaultAuthorizer.authorizeRequests`). The reconcile assigns the task to +the owners of the table who may create tests on it, and when none of them may, to the owners of the +ontology who may. A team stands for its users. When nobody qualifies, the task is filed with no +assignee, and the server gives it to the owners of the table, as it does any task filed with no +assignee. An owner denied `CreateTests` may then neither approve nor reject it, so an administrator +resolves it. A table with no owner leaves such a task with no assignee, and an administrator +resolves it. Its source is `Ingestion`, because a deterministic compile of a shape wrote it, and no +agent or model did. The governance bot files the task, not the person whose change started the run, +because `TaskAuthorPolicy`, which every user holds through the organization's default role, +refuses a non-administrator's resolve of a task they filed, and that +person is often the owner the task asks. So the task is not among the tasks that person created, and +deleting that person leaves the task in place. + +**A test is not kept in a review state.** The runner reads every test case of a suite and no status of +it, so a test that waits for a decision would run. The proposal is the task and the test does not +exist until it is approved. + +**What a proposal holds.** The suggested value is a `testCaseProposal` written as JSON: the test case +to create in the shape of a request to create one (the test `tableCustomSQLQuery` on the table's +entity link with the four parameters `sqlExpression`, `strategy` `COUNT`, `operator` `<=` and +`threshold` `0`), the statement that lists the keys of the records in violation, and `generatedBy`. +The statement of the count is passed through as the compile wrote it, with each colon written as a +backslash and a colon. The statement that lists the keys is stored as the test case's +`inspectionQuery`, never passed through a parameter binder, and no runner executes it. A proposal sets +no partition expression and leaves the computation of passed and failed rows off. + +**Identity and content.** The identity of a check is the digest the compile gives it. It holds no +test definition and no value of the constraint, so a changed bound keeps it, and a check that once +was offered as another test keeps it too. The content digest is the lowercase hex SHA-256 of the +canonical JSON of the test definition, the entity link and the parameter values, with sorted keys and +the parameters in their order. It decides whether the content changed. `generatedBy` holds the +identity, the shape, the constraint id, the part, the class, the table bindings the check was built +from with their revisions, and the content digest. Only a suggestion that creates the test and the +reconcile set it. + +**The reconcile.** A background job compiles the checks of each class in scope, for no caller, so it +reads every shape, property and table and masks nothing (the answer a person gets is a masked view of +the same compile, and a step that creates tests must never read a hidden constraint as absent). +For each check it does the first of these that applies: + +| What exists for the check | What the reconcile does | +|---|---| +| A live test case with the identity | Updates it in place when its content digest or its bindings changed, else leaves it alone. Deletes every other live test case of the identity, keeping the one with the lowest id. | +| An open task with the identity | Replaces its suggested value when the content or the bindings changed, else leaves it alone. | +| A rejected task, a test a person deleted, or an approved task whose test a person hard deleted, with the same content digest | Nothing | +| A test the reconcile deleted, and no test a person deleted | Restores the one with the lowest id, then updates it as in the first row | +| None of these | Files a new task | + +The reconcile deletes and restores a test as the governance bot, and a later run reads that name in +the test's `updatedBy` to tell its own delete from a person's. So a test it deleted comes back, with +its id and its results, when an older release wants its check again. A hard delete leaves no row, +so the content is compared with the content the task was approved with. A test whose content was +updated after its approval and then hard deleted is proposed once more. + +A test whose identity no longer appears is deleted, as a soft delete a person can see. An open task +whose identity no longer appears is closed as `Cancelled` with the reason as its comment. A part that +is now held by the mapping, not mapped or not enforceable counts as not appearing. A second open task +of one identity, or an open task of a check that has a test, is closed too. A rejected task of other +content, or a deleted test of other content, is proposed again. + +**A refused compile changes nothing.** The compile of a class can refuse, for example when the walk +up its ancestors passes the bound, or when the bindings change while it reads. The reconcile then +writes nothing for that class, deletes no test and cancels no task, logs the refusal with the class id, +and the next trigger tries again. A refusal is never read as "no checks". + +**When it runs.** After the commit of an activation, an older release included, for every class of the +ontology that a shape of the active release targets and every class that has a generated test or an +open proposal. After a write that moves the binding revision of a class, for that class and for every +class whose tests or proposals list a binding of it. A job runs one at a time for each ontology. A +request that arrives while one runs is merged with the others that wait and runs after it. + +**Running it twice writes nothing.** Every write follows from a difference between the compile and +what exists, so the state a run leaves has no difference. The reconcile counts its writes and a test +asserts that the second count is zero. + +**Read-only.** A test case with `generatedBy` refuses a change to its test definition, entity link, +parameter values or `generatedBy` by anyone but the reconcile, with a 400 that says the test comes +from a shape. A create that sends `generatedBy` is a 400, and so is a patch that changes it. A PUT +keeps the stored `generatedBy`, so a PUT that changes only the description, owners or tags succeeds. +A PUT finds a test by its entity link and name, so a PUT with another entity link creates a separate +test and leaves the generated one as it was. A CSV import runs the same check in its dry run and in +the real import, so the dry run reports a row that changes what the shape freezes. The description, +owners and tags stay editable, and a +person may delete the test. A test a person deleted is not brought back unless the content changes. + +**What a test costs and reads.** The test is added to the basic test suite of its table, created if +the table has none. A suite with no pipeline gets one that runs daily at midnight, and the +deployment is best-effort, as for a data contract. Creating the test and the pipeline happens in the +repositories, so the limits that a resource enforces on a request, which a deployment can set per +feature, do not apply to them. OpenMetadata has no way to read the most frequent schedule a +deployment allows, so the schedule stays daily at midnight. A check reads every row of its tables: +the runner executes the statement of a `tableCustomSQLQuery` test with `COUNT` as written, on its +own session, and never through the sampled data set that built-in tests read, whatever sample the +table, its schema, its database or the pipeline sets. A list of tasks reads the reviewers and the +domains of all its tasks together, not task by task, and gives each task the reviewers and domains +that a GET of it gives, sorted by name as a GET +sorts them, deleted reviewers included. Two domains with the same name, which sub-domains +under different parents can have, come in no fixed order in either. + +**What a caller reads.** Each check of `GET /v1/ontologyConcepts/{id}/shapeChecks` has a `proposal`: +`none`, `proposed` with the task, `rejected` with the task, or `accepted` with the test case and the +status and time of its latest result. A caller who may not view the task or the test case gets the +state without the reference. A caller who may not view the test case gets no latest result either. +Reading the proposal states of a class takes the same number of statements for one check as for +forty. The proposals do not show in the lists of suggestions that a page of descriptions and tags +reads, because those lists leave out a suggestion type they cannot show. + +## Consequences + +- A table owner sees a check as a task and accepts or rejects it with the rights they have on the + table. Nobody has to pass a test to a person who may not create one. +- A bound that changes keeps the test, its id and its results. A check whose statement changes, such + as one whose row filter changed, is updated without an activation. +- The queue is in memory. A trigger lost with the server is made good by the next one for the + ontology, because each run derives its writes from the state it reads. A crash in the middle of a + run leaves some writes made, each complete, and the next run finishes the rest. Two servers can + run two jobs of one ontology. They can file two open tasks of one check, or create two tests of it + once both tasks are approved. The next run cancels the second task, or deletes every test of the + check but the one with the lowest id. +- Finding the generated tests and their tasks reads every test case and every task of the + deployment, so a reconcile and a read of proposal states take time in proportion to them. +- The compile reads three things after its check of the binding revisions: the holders of the inverse + of a relation, the classes that share a filtered table, and the tables themselves. A change to + them that moves no revision listed by a check is not triggered by itself. The holders of an inverse + only choose between two reasons that are both "no check", so they change no check. A new subclass + that binds the table of a class a `class` part names, or a change to a table's declared keys or + columns, is seen by the next activation, the next write to a class of the check, or the next write + to a class whose checks list the class. +- A check still can abort at run time. A pattern check, on the `Postgres` service type only, can stop + with `regular expression is too complex`, which the runner reports as a failed run of the test. +- Revisit the queue if more than one server runs the reconcile at once, or if a deployment needs a + proposal to survive a restart that lost it before it ran. diff --git a/docs/decisions/2026-12-01-an-apps-configuration-is-checked-before-the-server-stores-it.md b/docs/decisions/2026-12-01-an-apps-configuration-is-checked-before-the-server-stores-it.md new file mode 100644 index 000000000000..7d394f73d215 --- /dev/null +++ b/docs/decisions/2026-12-01-an-apps-configuration-is-checked-before-the-server-stores-it.md @@ -0,0 +1,51 @@ +# An app's configuration is checked before the server stores it, by a method separate from the check before a run + +- **Status:** Accepted +- **Revisions:** v1 2026-12-01 (initial) +- **Deciders:** OpenMetadata maintainers +- **Guard:** `AppConfigurationCheckTest` (each shipped app refuses a configuration it cannot read, with its message, and accepts a good one; the default accepts every configuration; an app that inherits the default is not built), `AppConfigurationSaveCheckIT` (a refused configuration on POST, PUT, PATCH by id and PATCH by name, or a `move` out of the configuration, answers 400 and leaves the stored app and its schedule as they were; a caller without edit rights gets 403 before the check; an accepted configuration is stored and rescheduled) +- **Related:** none + +## Context + +An app's settings are its `appConfiguration`. The PATCH paths of `AppResource` stored the patched +app first, then deleted the scheduled job, and only then asked the app to install itself, so an app +that refused the new configuration answered 400 after the refused configuration was stored. A later +GET returned it, and every later reinstall (`/schedule`, `/restore`, `/deploy`) read it. The PUT path +deleted the scheduled job before it installed, so a refused PUT stored nothing but left the app +unscheduled. `SearchIndexApp`, `CacheWarmupApp`, `RdfIndexApp` and `DataInsightsReportApp` checked +their configuration with a message only in `validateConfig`, before a trigger. Three of them also +parse it in `init` at install, which a PATCH reached only after the store. So a configuration they +could not read was stored, and failed at the reinstall or at the next run. + +## Decision + +- `AbstractNativeApplication#validateConfigForSave(Map)` checks the configuration + an app is about to store. It reads only the configuration and has no side effect. By default it + accepts every configuration. +- It is a separate method from `validateConfig`. An app may use `validateConfig` to refuse a run + because of the server's state rather than the configuration's content, and such an app must still be + able to save its settings. The four shipped apps move their parse into the new method, and their + `validateConfig` calls it, so the check before a trigger and its messages are unchanged. +- `AppResource` runs the check on POST, PUT, and both PATCH paths, after authorization and before + the store and before any scheduler change. For a PATCH the patch is applied to the stored app in + memory to get the configuration that would be stored, and a patch that does not touch + `appConfiguration` is not checked. A refused check answers 400 with the app's message. +- `ApplicationHandler#validateConfigurationForSave` reaches the method on an instance built by the + app's constructor alone. It does not call `init`, which registers the app in the application + context and, for some apps, parses the configuration, and it does not install, schedule or store + anything, and it changes no bot or role. The handler builds an instance only for an app whose + class declares its own check, meaning the `validateConfigForSave` the class resolves is not the one + `AbstractNativeApplication` declares. An app that inherits the default is not built, because the + default accepts every configuration. A class that is not a native application, or that cannot be + found, has nothing to check. + +## Consequences + +- An app that shipped with a configuration its check now refuses is not changed by this record. The + check applies to the next write. +- A new app that validates its settings overrides `validateConfigForSave`, and its constructor must + not write anything, because the server builds an instance for each write of its configuration. + `DataInsightsReportApp`'s constructor builds a repository that registers itself in `Entity`; the + save path already did that through `AppRepository.prepare`. +- Revisit if an app needs the stored app, not only the configuration, to decide. diff --git a/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md b/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md new file mode 100644 index 000000000000..66cdcbe5403b --- /dev/null +++ b/docs/decisions/2026-12-04-the-table-mapping-of-a-version-is-one-read.md @@ -0,0 +1,76 @@ +# The table mapping of a whole ontology version is one read that counts what the caller may not view + +- **Status:** Accepted +- **Revisions:** v1 2026-12-04 (initial) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `OntologyTableMappingRulesTest`, `OntologyTableMappingsIT` +- **Related:** ADR:2026-11-22-record-statements-start-from-the-identity-table (the identity table and the join a relation follows), ADR:2026-11-21-a-table-binding-says-how-its-rows-become-records (the roles, the subject key and the row filter) + +## Context + +A statement about the records of one class reads that class's bindings. Code in the server that +needs to reason about a whole version of an ontology, such as which table identifies each class and +which column joins which tables, had no way to ask for it. It could repeat the per-class reads for +every class, which costs queries in proportion to the classes and lets a binding change between two +of them, so it would see a mapping that never existed. It could also read the stored rows directly, +which skips the caller's rights. + +A value that omits what the caller may not view looks the same as a value for a version that has +nothing more to show. A caller that acts on the whole mapping, for example by deciding that two +classes are unrelated, would act on a gap it cannot see. + +## Decision + +**The mapping of a version is one read.** `OntologyTableMappings.read(access, ontologyId, version)` +returns an `OntologyTableMapping`: every class of the version that binds an existing table, each +with its tables, subject keys, row filters, data columns and relation columns. A `null` version +means the active release. A read of the release of an ontology with no active release is a 404 that says so. The draft goes +through the same gate as the statements, a 403 without the right to read the working draft. + +**One call reads the binding rows between two equal reads of the binding revisions** of all the +classes at once, as a statement does, and returns a 409 after the same three attempts. A change that +lands between the reads is either seen whole or refused, never half seen. The draft reads the ids of its classes again after the second revision read, and a changed set is a retry like a changed revision, because a class bound for the first time during the read has no revision to compare. + +**The number of queries does not depend on the number of classes or bindings.** One query reads +each kind, in chunks of ids when a list is longer than one IN list: the ontology and its state, the +ids of the classes (twice for the draft), the revisions twice, the binding rows, the tables, the classes, the properties, +and the class hierarchy when a relation declares a range. A read runs 42 statements on MySQL for the release and 43 for the draft, for a version with 3 classes and for one with 300 classes and 600 bindings. A retry adds the statements of one attempt. + +**A part the caller may not view is counted and never named.** The answer carries `hiddenTables`, +`hiddenClasses` and `hiddenProperties`. A hidden part appears in no field and no id, name, column +path or IRI of it appears in the value, its text or its JSON. The read never fails for a hidden +part, so the caller decides what a non-zero count means for it. A caller that needs the whole +mapping refuses a value with a non-zero count. + +- `hiddenTables` counts the distinct existing tables that the classes of the version bind, and the + tables that a listed relation column joins, that the caller may not view. +- `hiddenClasses` counts the classes of the version that bind an existing table and that the caller + may not view. +- `hiddenProperties` counts the properties of the version that a column of a viewable table binds + and that the caller may not view, whether or not the caller may view the class that binds the table. + +**What is left out silently.** A deleted table is left out and counted nowhere, as the list of the +bindings of a class leaves it out. A class with no existing bound table is left out. A column whose +property the version does not declare is listed by its path as absent from the version. A column +that the table no longer has is listed by its path apart. A row filter that no longer applies is +given as a reason, a sentence that names the table and the column and never a value. + +**A relation column lists the classes that identify its target.** They are the classes the caller +may view whose identity table is the join's target table. When the relation declares a range, only +those that are in the range or are subclasses of a class in it, as that version declares them. + +**This is a Java API and has no endpoint.** The first caller is code in the same server that +already holds the caller's identity, and it needs a value to reason over, not a page to render. An +endpoint would add a response schema, a page size and a cursor over a read that must be consistent +as a whole, and none of them has a user yet. + +## Consequences + +A caller gets a mapping it can trust to be complete when the three counts are zero, and it can tell +when it is not. The cost of a read grows with the size of the data it returns, not with the number +of classes it asks about. A binding write that races a read makes the read retry or fail with a 409 +and never return a mix. + +The value holds the columns of each viewable table as the catalog holds them, so a mapping of a +large version is large. A caller that needs one class reads it with the statements. If a client +outside the server ever needs the whole mapping, an endpoint can wrap `read` without changing it. diff --git a/docs/decisions/2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index.md b/docs/decisions/2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index.md new file mode 100644 index 000000000000..d08867ffc84a --- /dev/null +++ b/docs/decisions/2026-12-05-the-lookups-of-generated-tests-and-their-tasks-use-an-index.md @@ -0,0 +1,84 @@ +# The lookups of generated tests and of the tasks that propose them read an index on the generating class + +- **Status:** Accepted +- **Revisions:** v1 2026-12-05 (initial); v2 2026-12-05 (a value a column cannot read is NULL) +- **Deciders:** Ontology Studio maintainers +- **Guard:** `GeneratedLookupIndexMigrationIT` +- **Related:** ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test (the generated tests, their suggestion tasks and the reconcile that reads both) + +## Context + +A test case that a shape check generated carries `generatedBy`, and the task that proposes one is a +suggestion task whose payload holds a test case proposal as JSON text. Four statements look them up: + +| Statement | Where | Filter before | +|---|---|---| +| Generated tests of one class | `TimeSeriesDAOs.TestCaseDAO.findGeneratedIdsOfClass` | `generatedBy.class.id` read inside the JSON | +| All generated tests | `TimeSeriesDAOs.TestCaseDAO.findGeneratedIds` | `generatedBy` present in the JSON | +| All test case tasks | `FeedDAOs.TaskDAO.findTestCaseSuggestionIds` | `payload.suggestionType` read inside the JSON | +| Test case tasks of one class | `FeedDAOs.TaskDAO.findTestCaseSuggestionIdsOfClass` | `payload.suggestionType` read inside the JSON, and the value `LIKE '%%'` | + +None of these filters is a column, so each statement read every row of `test_case` or +`task_entity`. The reconcile runs the first two kinds once per run, and every read of the proposal +state of a check runs the per-class ones, so each pays a full scan of two tables that grow with the +whole deployment. + +The per-class task statement was also wider than its name. A task of class A whose proposal lists +class B as a concept it read matched the `LIKE` for B. Its caller keeps only the tasks whose +generating class is B, so the extra rows were read and dropped. + +## Decision + +**The class that generated a row is a stored column of its own, with an index.** Both engines, in +the 2.2.0 migration: + +- `test_case.generatedByClassId` is `generatedBy.class.id`. It is NULL for every test case that no + shape generated. +- `task_entity.testCaseClassId` is `generatedBy.class.id` of the proposal in the payload, when the + payload's `suggestionType` is `TestCase`. It is NULL for every other task. +- **A value a column cannot read is NULL, and never fails a write or the migration.** Both columns + keep the class id only when it is 36 characters, which is the width of a UUID and of the column. + `testCaseClassId` is also NULL when the proposal is not JSON. MySQL tests `json_valid` in the + expression. PostgreSQL cannot catch a cast error inside a generated expression, so the column + calls `test_case_proposal_class_id(text)`, an `IMMUTABLE` function the same 2.2.0 file creates + with `CREATE OR REPLACE FUNCTION` before the column. It removes the `\u0000` escape, which + `jsonb` refuses, casts the text to `jsonb`, reads the class, and returns NULL on any error + (`EXCEPTION WHEN others`). Without these guards a task whose value is not JSON, or a class id + longer than 36 characters, failed its own write, and the migration failed on a database that + already held such a row. +- `idx_test_case_generated_by_class` and `idx_task_test_case_class` index them. PostgreSQL's are + partial (`WHERE ... IS NOT NULL`), because all but a few hundred rows are NULL; MySQL has no + partial index. + +Each statement now filters on its column: `= :classId`, or `IS NOT NULL` for the two that list all. +Each column is added only if absent, so the migration is safe to run twice. A stored generated +column fills itself from the JSON of every existing row when it is added, so no data step is needed. + +**The per-class task statement returns the tasks whose proposal was generated by the class**, no +longer every `TestCase` task whose value mentions it. Every caller already kept only those, so what +a reconcile or a read of proposal states returns does not change. + +## Measurements + +50,000 test cases and 50,000 tasks, 300 of each generated by 30 classes (10 per class). MySQL 8.4.13 +(`EXPLAIN ANALYZE` and `Handler_read_*` of one session) and PostgreSQL 15 (`EXPLAIN (ANALYZE, +BUFFERS)`), after `ANALYZE`. + +| Statement | Answer | MySQL rows read before / after | PostgreSQL buffers before / after | +|---|---|---|---| +| Tests of one class | 10 | 50,001 / 11 | 8,334 / 11 | +| All generated tests | 300 | 50,001 / 301 | 8,334 / 299 | +| All test case tasks | 300 | 50,001 / 301 | 7,143 / 299 | +| Tasks of one class | 10 (18 before) | 50,001 / 11 | 7,143 / 11 | + +Before, MySQL took a table scan and PostgreSQL a sequential scan on every statement. After, MySQL +takes an index lookup or index range scan, and PostgreSQL a bitmap scan of the index. Adding the two +columns and their indexes to the 50,000-row tables took 3.9 s on MySQL and 1.2 s on PostgreSQL. + +## Consequences + +- A lookup reads rows in proportion to its answer, on both engines. +- Each of the two tables gains one stored column and one index. Adding a stored column rewrites the + table once, at the upgrade. +- A new lookup of generated tests or of their tasks filters on these columns. The test fails when a + statement goes back to reading the JSON, because it counts the rows the database reads. diff --git a/docs/generated/api-reference.md b/docs/generated/api-reference.md index 14460e1bc0be..db1805fbf9a3 100644 --- a/docs/generated/api-reference.md +++ b/docs/generated/api-reference.md @@ -1379,6 +1379,7 @@ hand-edit; run `make generate-api-reference` (or `make generate-reference-docs`) | `POST` | `/v1/ontologies/{id}/library/{packId}/preview` | Preview verified library modules as native ontology draft operations | | `POST` | `/v1/ontologies/{id}/library/{packId}/review` | Review verified library modules item by item before they install | | `POST` | `/v1/ontologies/{id}/library/{packId}/summary` | Review verified library modules without returning draft operations | +| `GET` | `/v1/ontologies/{id}/mappingHealth` | List what the table bindings of an ontology's classes still need before their rows can be read as records, from catalog metadata alone | | `GET` | `/v1/ontologies/{id}/references` | Find working definitions that reference an exact IRI in this ontology | | `GET` | `/v1/ontologies/{id}/releases` | List this ontology's sealed releases, newest first | | `POST` | `/v1/ontologies/{id}/releases` | Capture immutable ontology release content | diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationSaveCheckIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationSaveCheckIT.java new file mode 100644 index 000000000000..3c390517ff7e --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/AppConfigurationSaveCheckIT.java @@ -0,0 +1,347 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +import jakarta.ws.rs.core.Response; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.factories.UserTestFactory; +import org.openmetadata.it.util.OssTestServer; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.app.App; +import org.openmetadata.schema.entity.app.AppMarketPlaceDefinition; +import org.openmetadata.schema.entity.app.AppSchedule; +import org.openmetadata.schema.entity.app.AppType; +import org.openmetadata.schema.entity.app.CreateApp; +import org.openmetadata.schema.entity.app.CreateAppMarketPlaceDefinitionReq; +import org.openmetadata.schema.entity.app.NativeAppPermission; +import org.openmetadata.schema.entity.app.ScheduleTimeline; +import org.openmetadata.schema.entity.app.ScheduleType; +import org.openmetadata.schema.entity.app.ScheduledExecutionContext; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; +import org.openmetadata.service.Entity; +import org.openmetadata.service.apps.AbstractNativeApplication; +import org.openmetadata.service.apps.scheduler.AppScheduler; +import org.openmetadata.service.exception.AppException; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.search.SearchRepository; +import org.quartz.CronTrigger; +import org.quartz.SchedulerException; +import org.quartz.TriggerKey; + +/** + * Installing and removing an app changes the job store shared by every app, so this class runs + * alone, as {@link AppsResourceIT} does. + */ +@Execution(ExecutionMode.SAME_THREAD) +@Isolated +@ExtendWith(TestNamespaceExtension.class) +public class AppConfigurationSaveCheckIT { + @Test + void patchByIdWithARefusedConfigurationStoresNothing(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + App app = createCheckedApp(name, 100); + try { + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + patch( + SdkClients.adminClient(), "/v1/apps/" + app.getId(), batchSizePatch("many"))); + + assertRefused(refused); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + + @Test + void patchByNameWithARefusedConfigurationStoresNothing(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + createCheckedApp(name, 100); + try { + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + patch(SdkClients.adminClient(), "/v1/apps/name/" + name, batchSizePatch("many"))); + + assertRefused(refused); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + + @Test + void moveOutOfTheConfigurationIsChecked(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + App app = createCheckedApp(name, 100); + try { + String move = + "[{\"op\":\"move\",\"from\":\"/appConfiguration/batchSize\",\"path\":\"/description\"}]"; + + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> patch(SdkClients.adminClient(), "/v1/apps/" + app.getId(), move)); + + assertRefused(refused); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + + @Test + void aCallerWithoutEditRightsIsRefusedBeforeTheConfigurationIsChecked(TestNamespace ns) + throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + App app = createCheckedApp(name, 100); + UserTestFactory.getDataConsumer(ns); + try { + OpenMetadataException forbidden = + assertThrows( + OpenMetadataException.class, + () -> + patch( + SdkClients.dataConsumerClient(), + "/v1/apps/" + app.getId(), + batchSizePatch("many"))); + + assertEquals(403, forbidden.getStatusCode(), forbidden.getMessage()); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + + @Test + void putWithARefusedConfigurationStoresNothingAndKeepsTheSchedule(TestNamespace ns) + throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + createCheckedApp(name, 100); + try { + CreateApp replacement = + checkedRequest(name, "many").withAppSchedule(schedule(ScheduleTimeline.MONTHLY)); + + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.PUT, "/v1/apps", replacement, App.class)); + + assertRefused(refused); + assertStoredUnchanged(name); + } finally { + uninstall(name); + } + } + + @Test + void postWithARefusedConfigurationStoresNoApp(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + try { + OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .getHttpClient() + .execute( + HttpMethod.POST, "/v1/apps", checkedRequest(name, "many"), App.class)); + + assertRefused(refused); + OpenMetadataException missing = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.GET, "/v1/apps/name/" + name, null, App.class)); + assertEquals(404, missing.getStatusCode(), missing.getMessage()); + assertNull(scheduledTrigger(name)); + } finally { + uninstallIfPresent(name); + } + } + + @Test + void anAcceptedConfigurationIsStoredAndTheAppIsRescheduled(TestNamespace ns) throws Exception { + assumeEmbeddedServer(); + String name = createCheckedDefinition(ns); + App app = createCheckedApp(name, 100); + try { + patch( + SdkClients.adminClient(), + "/v1/apps/" + app.getId(), + "[{\"op\":\"replace\",\"path\":\"/appConfiguration/batchSize\",\"value\":250}," + + "{\"op\":\"replace\",\"path\":\"/appSchedule/scheduleTimeline\"," + + "\"value\":\"Monthly\"}]"); + + App stored = getApp(name); + assertEquals(Map.of("batchSize", 250), stored.getAppConfiguration()); + assertEquals(ScheduleTimeline.MONTHLY, stored.getAppSchedule().getScheduleTimeline()); + assertEquals("0 0 0 1 * ?", scheduledTrigger(name).getCronExpression()); + } finally { + uninstall(name); + } + } + + private static void assumeEmbeddedServer() { + assumeFalse(OssTestServer.isExternalMode(), "Reads the scheduler inside the embedded server"); + } + + private static String createCheckedDefinition(TestNamespace ns) { + String name = ns.shortPrefix() + "Config" + UUID.randomUUID().toString().substring(0, 6); + AppMarketPlaceDefinition definition = + SdkClients.adminClient() + .getHttpClient() + .execute( + HttpMethod.POST, + "/v1/apps/marketplace", + new CreateAppMarketPlaceDefinitionReq() + .withName(name) + .withDisplayName("Configuration Test") + .withDescription("Configuration check before save") + .withFeatures("configuration") + .withDeveloper("Test Developer") + .withDeveloperUrl("https://www.example.com") + .withPrivacyPolicyUrl("https://www.example.com/privacy") + .withSupportEmail("support@example.com") + .withClassName(CheckedConfigurationApp.class.getName()) + .withAppType(AppType.Internal) + .withScheduleType(ScheduleType.Scheduled) + .withRuntime(new ScheduledExecutionContext().withEnabled(true)) + .withAppConfiguration(Map.of()) + .withPermission(NativeAppPermission.All), + AppMarketPlaceDefinition.class); + ns.trackRoot(Entity.APP_MARKET_PLACE_DEF, definition); + return name; + } + + private static CreateApp checkedRequest(String name, Object batchSize) { + return new CreateApp() + .withName(name) + .withAppConfiguration(Map.of("batchSize", batchSize)) + .withAppSchedule(schedule(ScheduleTimeline.HOURLY)); + } + + private static AppSchedule schedule(ScheduleTimeline timeline) { + return new AppSchedule().withScheduleTimeline(timeline); + } + + private static App createCheckedApp(String name, Object batchSize) { + return SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.POST, "/v1/apps", checkedRequest(name, batchSize), App.class); + } + + private static String batchSizePatch(String value) { + return "[{\"op\":\"replace\",\"path\":\"/appConfiguration/batchSize\",\"value\":\"" + + value + + "\"}]"; + } + + private static void patch(OpenMetadataClient client, String path, String body) { + client + .getHttpClient() + .executeForString( + HttpMethod.PATCH, + path, + body, + RequestOptions.builder().header("Content-Type", "application/json-patch+json").build()); + } + + private static App getApp(String name) { + return SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.GET, "/v1/apps/name/" + name, null, App.class); + } + + private static void uninstall(String name) { + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.DELETE, "/v1/apps/name/" + name + "?hardDelete=true", null, Void.class); + } + + private static void uninstallIfPresent(String name) { + try { + uninstall(name); + } catch (OpenMetadataException absent) { + assertEquals(404, absent.getStatusCode(), absent.getMessage()); + } + } + + private static CronTrigger scheduledTrigger(String name) throws SchedulerException { + return (CronTrigger) + AppScheduler.getInstance() + .getScheduler() + .getTrigger(new TriggerKey(name, AppScheduler.APPS_TRIGGER_GROUP)); + } + + private static void assertRefused(OpenMetadataException refused) { + assertEquals(400, refused.getStatusCode(), refused.getMessage()); + assertTrue( + refused.getMessage().contains("Invalid checked configuration: batchSize must be a number"), + refused.getMessage()); + } + + private static void assertStoredUnchanged(String name) throws SchedulerException { + App stored = getApp(name); + assertEquals(Map.of("batchSize", 100), stored.getAppConfiguration()); + assertEquals(ScheduleTimeline.HOURLY, stored.getAppSchedule().getScheduleTimeline()); + assertEquals("0 0 * ? * *", scheduledTrigger(name).getCronExpression()); + } + + /** An app that reads {@code batchSize} as a number and refuses any other configuration. */ + public static final class CheckedConfigurationApp extends AbstractNativeApplication { + public CheckedConfigurationApp(CollectionDAO collectionDAO, SearchRepository searchRepository) { + super(collectionDAO, searchRepository); + } + + @Override + public void validateConfigForSave(Map config) { + if (!(config.get("batchSize") instanceof Number)) { + throw AppException.byMessage( + Response.Status.BAD_REQUEST, + "Invalid checked configuration: batchSize must be a number"); + } + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BotUserRoleRecoveryIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BotUserRoleRecoveryIT.java new file mode 100644 index 000000000000..c0a2bc4220ba --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BotUserRoleRecoveryIT.java @@ -0,0 +1,119 @@ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.CreateBot; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.auth.JWTAuthMechanism; +import org.openmetadata.schema.auth.JWTTokenExpiry; +import org.openmetadata.schema.entity.Bot; +import org.openmetadata.schema.entity.teams.AuthenticationMechanism; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.service.Entity; +import org.openmetadata.service.migration.utils.v1114.MigrationUtil; + +/** + * The step that restores a bot user's default role gives the role back to a bot user that holds + * none, and leaves a bot user that holds another role as it is. + */ +@Isolated("Runs the role restore step over every bot in the shared database") +@ExtendWith(TestNamespaceExtension.class) +class BotUserRoleRecoveryIT { + private static final String DEFAULT_ROLE = "ApplicationBotRole"; + private static final String OTHER_ROLE = "DataConsumer"; + + @Test + void restoreGivesDefaultRoleOnlyToBotUserWithoutAnyRole(TestNamespace ns) { + final User botUser = createBotWithUser(ns); + final String userId = botUser.getId().toString(); + final String defaultRoleId = roleId(DEFAULT_ROLE); + final String otherRoleId = roleId(OTHER_ROLE); + + replaceRoles(userId, otherRoleId); + runRestore(); + assertEquals(List.of(otherRoleId), roleIds(userId)); + + replaceRoles(userId, null); + runRestore(); + assertEquals(List.of(defaultRoleId), roleIds(userId)); + } + + private static User createBotWithUser(TestNamespace ns) { + final String name = "rolerecoverybot" + UUID.randomUUID().toString().substring(0, 8); + final AuthenticationMechanism auth = + new AuthenticationMechanism() + .withAuthType(AuthenticationMechanism.AuthType.JWT) + .withConfig(new JWTAuthMechanism().withJWTTokenExpiry(JWTTokenExpiry.Unlimited)); + final User user = + SdkClients.adminClient() + .users() + .create( + new CreateUser() + .withName(name) + .withEmail(name + "@test.com") + .withIsBot(true) + .withAuthenticationMechanism(auth)); + ns.trackRoot(Entity.USER, user.getId()); + final Bot bot = + SdkClients.adminClient().bots().create(new CreateBot().withName(name).withBotUser(name)); + ns.trackRoot(Entity.BOT, bot.getId()); + return user; + } + + private static String roleId(String roleName) { + return SdkClients.adminClient().roles().getByName(roleName).getId().toString(); + } + + private static void runRestore() { + TestSuiteBootstrap.getJdbi() + .useHandle( + handle -> + MigrationUtil.restoreBotUserRolesIfMissing( + handle, TestSuiteBootstrap.getConnectionType())); + } + + private static void replaceRoles(String userId, String roleId) { + TestSuiteBootstrap.getJdbi() + .useHandle( + handle -> { + handle + .createUpdate( + "DELETE FROM entity_relationship WHERE fromId = :userId" + + " AND fromEntity = 'user' AND toEntity = 'role'") + .bind("userId", userId) + .execute(); + if (roleId != null) { + handle + .createUpdate( + "INSERT INTO entity_relationship" + + " (fromId, toId, fromEntity, toEntity, relation)" + + " VALUES (:userId, :roleId, 'user', 'role', 10)") + .bind("userId", userId) + .bind("roleId", roleId) + .execute(); + } + }); + } + + private static List roleIds(String userId) { + return TestSuiteBootstrap.getJdbi() + .withHandle( + handle -> + handle + .createQuery( + "SELECT toId FROM entity_relationship WHERE fromId = :userId" + + " AND fromEntity = 'user' AND toEntity = 'role' ORDER BY toId") + .bind("userId", userId) + .mapTo(String.class) + .list()); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java new file mode 100644 index 000000000000..6b78f1171795 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/GeneratedLookupIndexMigrationIT.java @@ -0,0 +1,506 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.MetricMigrationSqlFixture.currentConnectionType; +import static org.openmetadata.it.tests.MetricMigrationSqlFixture.readMigrationScripts; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import org.jdbi.v3.core.Handle; +import org.jdbi.v3.core.Jdbi; +import org.jdbi.v3.core.statement.PreparedBatch; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.jdbi3.FeedDAOs; +import org.openmetadata.service.jdbi3.TimeSeriesDAOs; +import org.openmetadata.service.jdbi3.locator.ConnectionType; + +/** + * Runs the 2.2.0 statements that add the class columns of generated test cases and of the tasks + * that propose one, on tables that already hold 20,000 rows each, then reads each of the four + * lookups and counts the rows the database reads for it. Drops the columns first, so the rows are + * the ones a database written before the migration holds, and restores them at the end. + */ +@Isolated("drops and adds the lookup columns of two tables that every test shares") +class GeneratedLookupIndexMigrationIT { + private static final int ROWS = 20_000; + private static final int CLASSES = 20; + private static final int GENERATED_PER_CLASS = 10; + private static final String PREFIX = "gli-"; + private static final String MARKER = "generatedbyclassid"; + private static final String TEST_CASE = "test_case"; + private static final String TASK = "task_entity"; + + @Test + void eachLookupReadsRowsInProportionToItsAnswerOnceTheMigrationRanOverExistingRows() + throws Exception { + final ConnectionType engine = currentConnectionType(); + final List migration = lookupMigration(engine); + final Jdbi jdbi = TestSuiteBootstrap.getJdbi(); + final List classes = classIds(); + final AtomicReference planted = new AtomicReference<>(); + final String shapeClass = UUID.randomUUID().toString(); + final List shapes = shapes(shapeClass); + final List earlyTasks = new ArrayList<>(); + final List earlyTests = new ArrayList<>(); + final List lateTasks = new ArrayList<>(); + final List lateTests = new ArrayList<>(); + try { + jdbi.useHandle(handle -> dropLookupColumns(handle, engine)); + jdbi.useHandle(handle -> planted.set(insertRows(handle, engine, classes))); + jdbi.useHandle( + handle -> insertShapesBeforeTheMigration(handle, engine, shapes, earlyTasks, earlyTests)); + jdbi.useHandle(handle -> migration.forEach(handle::execute)); + jdbi.useHandle(handle -> migration.forEach(handle::execute)); + jdbi.useHandle(handle -> insertShapesThroughTheDaos(handle, shapes, lateTasks, lateTests)); + jdbi.useHandle(handle -> analyze(handle, engine)); + + assertAllLookups(jdbi, engine, planted.get(), classes.get(3)); + jdbi.useHandle( + handle -> { + assertShapeColumns( + handle, shapes, earlyTasks, earlyTests, "written before the migration"); + assertShapeColumns(handle, shapes, lateTasks, lateTests, "written through the DAOs"); + }); + assertShapeLookups( + jdbi, engine, shapes, shapeClass, earlyTasks, earlyTests, lateTasks, lateTests); + } finally { + jdbi.useHandle( + handle -> deleteRows(handle, allOf(earlyTasks, lateTasks), allOf(earlyTests, lateTests))); + jdbi.useHandle(handle -> migration.forEach(handle::execute)); + } + } + + private static void assertAllLookups( + final Jdbi jdbi, final ConnectionType engine, final Planted planted, final String clazz) { + final Read testsOfClass = + measure(jdbi, engine, TEST_CASE, h -> testDao(h).findGeneratedIdsOfClass(clazz)); + assertEquals(planted.tests().get(clazz), Set.copyOf(testsOfClass.ids()), "tests of one class"); + assertBounded(testsOfClass, "generated tests of one class"); + + final Read allTests = measure(jdbi, engine, TEST_CASE, h -> testDao(h).findGeneratedIds()); + assertTrue(allTests.ids().containsAll(union(planted.tests())), "every generated test"); + assertBounded(allTests, "all generated tests"); + + final Read tasksOfClass = + measure(jdbi, engine, TASK, h -> taskDao(h).findTestCaseSuggestionIdsOfClass(clazz)); + assertEquals(planted.tasks().get(clazz), Set.copyOf(tasksOfClass.ids()), "tasks of one class"); + assertBounded(tasksOfClass, "tasks of one class"); + + final Read allTasks = measure(jdbi, engine, TASK, h -> taskDao(h).findTestCaseSuggestionIds()); + assertTrue(allTasks.ids().containsAll(union(planted.tasks())), "every test case task"); + assertTrue( + Collections.disjoint(allTasks.ids(), planted.imitators()), + "a task that proposes a description is not a test case task"); + assertBounded(allTasks, "all test case tasks"); + } + + private static Set union(final Map> byClass) { + final Set all = new HashSet<>(); + byClass.values().forEach(all::addAll); + return all; + } + + private static void assertBounded(final Read read, final String what) { + assertEquals(0, read.scans(), what + " scans the table"); + assertTrue( + read.rowsRead() <= 2L * read.ids().size() + 10, + what + " read " + read.rowsRead() + " rows for " + read.ids().size() + " answers"); + } + + private static TimeSeriesDAOs.TestCaseDAO testDao(final Handle handle) { + return handle.attach(TimeSeriesDAOs.TestCaseDAO.class); + } + + private static FeedDAOs.TaskDAO taskDao(final Handle handle) { + return handle.attach(FeedDAOs.TaskDAO.class); + } + + // ---- what the database counted -------------------------------------------------------------- + + private record Read(List ids, long rowsRead, long scans) {} + + private static Read measure( + final Jdbi jdbi, + final ConnectionType engine, + final String table, + final Function> lookup) { + return jdbi.inTransaction( + handle -> { + final long[] before = counters(handle, engine, table); + final List ids = lookup.apply(handle); + final long[] after = counters(handle, engine, table); + return new Read(ids, after[0] - before[0], after[1] - before[1]); + }); + } + + /** Rows read so far in this transaction or session, and the table scans among them. */ + private static long[] counters( + final Handle handle, final ConnectionType engine, final String table) { + return engine == ConnectionType.MYSQL ? mysqlCounters(handle) : postgresCounters(handle, table); + } + + private static long[] mysqlCounters(final Handle handle) { + final Map status = new HashMap<>(); + handle + .createQuery("SHOW SESSION STATUS LIKE 'Handler_read%'") + .map((rs, ctx) -> Map.entry(rs.getString(1), rs.getLong(2))) + .forEach(entry -> status.put(entry.getKey(), entry.getValue())); + final long scans = status.get("Handler_read_rnd_next"); + final long indexed = status.get("Handler_read_next") + status.get("Handler_read_key"); + return new long[] {scans + indexed + status.get("Handler_read_rnd"), scans}; + } + + private static long[] postgresCounters(final Handle handle, final String table) { + final long[] counted = + handle + .createQuery( + "SELECT seq_scan, seq_tup_read + idx_tup_fetch FROM pg_stat_xact_user_tables " + + "WHERE relname = :table") + .bind("table", table) + .map((rs, ctx) -> new long[] {rs.getLong(2), rs.getLong(1)}) + .findOne() + .orElse(new long[] {0, 0}); + return counted; + } + + // ---- rows a column cannot read --------------------------------------------------------------- + + /** A proposal or test case shape, and the class the columns must read from it, or null. */ + private record Shape(String name, String proposal, String testClass, String expected) {} + + private static List shapes(final String clazz) { + final String longId = "y".repeat(40); + return List.of( + new Shape("valid", proposalOf(clazz, "q"), clazz, clazz), + new Shape("nul-escape", proposalOf(clazz, "q\\u0000"), clazz, clazz), + new Shape("not-json", "this is not json", null, null), + new Shape("long-id", proposalOf(longId, "q"), longId, null)); + } + + private static String proposalOf(final String clazz, final String note) { + return "{\"note\":\"" + note + "\",\"generatedBy\":{\"class\":{\"id\":\"" + clazz + "\"}}}"; + } + + private static void insertShapesBeforeTheMigration( + final Handle handle, + final ConnectionType engine, + final List shapes, + final List taskIds, + final List testIds) { + final String cast = engine == ConnectionType.MYSQL ? ":json" : "CAST(:json AS jsonb)"; + for (final Shape shape : shapes) { + final String taskId = UUID.randomUUID().toString(); + handle + .createUpdate( + "INSERT INTO task_entity (id, json, fqnHash) VALUES (:id, " + cast + ", :hash)") + .bind("id", taskId) + .bind("json", shapeTaskJson(taskId, shape)) + .bind("hash", PREFIX + "early-k-" + shape.name()) + .execute(); + taskIds.add(taskId); + final String testId = UUID.randomUUID().toString(); + handle + .createUpdate("INSERT INTO test_case (json, fqnHash) VALUES (" + cast + ", :hash)") + .bind("json", shapeTestJson(testId, shape)) + .bind("hash", PREFIX + "early-t-" + shape.name()) + .execute(); + testIds.add(testId); + } + } + + private static void insertShapesThroughTheDaos( + final Handle handle, + final List shapes, + final List taskIds, + final List testIds) { + final FeedDAOs.TaskDAO tasks = taskDao(handle); + final TimeSeriesDAOs.TestCaseDAO tests = testDao(handle); + for (final Shape shape : shapes) { + final String taskId = UUID.randomUUID().toString(); + tasks.insertTask(taskId, shapeTaskJson(taskId, shape), PREFIX + "late-k-" + shape.name()); + taskIds.add(taskId); + final String testId = UUID.randomUUID().toString(); + tests.insert( + tests.getTableName(), + tests.getNameHashColumn(), + PREFIX + "late-t-" + shape.name(), + shapeTestJson(testId, shape)); + testIds.add(testId); + } + } + + private static String shapeTaskJson(final String id, final Shape shape) { + final Map task = new LinkedHashMap<>(); + task.put("id", id); + task.put("taskId", "GLI-" + shape.name()); + task.put("name", PREFIX + "shape-" + shape.name()); + task.put("category", "MetadataUpdate"); + task.put("type", "Suggestion"); + task.put("status", "Open"); + task.put("createdAt", 1L); + task.put("updatedAt", 1L); + task.put( + "payload", + Map.of( + "suggestionType", "TestCase", + "fieldPath", "testCases", + "suggestedValue", shape.proposal())); + return JsonUtils.pojoToJson(task); + } + + private static String shapeTestJson(final String id, final Shape shape) { + return testCaseJson(id, 0, shape.testClass()) + .replace("gli.db.schema.t0", "gli.db.schema." + shape.name()); + } + + /** Reads the generated columns of the rows of each shape, which are in the order of the shapes. */ + private static void assertShapeColumns( + final Handle handle, + final List shapes, + final List taskIds, + final List testIds, + final String when) { + for (int index = 0; index < shapes.size(); index++) { + final Shape shape = shapes.get(index); + assertEquals( + shape.expected(), + column( + handle, "SELECT testCaseClassId FROM task_entity WHERE id = ?", taskIds.get(index)), + "task of shape " + shape.name() + " " + when); + assertEquals( + readableClass(shape.testClass()), + column( + handle, "SELECT generatedByClassId FROM test_case WHERE id = ?", testIds.get(index)), + "test case of shape " + shape.name() + " " + when); + } + } + + private static List allOf(final List first, final List second) { + final List both = new ArrayList<>(first); + both.addAll(second); + return both; + } + + private static String readableClass(final String clazz) { + return clazz != null && clazz.length() == 36 ? clazz : null; + } + + private static String column(final Handle handle, final String sql, final String id) { + return handle.createQuery(sql).bind(0, id).mapTo(String.class).one(); + } + + /** The lookups find the rows of the readable shapes, written either way, and read an index. */ + private static void assertShapeLookups( + final Jdbi jdbi, + final ConnectionType engine, + final List shapes, + final String clazz, + final List earlyTasks, + final List earlyTests, + final List lateTasks, + final List lateTests) { + final Set tasks = new HashSet<>(); + final Set tests = new HashSet<>(); + for (int index = 0; index < shapes.size(); index++) { + if (shapes.get(index).expected() != null) { + tasks.add(earlyTasks.get(index)); + tasks.add(lateTasks.get(index)); + } + if (readableClass(shapes.get(index).testClass()) != null) { + tests.add(earlyTests.get(index)); + tests.add(lateTests.get(index)); + } + } + final Read tasksOfClass = + measure(jdbi, engine, TASK, h -> taskDao(h).findTestCaseSuggestionIdsOfClass(clazz)); + assertEquals(tasks, Set.copyOf(tasksOfClass.ids()), "tasks of the class that shapes name"); + assertBounded(tasksOfClass, "tasks of the class that shapes name"); + final Read testsOfClass = + measure(jdbi, engine, TEST_CASE, h -> testDao(h).findGeneratedIdsOfClass(clazz)); + assertEquals(tests, Set.copyOf(testsOfClass.ids()), "tests of the class that shapes name"); + assertBounded(testsOfClass, "tests of the class that shapes name"); + } + + // ---- the migration and the rows it runs over ------------------------------------------------ + + /** Every statement of the 2.2.0 file, as the migration runs them. */ + private static List lookupMigration(final ConnectionType engine) throws Exception { + final List all = readMigrationScripts(engine, "2.2.0").schemaStatements(); + assertTrue( + all.stream().anyMatch(sql -> sql.toLowerCase(Locale.ROOT).contains(MARKER)), + "no 2.2.0 statement adds the generated test class column"); + return all; + } + + private static void dropLookupColumns(final Handle handle, final ConnectionType engine) { + if (engine == ConnectionType.MYSQL) { + handle.execute( + "ALTER TABLE test_case DROP INDEX idx_test_case_generated_by_class, " + + "DROP COLUMN generatedByClassId"); + handle.execute( + "ALTER TABLE task_entity DROP INDEX idx_task_test_case_class, " + + "DROP COLUMN testCaseClassId"); + } else { + handle.execute("DROP INDEX IF EXISTS idx_test_case_generated_by_class"); + handle.execute("ALTER TABLE test_case DROP COLUMN IF EXISTS generatedbyclassid"); + handle.execute("DROP INDEX IF EXISTS idx_task_test_case_class"); + handle.execute("ALTER TABLE task_entity DROP COLUMN IF EXISTS testcaseclassid"); + } + } + + private static void analyze(final Handle handle, final ConnectionType engine) { + if (engine == ConnectionType.MYSQL) { + handle.createQuery("ANALYZE TABLE test_case, task_entity").mapToMap().list(); + } else { + handle.execute("ANALYZE test_case"); + handle.execute("ANALYZE task_entity"); + } + } + + private static void deleteRows( + final Handle handle, final List taskIds, final List testIds) { + handle.execute("DELETE FROM test_case WHERE fqnHash LIKE '" + PREFIX + "%'"); + handle.execute("DELETE FROM task_entity WHERE fqnHash LIKE '" + PREFIX + "%'"); + taskIds.forEach(id -> handle.execute("DELETE FROM task_entity WHERE id = ?", id)); + testIds.forEach(id -> handle.execute("DELETE FROM test_case WHERE id = ?", id)); + } + + private static List classIds() { + final List classes = new ArrayList<>(); + for (int index = 0; index < CLASSES; index++) { + classes.add(UUID.randomUUID().toString()); + } + return classes; + } + + /** + * Fills each table with {@link #ROWS} rows. Of the test cases, {@link #GENERATED_PER_CLASS} per + * class carry a generating class. Of the tasks, the same number per class propose a test case, + * and as many more propose another change with the same JSON in their value, which no lookup may + * return. + */ + private static Planted insertRows( + final Handle handle, final ConnectionType engine, final List classes) { + final String cast = engine == ConnectionType.MYSQL ? ":json" : "CAST(:json AS jsonb)"; + final PreparedBatch tests = + handle.prepareBatch( + "INSERT INTO test_case (json, fqnHash) VALUES (" + cast + ", :fqnHash)"); + final PreparedBatch tasks = + handle.prepareBatch( + "INSERT INTO task_entity (id, json, fqnHash) VALUES (:id, " + cast + ", :fqnHash)"); + final Planted planted = new Planted(new HashMap<>(), new HashMap<>(), new HashSet<>()); + for (int index = 0; index < ROWS; index++) { + final String clazz = classes.get(index % CLASSES); + final boolean generates = index < CLASSES * GENERATED_PER_CLASS; + final String testId = UUID.randomUUID().toString(); + tests + .bind("json", testCaseJson(testId, index, generates ? clazz : null)) + .bind("fqnHash", PREFIX + "t" + index) + .add(); + final String taskId = UUID.randomUUID().toString(); + tasks + .bind("id", taskId) + .bind("json", taskJson(taskId, index, clazz)) + .bind("fqnHash", PREFIX + "k" + index) + .add(); + planted.note(index, clazz, testId, taskId); + } + tests.execute(); + tasks.execute(); + return planted; + } + + /** The ids this test wrote, by the class they name. */ + private record Planted( + Map> tests, Map> tasks, Set imitators) { + void note(final int index, final String clazz, final String testId, final String taskId) { + final int span = CLASSES * GENERATED_PER_CLASS; + if (index < span) { + tests.computeIfAbsent(clazz, key -> new HashSet<>()).add(testId); + tasks.computeIfAbsent(clazz, key -> new HashSet<>()).add(taskId); + } else if (index < 2 * span) { + imitators.add(taskId); + } + } + } + + private static String testCaseJson(final String id, final int index, final String clazz) { + final Map test = new LinkedHashMap<>(); + test.put("id", id); + test.put("name", PREFIX + "t" + index); + test.put("entityLink", "<#E::table::gli.db.schema.t" + index + ">"); + test.put("entityFQN", "gli.db.schema.t" + index); + test.put("updatedAt", 1L); + test.put("updatedBy", "admin"); + test.put("deleted", false); + if (clazz != null) { + test.put("generatedBy", Map.of("identity", "i" + index, "class", Map.of("id", clazz))); + } + return JsonUtils.pojoToJson(test); + } + + /** + * Tasks 0 to 199 propose a test case, 200 to 399 propose a description whose value reads like a + * test case proposal of the same class, the rest propose a description. + */ + private static String taskJson(final String id, final int index, final String clazz) { + final int span = CLASSES * GENERATED_PER_CLASS; + final boolean proposes = index < span; + final boolean imitates = index >= span && index < 2 * span; + final String value = + proposes || imitates + ? JsonUtils.pojoToJson( + Map.of( + "generatedBy", + Map.of("identity", "i" + index, "class", Map.of("id", clazz)), + "testCase", + Map.of("name", "n" + index))) + : "a description " + index; + final Map task = new LinkedHashMap<>(); + task.put("id", id); + task.put("taskId", "GLI-" + index); + task.put("name", PREFIX + "k" + index); + task.put("category", "MetadataUpdate"); + task.put("type", "Suggestion"); + task.put("status", "Open"); + task.put("createdAt", 1L); + task.put("updatedAt", 1L); + task.put( + "payload", + Map.of( + "suggestionType", + proposes ? "TestCase" : "Description", + "fieldPath", + proposes ? "testCases" : "description", + "suggestedValue", + value)); + return JsonUtils.pojoToJson(task); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java new file mode 100644 index 000000000000..b34a4ff5cdfb --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceCountIT.java @@ -0,0 +1,139 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.health; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.util.SqlQueryCounter; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.service.Entity; + +/** + * What the mapping health read costs, counted in the SQL statements one request runs. A page of + * one hundred bindings, each with a sensitive key and a column type finding, runs the same + * statements as a page of five, whether or not the identity table of the class is on the page. + */ +@Isolated("Counts SQL statements while serving the mapping health read over HTTP") +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyMappingAdviceCountIT extends BaseOntologyApprovalIT { + private static final int FULL_PAGE = 100; + private static final int SMALL_PAGE = 5; + + private static final int SELECTS_WITH_IDENTITY_ON_PAGE = 53; + private static final int SELECTS_WITH_IDENTITY_OFF_PAGE = 53; + + @Test + void aPageOfOneHundredBindingsRunsNoMoreStatementsThanAPageOfFive(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + bindTables(ns, ontology, customer, FULL_PAGE, false); + + final int small = selects(ontology, SMALL_PAGE); + final int full = selects(ontology, FULL_PAGE); + + assertEquals(SELECTS_WITH_IDENTITY_ON_PAGE, full); + assertEquals(small, full); + assertEquals( + 3 * FULL_PAGE, health(admin(), ontology, "?limit=" + FULL_PAGE).getEntries().size()); + } + + @Test + void aPageWhoseIdentityTableIsOnAnotherPageRunsTheSameStatementsAsAPageOfFive( + final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + bindTables(ns, ontology, customer, FULL_PAGE + 1, true); + + final int small = selects(ontology, SMALL_PAGE); + final int full = selects(ontology, FULL_PAGE); + + assertEquals(SELECTS_WITH_IDENTITY_OFF_PAGE, full); + assertEquals(small, full); + assertEquals( + 2 * FULL_PAGE, + health(admin(), ontology, "?limit=" + FULL_PAGE).getEntries().stream() + .filter(entry -> entry.getType().value().equals("sensitiveKeyColumn")) + .count()); + } + + /** + * Binds {@code count} tables to the class, each with a table tag and a text column bound to an + * integer property. The identity table is the first by table id, or the last when {@code + * identityLast}, and the rest contribute. + */ + private static void bindTables( + final TestNamespace ns, + final Ontology ontology, + final OntologyConcept concept, + final int count, + final boolean identityLast) { + final var age = IndependentOntologyMappingAdviceIT.integerProperty(ontology, concept, "age"); + final var schema = schema(ns); + final List tables = new ArrayList<>(); + for (int i = 0; i < count; i++) { + tables.add( + IndependentOntologyMappingAdviceIT.customers( + schema, "customers_" + i, IndependentOntologyMappingAdviceIT.tag("PII.Sensitive"))); + } + tables.sort(Comparator.comparing(table -> table.getId().toString())); + final Table identity = identityLast ? tables.getLast() : tables.getFirst(); + for (int i = 0; i < count; i++) { + final Table table = tables.get(i); + put( + admin(), + concept, + binding( + table, + table == identity + ? OntologyBindingRole.IDENTITY + : OntologyBindingRole.CONTRIBUTING, + "email", + "id") + .withColumns(List.of(column(age, "age"))), + i); + } + } + + /** Asks once to fill what the server caches between requests, then counts the next request. */ + private static int selects(final Ontology ontology, final int limit) { + health(admin(), ontology, "?limit=" + limit); + try (var queries = + SqlQueryCounter.forRequests( + Entity.getJdbi(), + "select", + statement -> statement.getRenderedSql().toLowerCase(Locale.ROOT).contains("select"))) { + health(admin(), ontology, "?limit=" + limit); + return queries.count(); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceIT.java new file mode 100644 index 000000000000..c378eabf81ca --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingAdviceIT.java @@ -0,0 +1,254 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.health; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.summary; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.net.URI; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.CreateTable; +import org.openmetadata.schema.api.data.OntologyMappingHealthEntry; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.schema.type.TagLabel.TagSource; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; + +/** + * The mapping health read advises on a key column whose data is masked and on a column whose type + * cannot hold the datatype of its property, for the tables and properties the caller may view. + */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyMappingAdviceIT extends BaseOntologyApprovalIT { + private static final String INTEGER = "http://www.w3.org/2001/XMLSchema#integer"; + private static final String SENSITIVE = "PII.Sensitive"; + + @Test + void anEditorSeesTheSensitiveKeyAndTheColumnTypeThatCannotHoldItsProperty( + final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final Table customers = customers(schema(ns), "customers", tag(SENSITIVE)); + final var age = integerProperty(ontology, customer, "age"); + put( + admin(), + customer, + binding(customers, OntologyBindingRole.IDENTITY, "email") + .withColumns(List.of(column(age, "age"))), + 0L); + + final var entries = health(admin(), ontology, "").getEntries(); + + assertEquals( + List.of("sensitiveKeyColumn Customer customers", "columnTypeMismatch Customer customers"), + summary(entries)); + assertEquals( + "{\"type\":\"sensitiveKeyColumn\",\"concept\":\"Customer\",\"asset\":\"customers\"," + + "\"columnPath\":[\"email\"]}", + json(entries.get(0))); + assertEquals( + "{\"type\":\"columnTypeMismatch\",\"concept\":\"Customer\",\"asset\":\"customers\"," + + "\"property\":\"age\",\"columnPath\":[\"age\"],\"dataType\":\"VARCHAR\"," + + "\"propertyDatatype\":\"" + + INTEGER + + "\"}", + json(entries.get(1))); + } + + @Test + void aTableTagIsEnoughAndRemovingTheTagRemovesTheFinding(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final Table customers = customers(schema(ns), "customers", tag(SENSITIVE)); + put(admin(), customer, binding(customers, OntologyBindingRole.IDENTITY, "email", "id"), 0L); + + assertEquals( + List.of("sensitiveKeyColumn Customer customers", "sensitiveKeyColumn Customer customers"), + summary(health(admin(), ontology, "").getEntries())); + + admin() + .tables() + .patch( + customers.getId(), + JsonUtils.getObjectMapper() + .createArrayNode() + .add(JsonUtils.valueToTree(Map.of("op", "remove", "path", "/tags/0")))); + + assertEquals(List.of(), summary(health(admin(), ontology, "").getEntries())); + } + + @Test + void aBindingWithATaggedKeyStillWritesAndTheFindingFollowsTheTag(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final Table customers = customers(schema(ns), "customers"); + + final var written = + put(admin(), customer, binding(customers, OntologyBindingRole.IDENTITY, "email"), 0L); + + assertEquals(OntologyBindingRole.IDENTITY, written.getAssets().getFirst().getRole()); + assertEquals(List.of(List.of("email")), written.getAssets().getFirst().getSubjectKey()); + assertEquals(List.of(), summary(health(admin(), ontology, "").getEntries())); + + admin() + .tables() + .patch( + customers.getId(), + JsonUtils.getObjectMapper() + .createArrayNode() + .add( + JsonUtils.valueToTree( + Map.of( + "op", "add", "path", "/columns/0/tags/-", "value", tag(SENSITIVE))))); + final var rewritten = + put(admin(), customer, binding(customers, OntologyBindingRole.IDENTITY, "email"), 1L); + + assertEquals(OntologyBindingRole.IDENTITY, rewritten.getAssets().getFirst().getRole()); + assertEquals( + List.of("sensitiveKeyColumn Customer customers"), + summary(health(admin(), ontology, "").getEntries())); + + admin() + .tables() + .patch( + customers.getId(), + JsonUtils.getObjectMapper() + .createArrayNode() + .add(JsonUtils.valueToTree(Map.of("op", "remove", "path", "/columns/0/tags/0")))); + + assertEquals(List.of(), summary(health(admin(), ontology, "").getEntries())); + } + + @Test + void aReaderDeniedTheTableSeesNeitherFinding(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final var age = integerProperty(ontology, customer, "age"); + final DatabaseSchema schema = schema(ns); + try (var fixtures = new RdfAccessFixtures("adviceTable" + ns.shortPrefix())) { + final var reader = OntologyBindingFixtures.ownerReader(fixtures, Entity.TABLE); + final Table hidden = customers(schema, "customers", tag(SENSITIVE)); + put( + admin(), + customer, + binding(hidden, OntologyBindingRole.IDENTITY, "email") + .withColumns(List.of(column(age, "age"))), + 0L); + + assertEquals(List.of(), health(reader, ontology, "").getEntries()); + assertEquals( + List.of("sensitiveKeyColumn Customer customers", "columnTypeMismatch Customer customers"), + summary(health(admin(), ontology, "").getEntries())); + } + } + + @Test + void aReaderDeniedThePropertySeesTheSensitiveKeyAndNoColumnTypeFinding(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final Table customers = customers(schema(ns), "customers", tag(SENSITIVE)); + try (var fixtures = new RdfAccessFixtures("adviceProperty" + ns.shortPrefix())) { + final var reader = OntologyBindingFixtures.ownerReader(fixtures, Entity.ONTOLOGY_PROPERTY); + final var age = integerProperty(ontology, customer, "age"); + put( + admin(), + customer, + binding(customers, OntologyBindingRole.IDENTITY, "email") + .withColumns(List.of(column(age, "age"))), + 0L); + + final var seen = summary(health(reader, ontology, "").getEntries()); + + assertEquals(List.of("sensitiveKeyColumn Customer customers"), seen); + assertEquals( + List.of("sensitiveKeyColumn Customer customers", "columnTypeMismatch Customer customers"), + summary(health(admin(), ontology, "").getEntries())); + } + } + + /** A table with an {@code id}, an {@code email} and an {@code age} column, the last two text. */ + static Table customers( + final DatabaseSchema schema, final String name, final TagLabel... tableTags) { + return admin() + .tables() + .create( + new CreateTable() + .withName(name) + .withDatabaseSchema(schema.getFullyQualifiedName()) + .withTags(List.of(tableTags)) + .withColumns( + List.of( + column("email", ColumnDataType.VARCHAR), + column("id", ColumnDataType.BIGINT), + column("age", ColumnDataType.VARCHAR)))); + } + + static TagLabel tag(final String fqn) { + return new TagLabel() + .withTagFQN(fqn) + .withSource(TagSource.CLASSIFICATION) + .withLabelType(TagLabel.LabelType.MANUAL) + .withState(TagLabel.State.CONFIRMED); + } + + static OntologyProperty integerProperty( + final Ontology ontology, final OntologyConcept domain, final String name) { + return admin() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName(name) + .withOntology(ontology.getFullyQualifiedName()) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(domain.getIri())) + .withRange(List.of(URI.create(INTEGER)))); + } + + /** The entry with its class, table and property references reduced to their names. */ + private static String json(final OntologyMappingHealthEntry entry) { + final ObjectNode node = (ObjectNode) JsonUtils.valueToTree(entry); + for (final String field : List.of("concept", "asset", "property")) { + if (node.has(field)) { + node.put(field, node.get(field).get("name").asText()); + } + } + return node.toString(); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingHealthIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingHealthIT.java new file mode 100644 index 000000000000..5c109f2fbfeb --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingHealthIT.java @@ -0,0 +1,381 @@ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.health; +import static org.openmetadata.it.tests.OntologyMappingFixtures.join; +import static org.openmetadata.it.tests.OntologyMappingFixtures.objectProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.setMappingSource; +import static org.openmetadata.it.tests.OntologyMappingFixtures.summary; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.util.OssTestServer; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyMappingHealthEntry; +import org.openmetadata.schema.api.data.OntologyMappingHealthEntryType; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.StoredBinding; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * The mapping health read lists what the table bindings of an ontology's classes still need, + * from catalog metadata alone. + */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyMappingHealthIT extends BaseOntologyApprovalIT { + @Test + void bindingsWrittenWithoutARoleAreUnassignedAndTheirClassHasNoIdentityTable( + final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final var schema = schema(ns); + final Table orders = orders(schema); + final Table customers = customers(schema); + put(admin(), order, binding(orders), 0L); + put(admin(), customer, binding(customers, OntologyBindingRole.IDENTITY, "id"), 0L); + + final var report = health(admin(), ontology, ""); + + assertEquals( + List.of("noIdentityTable Order -", "unassignedBinding Order orders"), + summary(report.getEntries())); + assertEquals(order.getId(), report.getEntries().getFirst().getConcept().getId()); + assertEquals(orders.getId(), report.getEntries().getLast().getAsset().getId()); + assertNull(report.getMappingSource()); + assertNull(report.getAfter()); + } + + @Test + void bindingsAcrossTwoDatabasesAreReportedAndLeftAsTheyAre(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final var sales = schema(ns); + final var marketing = schema(ns); + final Table orders = orders(sales); + final Table customers = customers(marketing); + put(admin(), order, binding(orders, OntologyBindingRole.IDENTITY, "order_id"), 0L); + put(admin(), customer, binding(customers, OntologyBindingRole.IDENTITY, "id"), 0L); + final var ordersBefore = bindings(admin(), order); + final var customersBefore = bindings(admin(), customer); + + final var spanning = health(admin(), ontology, "").getEntries(); + + assertEquals(List.of("multipleDatabases - -"), summary(spanning)); + assertEquals( + Set.of(sales.getDatabase().getId(), marketing.getDatabase().getId()), + spanning.getFirst().getDatabases().stream() + .map(EntityReference::getId) + .collect(Collectors.toSet())); + + setMappingSource(admin(), ontology, sales.getDatabase()); + final var report = health(admin(), ontology, ""); + + assertEquals(sales.getDatabase().getId(), report.getMappingSource().getId()); + assertEquals(List.of("outsideMappingSource Customer customers"), summary(report.getEntries())); + assertEquals( + List.of(marketing.getDatabase().getId()), + report.getEntries().getFirst().getDatabases().stream() + .map(EntityReference::getId) + .toList()); + assertEquals(ordersBefore, bindings(admin(), order)); + assertEquals(customersBefore, bindings(admin(), customer)); + } + + @Test + void aContributingKeyThatDoesNotPairWithTheIdentityKeyIsReported(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var schema = schema(ns); + final Table orders = orders(schema); + final Table shipments = + table( + schema, + "shipments", + column("tenant_code", ColumnDataType.INT), + column("order_ref", ColumnDataType.INT)); + final Table refunds = table(schema, "refunds", column("order_ref", ColumnDataType.BIGINT)); + put(admin(), order, binding(orders, OntologyBindingRole.IDENTITY, "tenant", "order_id"), 0L); + put( + admin(), + order, + binding(shipments, OntologyBindingRole.CONTRIBUTING, "tenant_code", "order_ref"), + 1L); + put(admin(), order, binding(refunds, OntologyBindingRole.CONTRIBUTING, "order_ref"), 2L); + + final var entries = health(admin(), ontology, "").getEntries(); + + assertEquals( + Set.of("keyTypeMismatch Order shipments", "keyLengthMismatch Order refunds"), + Set.copyOf(summary(entries))); + final var types = entry(entries, OntologyMappingHealthEntryType.KEY_TYPE_MISMATCH); + assertEquals(orders.getId(), types.getRelatedAsset().getId()); + assertEquals(List.of("tenant_code"), types.getColumnPath()); + assertEquals(ColumnDataType.INT, types.getDataType()); + assertEquals(List.of("tenant"), types.getRelatedColumnPath()); + assertEquals(ColumnDataType.VARCHAR, types.getRelatedDataType()); + final var lengths = entry(entries, OntologyMappingHealthEntryType.KEY_LENGTH_MISMATCH); + assertEquals(orders.getId(), lengths.getRelatedAsset().getId()); + assertEquals(1, lengths.getKeyLength()); + assertEquals(2, lengths.getRelatedKeyLength()); + } + + @Test + void anUnconfirmedJoinAndJoinColumnsOfDifferentKindsAreReported(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final var schema = schema(ns); + final Table orders = orders(schema); + final Table customers = customers(schema); + final var placedBy = objectProperty(ontology, "placedBy", order, customer); + final var soldIn = objectProperty(ontology, "soldIn", order, customer); + put( + admin(), + order, + binding(orders, OntologyBindingRole.IDENTITY, "order_id") + .withColumns( + List.of( + column(placedBy, "customer_id") + .withJoin( + join(customers, OntologyJoinStatus.INFERRED, "customer_id", "id")), + column(soldIn, "tenant") + .withJoin(join(customers, OntologyJoinStatus.CONFIRMED, "tenant", "id")))), + 0L); + + final var entries = health(admin(), ontology, "").getEntries(); + + assertEquals( + Set.of("joinNotConfirmed Order orders", "joinTypeMismatch Order orders"), + Set.copyOf(summary(entries))); + final var inferred = entry(entries, OntologyMappingHealthEntryType.JOIN_NOT_CONFIRMED); + assertEquals(placedBy.getId(), inferred.getProperty().getId()); + assertEquals(List.of("customer_id"), inferred.getColumnPath()); + assertEquals(customers.getId(), inferred.getRelatedAsset().getId()); + final var mismatch = entry(entries, OntologyMappingHealthEntryType.JOIN_TYPE_MISMATCH); + assertEquals(soldIn.getId(), mismatch.getProperty().getId()); + assertEquals(List.of("tenant"), mismatch.getColumnPath()); + assertEquals(ColumnDataType.VARCHAR, mismatch.getDataType()); + assertEquals(List.of("id"), mismatch.getRelatedColumnPath()); + assertEquals(ColumnDataType.BIGINT, mismatch.getRelatedDataType()); + assertEquals(customers.getId(), mismatch.getRelatedAsset().getId()); + } + + @Test + void aRelationColumnStoredWithoutAJoinIsReported(final TestNamespace ns) { + assumeFalse(OssTestServer.isExternalMode(), "Seeds a row as it was written before joins"); + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final Table orders = orders(schema(ns)); + final var placedBy = objectProperty(ontology, "placedBy", order, customer); + try { + insertRelationColumnWithoutJoin(order, orders, placedBy); + + final var entries = health(admin(), ontology, "").getEntries(); + + assertEquals( + List.of( + "noIdentityTable Order -", + "unassignedBinding Order orders", + "relationColumnWithoutJoin Order orders"), + summary(entries)); + assertEquals(placedBy.getId(), entries.getLast().getProperty().getId()); + assertEquals(List.of("customer_id"), entries.getLast().getColumnPath()); + final var stored = bindings(admin(), order).getAssets().getFirst(); + assertNull(stored.getRole()); + assertNull(stored.getSubjectKey()); + assertNull(stored.getColumns().getFirst().getJoin()); + } finally { + Entity.getCollectionDAO().ontologyConceptBindingDAO().deleteConcept(order.getId()); + } + } + + @Test + void pagesReportAClassOnceAndASpanOfDatabasesWheneverAPageFindsANewOne(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final Table first = table(schema(ns), "orders_a", column("order_id", ColumnDataType.BIGINT)); + final Table second = table(schema(ns), "orders_b", column("order_id", ColumnDataType.BIGINT)); + final Table third = table(schema(ns), "orders_c", column("order_id", ColumnDataType.BIGINT)); + put(admin(), order, binding(first), 0L); + put(admin(), order, binding(second), 1L); + put(admin(), order, binding(third), 2L); + final List names = + List.of(first, second, third).stream() + .sorted(Comparator.comparing(table -> table.getId().toString())) + .map(Table::getName) + .toList(); + + final List> pages = new ArrayList<>(); + String after = ""; + do { + final var page = health(admin(), ontology, "?limit=1" + after); + pages.add(page.getEntries()); + after = page.getAfter() == null ? null : "&after=" + page.getAfter(); + } while (after != null); + + assertEquals( + List.of( + List.of("noIdentityTable Order -", "unassignedBinding Order " + names.get(0)), + List.of("unassignedBinding Order " + names.get(1), "multipleDatabases - -"), + List.of("unassignedBinding Order " + names.get(2), "multipleDatabases - -")), + pages.stream().map(OntologyMappingFixtures::summary).toList()); + assertEquals(2, pages.get(1).getLast().getDatabases().size()); + assertEquals(3, pages.get(2).getLast().getDatabases().size()); + assertEquals( + List.of( + "noIdentityTable Order -", + "unassignedBinding Order " + names.get(0), + "unassignedBinding Order " + names.get(1), + "unassignedBinding Order " + names.get(2), + "multipleDatabases - -"), + summary(health(admin(), ontology, "?limit=100").getEntries())); + } + + @Test + void aReaderGetsNoFindingForATableTheyCannotView(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var schema = schema(ns); + put(admin(), order, binding(orders(schema)), 0L); + try (var fixtures = new RdfAccessFixtures("mappingHealth" + ns.shortPrefix())) { + final var reader = OntologyBindingFixtures.ownerReader(fixtures, Entity.TABLE); + final Table owned = + OntologyMappingFixtures.ownedTable( + schema, + "owned_orders", + OntologyBindingFixtures.readerReference(reader), + column("order_id", ColumnDataType.BIGINT)); + + assertEquals(List.of(), health(reader, ontology, "").getEntries()); + + put(admin(), order, binding(owned), 1L); + assertEquals( + List.of("noIdentityTable Order -", "unassignedBinding Order owned_orders"), + summary(health(reader, ontology, "").getEntries())); + assertEquals(3, health(admin(), ontology, "").getEntries().size()); + } + } + + @Test + void aReaderWhoCannotViewTheIdentityTableSeesNeitherAMissingIdentityNorItsName( + final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var schema = schema(ns); + final Table orders = orders(schema); + put(admin(), order, binding(orders, OntologyBindingRole.IDENTITY, "tenant", "order_id"), 0L); + try (var fixtures = new RdfAccessFixtures("hiddenIdentity" + ns.shortPrefix())) { + final var reader = OntologyBindingFixtures.ownerReader(fixtures, Entity.TABLE); + final Table shipments = + OntologyMappingFixtures.ownedTable( + schema, + "owned_shipments", + OntologyBindingFixtures.readerReference(reader), + column("order_ref", ColumnDataType.BIGINT)); + put(admin(), order, binding(shipments, OntologyBindingRole.CONTRIBUTING, "order_ref"), 1L); + + final var seen = health(reader, ontology, ""); + + assertEquals(List.of(), seen.getEntries()); + final String body = JsonUtils.pojoToJson(seen); + assertFalse(body.contains(orders.getName()), body); + assertFalse(body.contains(orders.getId().toString()), body); + assertEquals( + List.of("keyLengthMismatch Order owned_shipments"), + summary(health(admin(), ontology, "").getEntries())); + } + } + + @Test + void aCallerWhoCannotViewTheOntologyIsRefusedAndABadCursorIsRejected(final TestNamespace ns) { + final var ontology = createOntology(ns); + assertStatus(400, () -> health(admin(), ontology, "?after=not-a-cursor")); + assertStatus(400, () -> health(admin(), ontology, "?limit=101")); + assertNotNull(health(admin(), ontology, "?limit=100").getEntries()); + try (var fixtures = new RdfAccessFixtures("mappingHealthDenied" + ns.shortPrefix())) { + final var hidden = fixtures.denyRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY); + final var stranger = + OntologyBindingFixtures.client(fixtures.userToken("stranger", List.of(hidden.getId()))); + + assertStatus(403, () -> health(stranger, ontology, "")); + } + } + + /** A row as the binding API wrote it before a relation column needed a join. */ + private static void insertRelationColumnWithoutJoin( + final OntologyConcept concept, final Table table, final OntologyProperty property) { + Entity.getCollectionDAO() + .ontologyConceptBindingDAO() + .upsert( + new StoredBinding( + concept.getId().toString(), + table.getId().toString(), + Entity.TABLE, + FullyQualifiedName.buildHash(table.getFullyQualifiedName()), + "[{\"propertyId\":\"%s\",\"columnPath\":[\"customer_id\"]}]" + .formatted(property.getId()), + null, + null, + null)); + } + + private static OntologyMappingHealthEntry entry( + final List entries, final OntologyMappingHealthEntryType type) { + return entries.stream().filter(entry -> entry.getType() == type).findFirst().orElseThrow(); + } + + private static Table orders(final DatabaseSchema schema) { + return table( + schema, + "orders", + column("tenant", ColumnDataType.VARCHAR), + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT)); + } + + private static Table customers(final DatabaseSchema schema) { + return table(schema, "customers", column("id", ColumnDataType.BIGINT)); + } + + private static void assertStatus(final int status, final Runnable request) { + assertEquals(status, assertThrows(OpenMetadataException.class, request::run).getStatusCode()); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingSourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingSourceIT.java new file mode 100644 index 000000000000..037cf8c8b146 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingSourceIT.java @@ -0,0 +1,279 @@ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; +import static org.openmetadata.it.tests.OntologyMappingFixtures.clearMappingSource; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.mappingSource; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.setMappingSource; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Consumer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyReleaseMember; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** An ontology names one database as the place its classes' tables live. */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyMappingSourceIT extends BaseOntologyApprovalIT { + @Test + void anOntologyNamesChangesAndClearsItsMappingSource(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var sales = schema(ns).getDatabase(); + final var marketing = schema(ns).getDatabase(); + assertNull(mappingSource(admin(), ontology)); + + final Ontology patched = setMappingSource(admin(), ontology, sales); + + assertEquals(sales.getId(), patched.getMappingSource().getId()); + final EntityReference stored = mappingSource(admin(), ontology); + assertEquals(sales.getId(), stored.getId()); + assertEquals(Entity.DATABASE, stored.getType()); + assertEquals(sales.getFullyQualifiedName(), stored.getFullyQualifiedName()); + assertNull(admin().ontologies().get(ontology.getId()).getMappingSource()); + + setMappingSource(admin(), ontology, marketing); + assertEquals(marketing.getId(), mappingSource(admin(), ontology).getId()); + + assertNull(clearMappingSource(admin(), ontology).getMappingSource()); + assertNull(mappingSource(admin(), ontology)); + } + + @Test + void aCreateRequestCanNameTheMappingSourceAndAPutThatNamesNoneKeepsIt(final TestNamespace ns) { + final var sales = schema(ns).getDatabase(); + final var marketing = schema(ns).getDatabase(); + final var request = request(ns).withName(ns.prefix("mapped")).withMappingSource(sales); + + final Ontology created = admin().ontologies().create(request); + ns.trackRoot("ontology", created); + + assertEquals(sales.getId(), mappingSource(admin(), created).getId()); + admin().ontologies().upsert(request.withMappingSource(null).withDescription("Described")); + assertEquals(sales.getId(), mappingSource(admin(), created).getId()); + admin().ontologies().upsert(request.withMappingSource(marketing)); + assertEquals(marketing.getId(), mappingSource(admin(), created).getId()); + } + + @Test + void aMappingSourceMustBeADatabaseThatExists(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var schema = schema(ns); + final var orders = table(schema, "orders", column("order_id", ColumnDataType.BIGINT)); + + final var notADatabase = + assertThrows( + OpenMetadataException.class, + () -> setMappingSource(admin(), ontology, orders.getEntityReference())); + assertEquals(400, notADatabase.getStatusCode()); + assertTrue( + notADatabase.getMessage().contains("An ontology's mapping source must be a database"), + notADatabase.getMessage()); + assertStatus( + 404, + () -> + setMappingSource( + admin(), + ontology, + new EntityReference().withId(UUID.randomUUID()).withType(Entity.DATABASE))); + assertNull(mappingSource(admin(), ontology)); + } + + @Test + void aMappingSourceThatNamesNoIdIsRefusedAsABadRequestOnEveryWrite(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var noId = new EntityReference().withType(Entity.DATABASE); + final var unsaved = + request(ns) + .withName(ns.prefix("noid")) + .withIri(URI.create("https://example.org/model/" + ns.shortPrefix() + "noid")); + + assertRefused(400, "mappingSource.id", () -> setMappingSource(admin(), ontology, noId)); + assertRefused( + 400, + "id must not be null", + () -> admin().ontologies().create(unsaved.withMappingSource(noId))); + assertRefused( + 400, + "id must not be null", + () -> admin().ontologies().upsert(request(ns).withMappingSource(noId))); + + assertStatus(404, () -> admin().ontologies().getByName(unsaved.getName())); + assertNull(mappingSource(admin(), ontology)); + assertEquals(ontology.getVersion(), admin().ontologies().get(ontology.getId()).getVersion()); + } + + @Test + void aCreateAndAPutRefuseAMappingSourceThatIsNotALiveDatabase(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var orders = table(schema(ns), "orders", column("order_id", ColumnDataType.BIGINT)); + final var retired = schema(ns).getDatabase(); + admin().databases().delete(retired.getId().toString(), Map.of("recursive", "true")); + final var missing = new EntityReference().withId(UUID.randomUUID()).withType(Entity.DATABASE); + final var unsaved = + request(ns) + .withName(ns.prefix("unsaved")) + .withIri(URI.create("https://example.org/model/" + ns.shortPrefix() + "unsaved")); + final List> writes = + List.of( + source -> admin().ontologies().create(unsaved.withMappingSource(source)), + source -> admin().ontologies().upsert(request(ns).withMappingSource(source))); + + for (final var write : writes) { + assertRefused( + 400, + "An ontology's mapping source must be a database", + () -> write.accept(orders.getEntityReference())); + assertRefused(404, missing.getId().toString(), () -> write.accept(missing)); + assertRefused(400, "must not be a deleted database", () -> write.accept(retired)); + } + + assertStatus(404, () -> admin().ontologies().getByName(unsaved.getName())); + assertNull(mappingSource(admin(), ontology)); + assertEquals(ontology.getVersion(), admin().ontologies().get(ontology.getId()).getVersion()); + } + + @Test + void aDeletedDatabaseCannotBecomeTheMappingSourceAndNeverBlocksAnotherEdit( + final TestNamespace ns) { + final var ontology = createOntology(ns); + final var sales = schema(ns).getDatabase(); + final var retired = schema(ns).getDatabase(); + setMappingSource(admin(), ontology, sales); + admin().databases().delete(sales.getId().toString(), Map.of("recursive", "true")); + admin().databases().delete(retired.getId().toString(), Map.of("recursive", "true")); + + final var refused = + assertThrows( + OpenMetadataException.class, () -> setMappingSource(admin(), ontology, retired)); + assertEquals(400, refused.getStatusCode()); + assertTrue( + refused.getMessage().contains("must not be a deleted database"), refused.getMessage()); + + final var patch = JsonUtils.getObjectMapper().createArrayNode(); + patch.addObject().put("op", "add").put("path", "/description").put("value", "Still editable"); + final Ontology edited = + admin() + .getHttpClient() + .execute(HttpMethod.PATCH, "/v1/ontologies/" + ontology.getId(), patch, Ontology.class); + assertEquals("Still editable", edited.getDescription()); + final EntityReference kept = mappingSource(admin(), ontology); + assertEquals(sales.getId(), kept.getId()); + assertEquals(Boolean.TRUE, kept.getDeleted()); + } + + @Test + void changingTheMappingSourceNeedsEditAllOnTheOntology(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var sales = schema(ns).getDatabase(); + final var marketing = schema(ns).getDatabase(); + setMappingSource(admin(), ontology, sales); + try (var fixtures = new RdfAccessFixtures("mappingSource" + ns.shortPrefix())) { + final var reader = OntologyBindingFixtures.client(fixtures.userToken("reader", List.of())); + + assertStatus(403, () -> setMappingSource(reader, ontology, marketing)); + assertStatus(403, () -> clearMappingSource(reader, ontology)); + + assertEquals(sales.getId(), mappingSource(reader, ontology).getId()); + } + try (var fixtures = new RdfAccessFixtures("mappingEditor" + ns.shortPrefix())) { + final var editor = fixtures.allowRole(MetadataOperation.EDIT_ALL, Entity.ONTOLOGY); + final var client = + OntologyBindingFixtures.client(fixtures.userToken("editor", List.of(editor.getId()))); + + setMappingSource(client, ontology, marketing); + + assertEquals(marketing.getId(), mappingSource(admin(), ontology).getId()); + } + } + + @Test + void namingAMappingSourceLeavesEarlierBindingsElsewhereAsTheyAre(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var sales = schema(ns); + final var marketing = schema(ns); + final var orders = table(marketing, "orders", column("order_id", ColumnDataType.BIGINT)); + put(admin(), order, binding(orders), 0L); + final var before = bindings(admin(), order); + + setMappingSource(admin(), ontology, sales.getDatabase()); + + assertEquals(before, bindings(admin(), order)); + assertEquals(sales.getDatabase().getId(), mappingSource(admin(), ontology).getId()); + } + + @Test + void theMappingSourceStaysOutOfReleasesAndTheirDigests(final TestNamespace ns) { + final var ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final var sales = schema(ns).getDatabase(); + final var before = capture(ontology); + final long workingRevision = workingRevision(ontology); + + setMappingSource(admin(), ontology, sales); + + assertEquals(workingRevision, workingRevision(ontology)); + assertEquals(ontology.getVersion(), admin().ontologies().get(ontology.getId()).getVersion()); + final var after = capture(ontology); + assertEquals(before.getContentDigest(), after.getContentDigest()); + final OntologyReleaseMember frozen = ontologyMember(after, ontology); + assertEquals(ontology.getName(), frozen.getPayload().path("name").asText()); + assertTrue(frozen.getPayload().path("mappingSource").isMissingNode()); + assertEquals(ontologyMember(before, ontology).getPayloadDigest(), frozen.getPayloadDigest()); + assertEquals(sales.getId(), mappingSource(admin(), ontology).getId()); + } + + private static long workingRevision(final Ontology ontology) { + return admin().ontologies().state(ontology.getId()).getWorkingRevision(); + } + + private static OntologyReleaseMember ontologyMember( + final OntologyRelease release, final Ontology ontology) { + return admin() + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/ontologyReleases/" + release.getId() + "/members/ONTOLOGY/" + ontology.getId(), + null, + OntologyReleaseMember.class); + } + + private static void assertStatus(final int status, final Runnable request) { + assertEquals(status, assertThrows(OpenMetadataException.class, request::run).getStatusCode()); + } + + private static void assertRefused( + final int status, final String message, final Runnable request) { + final var failure = assertThrows(OpenMetadataException.class, request::run); + assertEquals(status, failure.getStatusCode()); + assertTrue(failure.getMessage().contains(message), failure.getMessage()); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingSourceReadIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingSourceReadIT.java new file mode 100644 index 000000000000..d01f5231cdd0 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyMappingSourceReadIT.java @@ -0,0 +1,109 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.health; +import static org.openmetadata.it.tests.OntologyMappingFixtures.mappingSource; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.setMappingSource; +import static org.openmetadata.it.tests.OntologyMappingFixtures.summary; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.util.DenyPolicyPrincipals; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.Database; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; + +/** The database an ontology names as its mapping source is shown only to a reader who may view it. */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyMappingSourceReadIT extends BaseOntologyApprovalIT { + private static final String PII_SENSITIVE = "PII.Sensitive"; + + @Test + void aReaderDeniedTheMappingSourceDatabaseSeesNoReferenceToIt(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var open = schema(ns); + final Database sensitive = tagged(schema(ns).getDatabase().getId().toString()); + put( + admin(), + order, + binding( + table(open, "orders", column("order_id", ColumnDataType.BIGINT)), + OntologyBindingRole.IDENTITY, + "order_id"), + 0L); + setMappingSource(admin(), ontology, sensitive.getEntityReference()); + final OpenMetadataClient reader = + DenyPolicyPrincipals.clientDeniedWhen( + ns.shortPrefix("mapSrc"), + "database", + MetadataOperation.VIEW_BASIC, + "matchAnyTag('" + PII_SENSITIVE + "')"); + + assertEquals( + 403, + assertThrows( + OpenMetadataException.class, + () -> reader.databases().get(sensitive.getId().toString())) + .getStatusCode()); + + final var seenHealth = health(reader, ontology, ""); + final var seenOntology = reader.ontologies().get(ontology.getId().toString(), "mappingSource"); + + assertNull(seenHealth.getMappingSource()); + assertNull(mappingSource(reader, ontology)); + assertEquals(List.of("outsideMappingSource Order orders"), summary(seenHealth.getEntries())); + for (final String body : + List.of(JsonUtils.pojoToJson(seenHealth), JsonUtils.pojoToJson(seenOntology))) { + assertFalse(body.contains(sensitive.getId().toString()), body); + } + assertEquals(sensitive.getId(), health(admin(), ontology, "").getMappingSource().getId()); + assertEquals(sensitive.getId(), mappingSource(admin(), ontology).getId()); + } + + private static Database tagged(final String id) { + final Database database = admin().databases().get(id); + final TagLabel tag = + new TagLabel() + .withTagFQN(PII_SENSITIVE) + .withSource(TagLabel.TagSource.CLASSIFICATION) + .withLabelType(TagLabel.LabelType.MANUAL) + .withState(TagLabel.State.CONFIRMED); + database.setTags(List.of(tag)); + return admin().databases().update(id, database); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseExportIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseExportIT.java index ed25a0c6a7da..2c6cb0a3aca4 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseExportIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseExportIT.java @@ -131,7 +131,8 @@ void exportsFrozenDefinitionsWithoutAnRdfServer(RdfSerializationFormat format, T new OntologyLiteral().withValue("Gold"), new OntologyLiteral().withValue("Silver"))) .withUnit("kg") - .withIsIdentifier(true)); + .withIsIdentifier(true) + .withIsDisplayName(true)); var subclass = client.ontologyAxioms().create(axiom(ontology)); OntologyRelease release = capture(ontology); client.ontologyConcepts().update(concept.getId(), concept.withDisplayName("Later label")); @@ -187,6 +188,11 @@ void exportsFrozenDefinitionsWithoutAnRdfServer(RdfSerializationFormat format, T model.getResource("urn:example:customerCode"), model.createProperty("https://open-metadata.org/ontology/unitAnnotation"), "kg")); + assertTrue( + model.contains( + model.getResource("urn:example:customerCode"), + model.createProperty("https://open-metadata.org/ontology/displayNameIntent"), + model.createTypedLiteral(true))); assertFalse( model.contains( model.getResource("urn:example:customerCode"), RDF.type, OWL2.FunctionalProperty)); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseIT.java index 893daede85f2..2182b6e8c28d 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseIT.java @@ -479,24 +479,21 @@ private static JsonNode events(OntologyRelease release, String query) { private static void assertMemberReadDenied( OpenMetadataClient denied, OntologyRelease release, OntologyConcept concept) { - for (String suffix : List.of("", "/" + concept.getId())) { - assertEquals( - 403, - assertThrows( - OpenMetadataException.class, - () -> - denied - .getHttpClient() - .execute( - HttpMethod.GET, - "/v1/ontologyReleases/" - + release.getId() - + "/members/CONCEPT" - + suffix, - null, - JsonNode.class)) - .getStatusCode()); - } + final String members = "/v1/ontologyReleases/" + release.getId() + "/members/CONCEPT"; + final JsonNode listed = + denied.getHttpClient().execute(HttpMethod.GET, members, null, JsonNode.class); + assertEquals(0, listed.path("data").size()); + assertEquals(0, listed.path("paging").path("total").asInt()); + assertEquals( + 403, + assertThrows( + OpenMetadataException.class, + () -> + denied + .getHttpClient() + .execute( + HttpMethod.GET, members + "/" + concept.getId(), null, JsonNode.class)) + .getStatusCode()); } private static OntologyReleaseMember member(OntologyRelease release, UUID conceptId) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseMemberReadIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseMemberReadIT.java new file mode 100644 index 000000000000..8380e77bafcf --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyReleaseMemberReadIT.java @@ -0,0 +1,269 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.bootstrap.SharedEntities; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyConcept; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyConceptType; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.config.OpenMetadataConfig; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** A release lists, to each reader, only the members that reader may view. */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyReleaseMemberReadIT extends BaseOntologyApprovalIT { + private record Members( + Ontology ontology, + OntologyRelease release, + List classes, + List properties) {} + + @Test + void aReaderDeniedMembersOwnedByOthersListsOnlyTheMembersItMayView(final TestNamespace ns) { + final Members members = members(ns); + ownBy(members, SharedEntities.get().USER1.getEntityReference()); + try (RdfAccessFixtures concepts = new RdfAccessFixtures("ownC" + ns.shortPrefix()); + RdfAccessFixtures properties = new RdfAccessFixtures("ownP" + ns.shortPrefix())) { + assertReaderSeesOnlyViewable(members, reader(concepts, properties, "!noOwner()")); + } + } + + @Test + void aReaderDeniedMembersItOwnsListsOnlyTheMembersItMayView(final TestNamespace ns) { + final Members members = members(ns); + try (RdfAccessFixtures concepts = new RdfAccessFixtures("mineC" + ns.shortPrefix()); + RdfAccessFixtures properties = new RdfAccessFixtures("mineP" + ns.shortPrefix())) { + final OpenMetadataClient reader = reader(concepts, properties, "isOwner()"); + final String userName = + ("mineC" + ns.shortPrefix() + "reader" + concepts.suffix()).toLowerCase(Locale.ROOT); + ownBy(members, SdkClients.adminClient().users().getByName(userName).getEntityReference()); + assertReaderSeesOnlyViewable(members, reader); + } + } + + @Test + void aReaderDeniedTheOntologyStillGetsForbidden(final TestNamespace ns) { + final Members members = members(ns); + try (RdfAccessFixtures fixtures = new RdfAccessFixtures("noOnt" + ns.shortPrefix())) { + final var role = fixtures.denyRole(MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_RELEASE); + final OpenMetadataClient denied = client(fixtures.userToken("reader", List.of(role.getId()))); + assertEquals( + 403, + assertThrows( + OpenMetadataException.class, + () -> page(denied, members.release(), "CONCEPT", 50, null)) + .getStatusCode()); + } + } + + private static void assertReaderSeesOnlyViewable( + final Members members, final OpenMetadataClient reader) { + final List hidden = List.of(hiddenClass(members), hiddenProperty(members)); + assertEquals( + 403, + assertThrows( + OpenMetadataException.class, + () -> reader.ontologyConcepts().get(hiddenClass(members))) + .getStatusCode()); + assertEquals( + 403, + assertThrows( + OpenMetadataException.class, + () -> reader.ontologyProperties().get(hiddenProperty(members))) + .getStatusCode()); + final List viewableClasses = idsExcept(members.classes(), hiddenClass(members)); + final List viewableProperties = idsExcept(members.properties(), hiddenProperty(members)); + assertEquals(viewableClasses, walk(reader, members.release(), "CONCEPT", 1, hidden)); + assertEquals(viewableProperties, walk(reader, members.release(), "PROPERTY", 1, hidden)); + assertEquals( + viewableClasses.size(), + page(reader, members.release(), "CONCEPT", 50, null).path("paging").path("total").asInt()); + assertEquals( + viewableProperties.size(), + page(reader, members.release(), "PROPERTY", 50, null).path("paging").path("total").asInt()); + assertEquals( + members.classes().size(), + page(SdkClients.adminClient(), members.release(), "CONCEPT", 50, null).path("data").size()); + assertEquals( + members.properties().size(), + page(SdkClients.adminClient(), members.release(), "PROPERTY", 50, null) + .path("data") + .size()); + assertEquals( + 403, + assertThrows( + OpenMetadataException.class, + () -> + reader + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/ontologyReleases/" + + members.release().getId() + + "/members/CONCEPT/" + + hiddenClass(members), + null, + JsonNode.class)) + .getStatusCode()); + } + + private static List walk( + final OpenMetadataClient reader, + final OntologyRelease release, + final String kind, + final int limit, + final List hidden) { + final List seen = new ArrayList<>(); + String after = null; + do { + final JsonNode body = page(reader, release, kind, limit, after); + final String text = body.toString(); + hidden.forEach(secret -> assertFalse(text.contains(secret), text)); + body.path("data") + .forEach(member -> seen.add(UUID.fromString(member.path("memberId").asText()))); + after = textOrNull(body); + } while (after != null); + return seen.stream().sorted().toList(); + } + + private static String textOrNull(final JsonNode body) { + final String after = body.path("paging").path("after").asText(""); + return after.isEmpty() ? null : after; + } + + private static JsonNode page( + final OpenMetadataClient client, + final OntologyRelease release, + final String kind, + final int limit, + final String after) { + final String cursor = after == null ? "" : "&after=" + after; + return client + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/ontologyReleases/" + + release.getId() + + "/members/" + + kind + + "?limit=" + + limit + + cursor, + null, + JsonNode.class); + } + + private static String hiddenClass(final Members members) { + return members.classes().get(1).getId().toString(); + } + + private static String hiddenProperty(final Members members) { + return members.properties().get(1).getId().toString(); + } + + private static > List idsExcept( + final List all, final String hiddenId) { + return all.stream() + .map(T::getId) + .filter(id -> !id.toString().equals(hiddenId)) + .sorted() + .toList(); + } + + private static OpenMetadataClient reader( + final RdfAccessFixtures concepts, + final RdfAccessFixtures properties, + final String condition) { + final var conceptRole = + concepts.denyRole(MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_CONCEPT, condition); + final var propertyRole = + properties.denyRole(MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_PROPERTY, condition); + return client(concepts.userToken("reader", List.of(conceptRole.getId(), propertyRole.getId()))); + } + + private static OpenMetadataClient client(final String token) { + return new OpenMetadataClient( + OpenMetadataConfig.builder().serverUrl(SdkClients.baseUrl()).accessToken(token).build()); + } + + /** Three classes and two properties; the second of each is the one a test hides. */ + private static Members members(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final var admin = SdkClients.adminClient(); + final List classes = new ArrayList<>(); + for (int index = 0; index < 3; index++) { + classes.add( + admin + .ontologyConcepts() + .create( + new CreateOntologyConcept() + .withOntology(ontology.getFullyQualifiedName()) + .withName("Class" + index) + .withConceptType(OntologyConceptType.OWL_CLASS))); + } + final List properties = new ArrayList<>(); + for (int index = 0; index < 2; index++) { + properties.add( + admin + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withOntology(ontology.getFullyQualifiedName()) + .withName("property" + index) + .withKind(OntologyPropertyKind.OBJECT))); + } + return new Members(ontology, capture(ontology), classes, properties); + } + + private static void ownBy(final Members members, final EntityReference owner) { + final var concepts = SdkClients.adminClient().ontologyConcepts(); + final String conceptId = members.classes().get(1).getId().toString(); + final OntologyConcept concept = concepts.get(conceptId); + concept.setOwners(List.of(owner)); + concepts.update(conceptId, concept); + final var properties = SdkClients.adminClient().ontologyProperties(); + final String propertyId = members.properties().get(1).getId().toString(); + final OntologyProperty property = properties.get(propertyId); + property.setOwners(List.of(owner)); + properties.update(propertyId, property); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeDeleteImpactIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeDeleteImpactIT.java new file mode 100644 index 000000000000..f91e3417e724 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeDeleteImpactIT.java @@ -0,0 +1,192 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; + +/** A class or property that a live shape names cannot be deleted; a shape save stays lenient. */ +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyShapeDeleteImpactIT extends BaseOntologyApprovalIT { + + @Test + void deletingAClassAShapeNamesIsRefusedAndListsTheShapeAsABlocker(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept person = declareClass(ontology, "Person", model("Person")); + final OntologyConcept address = declareClass(ontology, "Address", model("Address")); + final OntologyConcept unrelated = declareClass(ontology, "Unrelated", model("Unrelated")); + declareProperty(ontology, "livesAt", OntologyPropertyKind.OBJECT); + final OntologyShape shape = + SdkClients.adminClient().ontologyShapes().create(request(ontology, "PersonShape")); + + assertEquals(List.of("PersonShape"), blockers(person.getId())); + assertEquals(List.of("PersonShape"), blockers(address.getId())); + assertEquals(List.of(), blockers(unrelated.getId())); + for (final OntologyConcept named : List.of(person, address)) { + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> SdkClients.adminClient().ontologyConcepts().delete(named.getId())); + assertEquals(400, refused.getStatusCode()); + assertTrue(refused.getMessage().contains("'PersonShape'"), refused.getMessage()); + assertFalse( + Boolean.TRUE.equals( + SdkClients.adminClient().ontologyConcepts().get(named.getId()).getDeleted())); + } + SdkClients.adminClient().ontologyConcepts().delete(unrelated.getId()); + + SdkClients.adminClient().ontologyShapes().delete(shape.getId()); + assertEquals(List.of(), blockers(person.getId())); + SdkClients.adminClient().ontologyConcepts().delete(person.getId()); + SdkClients.adminClient().ontologyConcepts().delete(address.getId()); + } + + @Test + void deletingAPropertyAShapeConstrainsIsRefusedUntilTheShapeIsDeleted(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Person", model("Person")); + declareClass(ontology, "Address", model("Address")); + final OntologyProperty livesAt = + declareProperty(ontology, "livesAt", OntologyPropertyKind.OBJECT); + final OntologyShape shape = + SdkClients.adminClient().ontologyShapes().create(request(ontology, "PersonShape")); + + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> SdkClients.adminClient().ontologyProperties().delete(livesAt.getId())); + + assertEquals(400, refused.getStatusCode()); + assertTrue(refused.getMessage().contains("'PersonShape'"), refused.getMessage()); + SdkClients.adminClient().ontologyShapes().delete(shape.getId()); + SdkClients.adminClient().ontologyProperties().delete(livesAt.getId()); + } + + @Test + void aShapeNamingTwoMissingClassesDoesNotBlockDeclaringOneOfThem(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyShape shape = + SdkClients.adminClient() + .ontologyShapes() + .create( + request(ontology, "AheadOfItsModel") + .withTargetConcept(model("Ghost")) + .withConstraints( + new ArrayList<>( + List.of( + new OntologyShapeConstraint() + .withId("lives-at") + .withPath(model("livesAt")) + .withClassIri(model("Phantom")))))); + + final OntologyConcept ghost = declareClass(ontology, "Ghost", model("Ghost")); + + assertEquals(model("Ghost"), ghost.getIri()); + assertEquals( + shape.getId(), + SdkClients.adminClient().ontologyShapes().get(shape.getId().toString()).getId()); + } + + @Test + void deletingTheOntologyThatHoldsTheShapeAndItsClassesStillWorks(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Person", model("Person")); + declareClass(ontology, "Address", model("Address")); + declareProperty(ontology, "livesAt", OntologyPropertyKind.OBJECT); + final OntologyShape shape = + SdkClients.adminClient().ontologyShapes().create(request(ontology, "PersonShape")); + + SdkClients.adminClient() + .ontologies() + .delete(ontology.getId().toString(), Map.of("recursive", "true")); + + final OpenMetadataException gone = + assertThrows( + OpenMetadataException.class, + () -> SdkClients.adminClient().ontologyShapes().get(shape.getId().toString())); + assertEquals(404, gone.getStatusCode()); + } + + private static List blockers(final UUID conceptId) { + final JsonNode impact = + SdkClients.adminClient() + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/ontologyConcepts/" + conceptId + "/deleteImpact", + null, + JsonNode.class); + final List names = new ArrayList<>(); + impact.path("blockers").forEach(blocker -> names.add(blocker.path("name").asText())); + return names; + } + + private static OntologyProperty declareProperty( + final Ontology ontology, final String name, final OntologyPropertyKind kind) { + return SdkClients.adminClient() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName(name) + .withOntology(ontology.getFullyQualifiedName()) + .withIri(model(name)) + .withKind(kind)); + } + + private static CreateOntologyShape request(final Ontology ontology, final String name) { + return new CreateOntologyShape() + .withName(name) + .withDisplayName(name) + .withDescription("Shape of a person") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(model("Person")) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints( + new ArrayList<>( + List.of( + new OntologyShapeConstraint() + .withId("lives-at") + .withPath(model("livesAt")) + .withClassIri(model("Address"))))); + } + + private static URI model(final String name) { + return URI.create("https://example.org/model/" + name); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeReleaseIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeReleaseIT.java new file mode 100644 index 000000000000..9e1933d2fd96 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeReleaseIT.java @@ -0,0 +1,332 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.auth.JwtAuthProvider; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.data.ImportOntologyShapes; +import org.openmetadata.schema.api.data.OntologyValidationError; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.EntityStatus; +import org.openmetadata.schema.type.OntologyProfileViolationCode; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; +import org.openmetadata.service.Entity; + +/** A shape through capture, review, activation, export and release validation. */ +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyShapeReleaseIT extends BaseOntologyApprovalIT { + private static final HttpClient HTTP = HttpClient.newHttpClient(); + + @Test + void aShapeSurvivesCaptureReviewAndActivationWithTheSameConstraintIds(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + declareModel(ontology); + final OntologyShape draft = client.ontologyShapes().create(shape(ontology, "PersonShape")); + + final OntologyRelease release = activate(ns, ontology); + + final JsonNode sealed = sealedShapes(release); + assertEquals(1, sealed.size()); + final JsonNode member = sealed.get(0); + assertEquals(draft.getId().toString(), member.path("memberId").asText()); + assertEquals(draft.getId().toString(), member.path("payload").path("id").asText()); + assertEquals( + List.of("has-name", "address-class"), ids(member.path("payload").path("constraints"))); + assertEquals( + model("Person"), URI.create(member.path("payload").path("targetConcept").asText())); + assertEquals("Info", member.path("payload").path("severity").asText()); + assertTrue(client.ontologyReleases().structure(release.getId()).getValid()); + assertEquals( + EntityStatus.APPROVED, client.ontologyReleases().get(release.getId()).getEntityStatus()); + } + + @Test + void editingTheWorkingShapeAfterActivationDoesNotChangeTheSealedOne(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + declareModel(ontology); + final CreateOntologyShape request = shape(ontology, "PersonShape"); + client.ontologyShapes().create(request); + final OntologyRelease release = activate(ns, ontology); + + request.getConstraints().getFirst().setId("renamed"); + client.ontologyShapes().upsert(request); + + assertEquals( + List.of("has-name", "address-class"), + ids(sealedShapes(release).get(0).path("payload").path("constraints"))); + } + + @Test + void aShapeNamingADefinitionTheOntologyLacksBlocksCaptureUntilItIsDeclared( + final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Person", model("Person")); + client + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName("name") + .withOntology(ontology.getFullyQualifiedName()) + .withIri(model("name")) + .withKind(OntologyPropertyKind.DATA)); + final CreateOntologyShape request = shape(ontology, "PersonShape"); + final OntologyShape stored = client.ontologyShapes().create(request); + + final OntologyValidationError error = refusedCapture(ontology); + + assertEquals( + List.of( + OntologyProfileViolationCode.UNDECLARED_PROPERTY + " /constraints/1/path", + OntologyProfileViolationCode.UNDECLARED_CLASS + " /constraints/1/classIri"), + error.getViolations().stream() + .map(issue -> issue.getViolation().getCode() + " " + issue.getViolation().getPath()) + .toList()); + assertEquals(stored.getId(), error.getViolations().getFirst().getMemberId()); + + declareClass(ontology, "Address", model("Address")); + client + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName("livesAt") + .withOntology(ontology.getFullyQualifiedName()) + .withIri(model("livesAt")) + .withKind(OntologyPropertyKind.OBJECT)); + assertNotNull(capture(ontology).getId()); + } + + @Test + void aShapeTargetingAClassTheOntologyLacksBlocksCapture(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + declareModel(ontology); + final CreateOntologyShape request = + shape(ontology, "GhostShape").withTargetConcept(model("Ghost")); + client.ontologyShapes().create(request); + + final OntologyValidationError error = refusedCapture(ontology); + + assertEquals( + List.of(OntologyProfileViolationCode.UNDECLARED_CLASS + " /targetConcept"), + error.getViolations().stream() + .map(issue -> issue.getViolation().getCode() + " " + issue.getViolation().getPath()) + .toList()); + } + + @Test + void aSealedReleaseExportsItsShapesAsShaclThatImportsBackWithEveryId(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "shapeExportSource"); + final Ontology fresh = createOntology(ns, "shapeExportFresh"); + declareModel(ontology); + client.ontologyShapes().create(shape(ontology, "PersonShape")); + final OntologyRelease release = activate(ns, ontology); + + final String shacl = + client + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/ontologyReleases/" + release.getId() + "/export?format=shacl", + null, + RequestOptions.builder().header("Accept", "*/*").build()); + final var imported = + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(fresh.getFullyQualifiedName()) + .withContent(shacl)); + + assertEquals(List.of(), imported.getUnsupported()); + assertEquals( + List.of("has-name", "address-class"), imported.getShapes().getFirst().getConstraintIds()); + final String turtle = + client + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/ontologyReleases/" + release.getId() + "/export?format=turtle", + null, + RequestOptions.builder().header("Accept", "*/*").build()); + assertTrue(!turtle.contains("NodeShape"), "the OWL graph does not carry shapes"); + } + + @Test + void aConsumerReadsTheSealedShapesAndNoWorkingDraftOnes(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + declareModel(ontology); + client.ontologyShapes().create(shape(ontology, "PersonShape")); + final OntologyRelease release = activate(ns, ontology); + final String name = ns.shortPrefix("shapeReleaseConsumer"); + final User consumer = + ns.trackRoot( + Entity.USER, + client + .users() + .create( + new CreateUser() + .withName(name) + .withEmail(name + "@test.om.org") + .withDescription("v7 user") + .withRoles(List.of(client.roles().getByName("DataConsumer").getId())))); + + assertEquals( + 200, status(consumer, "/v1/ontologyReleases/" + release.getId() + "/members/shape")); + assertEquals( + 200, status(consumer, "/v1/ontologyReleases/" + release.getId() + "/export?format=shacl")); + assertEquals(403, status(consumer, "/v1/ontologyShapes?ontologyId=" + ontology.getId())); + assertEquals( + 403, status(consumer, "/v1/ontologies/" + ontology.getId() + "/export?format=shacl")); + } + + private static JsonNode sealedShapes(final OntologyRelease release) { + final String body = + SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/ontologyReleases/" + release.getId() + "/members/shape", + null, + RequestOptions.builder().header("Accept", "application/json").build()); + return JsonUtils.readTree(body).path("data"); + } + + private static List ids(final JsonNode constraints) { + final List ids = new ArrayList<>(); + constraints.forEach(constraint -> ids.add(constraint.path("id").asText())); + return ids; + } + + private static void declareModel(final Ontology ontology) { + declareClass(ontology, "Person", model("Person")); + declareClass(ontology, "Address", model("Address")); + SdkClients.adminClient() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName("name") + .withOntology(ontology.getFullyQualifiedName()) + .withIri(model("name")) + .withKind(OntologyPropertyKind.DATA)); + SdkClients.adminClient() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName("livesAt") + .withOntology(ontology.getFullyQualifiedName()) + .withIri(model("livesAt")) + .withKind(OntologyPropertyKind.OBJECT)); + } + + private static CreateOntologyShape shape(final Ontology ontology, final String name) { + return new CreateOntologyShape() + .withName(name) + .withDisplayName(name) + .withDescription("Shape of a person") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(model("Person")) + .withSeverity(OntologyShapeSeverity.INFO) + .withConstraints( + new ArrayList<>( + List.of( + new OntologyShapeConstraint() + .withId("has-name") + .withPath(model("name")) + .withMinCount(1), + new OntologyShapeConstraint() + .withId("address-class") + .withPath(model("livesAt")) + .withClassIri(model("Address"))))); + } + + private static URI model(final String name) { + return URI.create("https://example.org/model/" + name); + } + + private static OntologyValidationError refusedCapture(final Ontology ontology) { + final long revision = + SdkClients.adminClient().ontologies().state(ontology.getId()).getWorkingRevision(); + try { + final HttpResponse response = + HTTP.send( + HttpRequest.newBuilder() + .uri( + URI.create( + SdkClients.getServerUrl() + + "/v1/ontologies/" + + ontology.getId() + + "/releases")) + .header("Authorization", "Bearer " + SdkClients.getAdminToken()) + .header("Content-Type", "application/json") + .POST( + HttpRequest.BodyPublishers.ofString( + "{\"expectedWorkingRevision\":" + revision + "}")) + .build(), + HttpResponse.BodyHandlers.ofString()); + assertEquals(400, response.statusCode(), response.body()); + return JsonUtils.readValue(response.body(), OntologyValidationError.class); + } catch (java.io.IOException | InterruptedException e) { + throw new IllegalStateException(e); + } + } + + private static int status(final User user, final String path) { + final String token = + JwtAuthProvider.tokenFor(user.getEmail(), user.getEmail(), new String[] {}, 600); + try { + return HTTP.send( + HttpRequest.newBuilder() + .uri(URI.create(SdkClients.getServerUrl() + path)) + .header("Authorization", "Bearer " + token) + .GET() + .build(), + HttpResponse.BodyHandlers.ofString()) + .statusCode(); + } catch (java.io.IOException | InterruptedException e) { + throw new IllegalStateException(path, e); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeStatusIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeStatusIT.java new file mode 100644 index 000000000000..85ae1be5e748 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyShapeStatusIT.java @@ -0,0 +1,150 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyReleaseChangeType; +import org.openmetadata.schema.type.OntologyReleaseMemberChange; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.sdk.models.ListParams; + +/** What a shape edit does to the working state, the working diff and the publication status. */ +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyShapeStatusIT extends BaseOntologyApprovalIT { + + @Test + void editingASealedShapeIsOneUnpublishedChangeOnTheSingleReadAndOnTheList( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareModel(ontology); + final OntologyShape shape = + SdkClients.adminClient().ontologyShapes().create(request(ontology, "PersonShape")); + activate(ns, ontology); + assertEquals(0, unpublishedOnSingleRead(ontology)); + assertEquals(0, unpublishedOnList(ontology)); + + SdkClients.adminClient() + .ontologyShapes() + .update(shape.getId(), shape.withSeverity(OntologyShapeSeverity.WARNING)); + + assertEquals(1, unpublishedOnSingleRead(ontology)); + assertEquals(1, unpublishedOnList(ontology)); + } + + @Test + void everyShapeWriteMovesTheWorkingRevisionAndTheWorkingDiffListsTheEditedShape( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareModel(ontology); + final var service = SdkClients.adminClient().ontologyShapes(); + long revision = workingRevision(ontology); + + final OntologyShape shape = service.create(request(ontology, "PersonShape")); + final long afterCreate = workingRevision(ontology); + assertTrue(afterCreate > revision, "create"); + + activate(ns, ontology); + final long afterActivation = workingRevision(ontology); + service.update(shape.getId(), shape.withSeverity(OntologyShapeSeverity.WARNING)); + final long afterUpdate = workingRevision(ontology); + assertTrue(afterUpdate > afterActivation, "update"); + final List diff = + SdkClients.adminClient().ontologies().workingDiff(ontology.getId(), 100, null).getData(); + assertEquals( + List.of("SHAPE:CHANGED:" + shape.getId()), + diff.stream() + .map( + row -> + row.getMemberKind() + ":" + row.getChangeType() + ":" + row.getEntity().getId()) + .toList()); + assertEquals(OntologyReleaseChangeType.CHANGED, diff.getFirst().getChangeType()); + + service.delete(shape.getId().toString()); + assertTrue(workingRevision(ontology) > afterUpdate, "delete"); + } + + private static int unpublishedOnSingleRead(final Ontology ontology) { + return SdkClients.adminClient() + .ontologies() + .get(ontology.getId().toString(), "publicationStatus") + .getPublicationStatus() + .getUnpublishedChanges(); + } + + private static int unpublishedOnList(final Ontology ontology) { + return SdkClients.adminClient() + .ontologies() + .list(new ListParams().setLimit(1000).setFields("publicationStatus")) + .getData() + .stream() + .filter(listed -> listed.getId().equals(ontology.getId())) + .findFirst() + .orElseThrow() + .getPublicationStatus() + .getUnpublishedChanges(); + } + + private static long workingRevision(final Ontology ontology) { + return SdkClients.adminClient().ontologies().state(ontology.getId()).getWorkingRevision(); + } + + private static void declareModel(final Ontology ontology) { + declareClass(ontology, "Person", model("Person")); + SdkClients.adminClient() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName("name") + .withOntology(ontology.getFullyQualifiedName()) + .withIri(model("name")) + .withKind(OntologyPropertyKind.DATA)); + } + + private static CreateOntologyShape request(final Ontology ontology, final String name) { + return new CreateOntologyShape() + .withName(name) + .withDisplayName(name) + .withDescription("Shape of a person") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(model("Person")) + .withSeverity(OntologyShapeSeverity.INFO) + .withConstraints( + new ArrayList<>( + List.of( + new OntologyShapeConstraint() + .withId("has-name") + .withPath(model("name")) + .withMinCount(1)))); + } + + private static URI model(final String name) { + return URI.create("https://example.org/model/" + name); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyTableBindingIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyTableBindingIT.java new file mode 100644 index 000000000000..ba7764569edc --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IndependentOntologyTableBindingIT.java @@ -0,0 +1,536 @@ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindingsPath; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.conceptsBoundTo; +import static org.openmetadata.it.tests.OntologyMappingFixtures.dataProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.join; +import static org.openmetadata.it.tests.OntologyMappingFixtures.objectProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ownedTable; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.setMappingSource; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; +import static org.openmetadata.it.tests.OntologyMappingFixtures.unbind; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.factories.TopicTestFactory; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyAssetBinding; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * What a table binding may carry and what each write of one must satisfy: a role with its subject + * key, one row filter, and a join on every column bound to an OBJECT property. + */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +class IndependentOntologyTableBindingIT extends BaseOntologyApprovalIT { + private static final String SECOND_IDENTITY_TABLE = + "A class has at most one identity table. Change the role of the current one or remove its binding first"; + private static final String OUTSIDE_MAPPING_SOURCE = + "Once an ontology names a mapping source, every table binding must sit in that database"; + + @Test + void aTableBindingKeepsItsRoleKeyFilterAndJoinAndReadsThemBack(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final var order = declareClass(ontology, "Order", ORDER); + final var schema = schema(ns); + final Table customers = customers(schema); + final Table orders = orders(schema); + final var placedBy = objectProperty(ontology, "placedBy", order, customer); + final var total = dataProperty(ontology, "total", order); + final var asset = + binding(orders, OntologyBindingRole.IDENTITY, "tenant", "order_id") + .withRowFilter(filter("status", OntologyRowFilterOperator.NOT_EQUALS, "DELETED")) + .withColumns( + List.of( + column(total, "total"), + column(placedBy, "customer_id") + .withJoin( + join(customers, OntologyJoinStatus.INFERRED, "customer_id", "id")))); + + final var saved = put(admin(), order, asset, 0L); + + assertEquals(1L, saved.getRevision()); + assertEquals(saved, bindings(admin(), order)); + final var stored = saved.getAssets().getFirst(); + assertEquals(OntologyBindingRole.IDENTITY, stored.getRole()); + assertEquals(List.of(List.of("tenant"), List.of("order_id")), stored.getSubjectKey()); + assertEquals(List.of("status"), stored.getRowFilter().getColumn()); + assertEquals(OntologyRowFilterOperator.NOT_EQUALS, stored.getRowFilter().getOperator()); + assertEquals("DELETED", stored.getRowFilter().getValue()); + final var relation = + stored.getColumns().stream() + .filter(column -> column.getPropertyId().equals(placedBy.getId())) + .findFirst() + .orElseThrow(); + assertEquals(customers.getId(), relation.getJoin().getTargetAssetId()); + assertEquals(OntologyJoinStatus.INFERRED, relation.getJoin().getStatus()); + assertEquals(List.of("customer_id"), relation.getJoin().getOn().getFirst().getChild()); + assertEquals(List.of("id"), relation.getJoin().getOn().getFirst().getParent()); + assertEquals( + customers.getFullyQualifiedName(), relation.getJoinTarget().getFullyQualifiedName()); + final var linked = + conceptsBoundTo(admin(), orders).getLinks().getFirst().getColumns().stream() + .filter(column -> column.getPropertyId().equals(placedBy.getId())) + .findFirst() + .orElseThrow(); + assertEquals(customers.getId(), linked.getJoin().getTargetAssetId()); + assertEquals(customers.getId(), linked.getJoinTarget().getId()); + assertEquals(1L, put(admin(), order, asset, 1L).getRevision()); + } + + @Test + void aBindingWrittenWithoutARoleReadsBackWithNoRoleNoKeyAndNoFilter(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns)); + + put(admin(), order, binding(orders).withColumns(List.of()), 0L); + + final String body = + admin().getHttpClient().executeForString(HttpMethod.GET, bindingsPath(order), null); + assertTrue(body.contains(orders.getId().toString())); + for (final String field : List.of("\"role\"", "\"subjectKey\"", "\"rowFilter\"")) { + assertFalse(body.contains(field), field); + } + final var stored = bindings(admin(), order).getAssets().getFirst(); + assertNull(stored.getRole()); + assertNull(stored.getSubjectKey()); + assertNull(stored.getRowFilter()); + } + + @Test + void aSecondIdentityTableForOneClassIsRejectedWithTheRule(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final var schema = schema(ns); + final Table orders = orders(schema); + final Table archive = + table(schema, "orders_archive", column("order_id", ColumnDataType.BIGINT)); + put(admin(), order, binding(orders, OntologyBindingRole.IDENTITY, "order_id"), 0L); + + assertRejected( + SECOND_IDENTITY_TABLE, + () -> put(admin(), order, binding(archive, OntologyBindingRole.IDENTITY, "order_id"), 1L)); + + assertEquals(1L, bindings(admin(), order).getRevision()); + put(admin(), order, binding(archive, OntologyBindingRole.CONTRIBUTING, "order_id"), 1L); + put(admin(), order, binding(orders, OntologyBindingRole.CONTRIBUTING, "order_id"), 2L); + assertEquals( + 4L, + put(admin(), order, binding(archive, OntologyBindingRole.IDENTITY, "order_id"), 3L) + .getRevision()); + assertEquals( + 1L, + put(admin(), customer, binding(orders, OntologyBindingRole.IDENTITY, "order_id"), 0L) + .getRevision()); + } + + @Test + void aClassWhoseIdentityTableWasDeletedTakesAnotherIdentityTable(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var schema = schema(ns); + final Table orders = orders(schema); + final Table archive = + table(schema, "orders_archive", column("order_id", ColumnDataType.BIGINT)); + put(admin(), order, binding(orders, OntologyBindingRole.IDENTITY, "order_id"), 0L); + + admin().tables().delete(orders.getId()); + + final var saved = + put(admin(), order, binding(archive, OntologyBindingRole.IDENTITY, "order_id"), 1L); + assertEquals(2L, saved.getRevision()); + assertEquals( + List.of(archive.getId()), + saved.getAssets().stream().map(asset -> asset.getAssetId()).toList()); + assertEquals(OntologyBindingRole.IDENTITY, saved.getAssets().getFirst().getRole()); + } + + @Test + void aRoleNeedsKeyColumnsOfTheBoundTable(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns)); + + assertRejected( + "A role and a subject key are set together", + () -> put(admin(), order, binding(orders).withRole(OntologyBindingRole.IDENTITY), 0L)); + assertRejected( + "A role and a subject key are set together", + () -> + put(admin(), order, binding(orders).withSubjectKey(List.of(List.of("order_id"))), 0L)); + assertRejected( + "Every subject key column must exist in the bound table", + () -> put(admin(), order, binding(orders, OntologyBindingRole.IDENTITY, "missing"), 0L)); + assertEquals(List.of(), bindings(admin(), order).getAssets()); + } + + @Test + void onlyATableBindingTakesARole(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var topic = TopicTestFactory.createSimple(ns); + final var asset = + new OntologyAssetBinding() + .withAssetType(OntologyBindingAssetType.TOPIC) + .withAssetId(topic.getId()) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of("order_id"))); + + assertRejected( + "Only table bindings take a role, a subject key or a row filter", + () -> put(admin(), order, asset, 0L)); + } + + @Test + void aRowFilterWriteNeedsViewSampleDataOnTheTable(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns)); + final var open = filter("status", OntologyRowFilterOperator.EQUALS, "OPEN"); + final var closed = filter("status", OntologyRowFilterOperator.EQUALS, "CLOSED"); + try (var fixtures = new RdfAccessFixtures("rowFilter" + ns.shortPrefix())) { + final var noSamples = fixtures.denyRole(MetadataOperation.VIEW_SAMPLE_DATA, Entity.TABLE); + final var editor = fixtures.allowRole(MetadataOperation.EDIT_ALL, Entity.ONTOLOGY_CONCEPT); + final var client = + OntologyBindingFixtures.client( + fixtures.userToken("editor", List.of(noSamples.getId(), editor.getId()))); + + assertStatus(403, () -> put(client, order, binding(orders).withRowFilter(open), 0L)); + assertEquals(List.of(), bindings(admin(), order).getAssets()); + assertEquals(1L, put(client, order, binding(orders), 0L).getRevision()); + + final var filtered = put(admin(), order, binding(orders).withRowFilter(open), 1L); + assertEquals(open, filtered.getAssets().getFirst().getRowFilter()); + assertEquals(open, bindings(client, order).getAssets().getFirst().getRowFilter()); + + assertStatus(403, () -> put(client, order, binding(orders).withRowFilter(closed), 2L)); + final var keyed = + put( + client, + order, + binding(orders, OntologyBindingRole.IDENTITY, "order_id").withRowFilter(open), + 2L); + assertEquals(open, keyed.getAssets().getFirst().getRowFilter()); + assertEquals(OntologyBindingRole.IDENTITY, keyed.getAssets().getFirst().getRole()); + final var cleared = + put(client, order, binding(orders, OntologyBindingRole.IDENTITY, "order_id"), 3L); + assertNull(cleared.getAssets().getFirst().getRowFilter()); + } + } + + @Test + void aWriterSetsARowFilterOnATableWhoseSampleDataTheyMayViewAndOnNoOther(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var schema = schema(ns); + final var open = filter("status", OntologyRowFilterOperator.EQUALS, "OPEN"); + try (var fixtures = new RdfAccessFixtures("ownFilter" + ns.shortPrefix())) { + final var ownedOnly = + fixtures.denyRole(MetadataOperation.VIEW_SAMPLE_DATA, Entity.TABLE, "!isOwner()"); + final var editor = fixtures.allowRole(MetadataOperation.EDIT_ALL, Entity.ONTOLOGY_CONCEPT); + final var client = + OntologyBindingFixtures.client( + fixtures.userToken("editor", List.of(ownedOnly.getId(), editor.getId()))); + final Table owned = + ownedTable( + schema, + "orders", + OntologyBindingFixtures.readerReference(client), + column("order_id", ColumnDataType.BIGINT), + column("status", ColumnDataType.VARCHAR)); + final Table other = + table( + schema, + "orders_archive", + column("order_id", ColumnDataType.BIGINT), + column("status", ColumnDataType.VARCHAR)); + + final var saved = put(client, order, binding(owned).withRowFilter(open), 0L); + + assertEquals(1L, saved.getRevision()); + assertEquals(open, bindings(client, order).getAssets().getFirst().getRowFilter()); + assertStatus(403, () -> put(client, order, binding(other).withRowFilter(open), 1L)); + assertEquals(1L, bindings(admin(), order).getRevision()); + assertEquals(2L, put(client, order, binding(other), 1L).getRevision()); + } + } + + @Test + void aRowFilterNamesAColumnOfTheTableAndAValueItsOperatorTakes(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns)); + + assertRejected( + "A row filter column must exist in the bound table", + () -> + put( + admin(), + order, + binding(orders) + .withRowFilter(filter("missing", OntologyRowFilterOperator.IS_NULL, null)), + 0L)); + assertRejected( + "A row filter compares with a string of at most 1024 characters", + () -> + put( + admin(), + order, + binding(orders) + .withRowFilter(filter("status", OntologyRowFilterOperator.IS_NULL, "OPEN")), + 0L)); + final var listed = + put( + admin(), + order, + binding(orders) + .withRowFilter( + filter("status", OntologyRowFilterOperator.IN, List.of("OPEN", "HELD"))), + 0L); + assertEquals(List.of("OPEN", "HELD"), listed.getAssets().getFirst().getRowFilter().getValue()); + } + + @Test + void aColumnBoundToAnObjectPropertyNeedsAJoinToATableInTheSameDatabase(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final var order = declareClass(ontology, "Order", ORDER); + final var schema = schema(ns); + final Table customers = customers(schema); + final Table orders = orders(schema); + final Table elsewhere = customers(schema(ns)); + final var placedBy = objectProperty(ontology, "placedBy", order, customer); + final var total = dataProperty(ontology, "total", order); + final var relation = column(placedBy, "customer_id"); + + assertRejected( + "A column bound to an OBJECT property requires a join", + () -> put(admin(), order, binding(orders).withColumns(List.of(relation)), 0L)); + assertRejected( + "A join target must be a table in the same database as the bound table", + () -> + put( + admin(), + order, + binding(orders) + .withColumns( + List.of( + column(placedBy, "customer_id") + .withJoin( + join( + elsewhere, + OntologyJoinStatus.CONFIRMED, + "customer_id", + "id")))), + 0L)); + assertRejected( + "Join columns must exist", + () -> + put( + admin(), + order, + binding(orders) + .withColumns( + List.of( + column(placedBy, "customer_id") + .withJoin( + join( + customers, + OntologyJoinStatus.CONFIRMED, + "customer_id", + "missing")))), + 0L)); + assertRejected( + "Only a column bound to an OBJECT property takes a join", + () -> + put( + admin(), + order, + binding(orders) + .withColumns( + List.of( + column(total, "total") + .withJoin( + join( + customers, + OntologyJoinStatus.CONFIRMED, + "customer_id", + "id")))), + 0L)); + assertEquals(List.of(), bindings(admin(), order).getAssets()); + + final var saved = + put( + admin(), + order, + binding(orders) + .withColumns( + List.of( + column(placedBy, "customer_id") + .withJoin( + join( + customers, + OntologyJoinStatus.CONFIRMED, + "customer_id", + "id")))), + 0L); + final var stored = saved.getAssets().getFirst().getColumns().getFirst(); + assertEquals(customers.getId(), stored.getJoin().getTargetAssetId()); + assertEquals(OntologyJoinStatus.CONFIRMED, stored.getJoin().getStatus()); + assertEquals(customers.getId(), stored.getJoinTarget().getId()); + assertEquals(saved, bindings(admin(), order)); + } + + @Test + void aWriterJoinsToATableTheyMayViewAndAReaderDeniedTheTargetSeesNoTarget( + final TestNamespace ns) { + final var ontology = createOntology(ns); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final var order = declareClass(ontology, "Order", ORDER); + final var schema = schema(ns); + final Table customers = customers(schema); + final var placedBy = objectProperty(ontology, "placedBy", order, customer); + try (var fixtures = new RdfAccessFixtures("joinTarget" + ns.shortPrefix())) { + final var ownedOnly = + fixtures.denyRole(MetadataOperation.VIEW_BASIC, Entity.TABLE, "!isOwner()"); + final var editor = fixtures.allowRole(MetadataOperation.EDIT_ALL, Entity.ONTOLOGY_CONCEPT); + final var client = + OntologyBindingFixtures.client( + fixtures.userToken("editor", List.of(ownedOnly.getId(), editor.getId()))); + final var owner = OntologyBindingFixtures.readerReference(client); + final Table orders = + ownedTable( + schema, + "orders", + owner, + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT)); + final Table partners = + ownedTable(schema, "partners", owner, column("id", ColumnDataType.BIGINT)); + final var hidden = joined(orders, placedBy, customers); + + assertStatus(403, () -> put(client, order, hidden, 0L)); + assertEquals(List.of(), bindings(admin(), order).getAssets()); + + final var own = put(client, order, joined(orders, placedBy, partners), 0L); + assertEquals(1L, own.getRevision()); + final var written = bindings(client, order).getAssets().getFirst().getColumns().getFirst(); + assertEquals(partners.getId(), written.getJoin().getTargetAssetId()); + assertEquals(partners.getId(), written.getJoinTarget().getId()); + final var linked = + conceptsBoundTo(client, orders).getLinks().getFirst().getColumns().getFirst(); + assertEquals(partners.getId(), linked.getJoinTarget().getId()); + + put(admin(), order, hidden, 1L); + final var seen = bindings(client, order).getAssets().getFirst().getColumns().getFirst(); + assertEquals(customers.getId(), seen.getJoin().getTargetAssetId()); + assertNull(seen.getJoinTarget()); + final var relinked = + conceptsBoundTo(client, orders).getLinks().getFirst().getColumns().getFirst(); + assertEquals(customers.getId(), relinked.getJoin().getTargetAssetId()); + assertNull(relinked.getJoinTarget()); + } + } + + @Test + void onceAnOntologyNamesAMappingSourceATableOutsideItIsRejected(final TestNamespace ns) { + final var ontology = createOntology(ns); + final var order = declareClass(ontology, "Order", ORDER); + final var inside = schema(ns); + final var outside = schema(ns); + final Table earlier = table(outside, "orders_2019", column("order_id", ColumnDataType.BIGINT)); + final Table later = table(outside, "orders_2020", column("order_id", ColumnDataType.BIGINT)); + final Table orders = orders(inside); + put(admin(), order, binding(earlier), 0L); + + setMappingSource(admin(), ontology, inside.getDatabase()); + + assertRejected(OUTSIDE_MAPPING_SOURCE, () -> put(admin(), order, binding(later), 1L)); + assertEquals(1L, put(admin(), order, binding(earlier), 1L).getRevision()); + assertRejected( + OUTSIDE_MAPPING_SOURCE, + () -> put(admin(), order, binding(earlier, OntologyBindingRole.IDENTITY, "order_id"), 1L)); + assertEquals( + 2L, + put(admin(), order, binding(orders, OntologyBindingRole.IDENTITY, "order_id"), 1L) + .getRevision()); + unbind(admin(), order, earlier, 2L); + assertEquals( + List.of(orders.getId()), + bindings(admin(), order).getAssets().stream().map(asset -> asset.getAssetId()).toList()); + } + + private static Table orders(final DatabaseSchema schema) { + return table( + schema, + "orders", + column("tenant", ColumnDataType.VARCHAR), + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT), + column("status", ColumnDataType.VARCHAR), + column("total", ColumnDataType.DECIMAL)); + } + + private static Table customers(final DatabaseSchema schema) { + return table( + schema, + "customers", + column("tenant", ColumnDataType.VARCHAR), + column("id", ColumnDataType.BIGINT)); + } + + /** A binding of {@code table} whose {@code customer_id} column joins to {@code target.id}. */ + private static OntologyAssetBinding joined( + final Table table, final OntologyProperty relation, final Table target) { + return binding(table) + .withColumns( + List.of( + column(relation, "customer_id") + .withJoin(join(target, OntologyJoinStatus.CONFIRMED, "customer_id", "id")))); + } + + private static void assertStatus(final int status, final Runnable request) { + assertEquals(status, assertThrows(OpenMetadataException.class, request::run).getStatusCode()); + } + + /** A 400 whose message names the rule that refused the write. */ + private static void assertRejected(final String rule, final Runnable request) { + final var failure = assertThrows(OpenMetadataException.class, request::run); + assertEquals(400, failure.getStatusCode()); + assertTrue(failure.getMessage().contains(rule), failure.getMessage()); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphBindingScanIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphBindingScanIT.java index 2bec8513190d..a1975482a547 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphBindingScanIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphBindingScanIT.java @@ -41,6 +41,7 @@ import org.openmetadata.schema.type.OntologyBindingAssetType; import org.openmetadata.schema.type.OntologyHydratedAssetBinding; import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.StoredBinding; import org.openmetadata.service.util.FullyQualifiedName; import org.openmetadata.service.util.RestUtil; @@ -145,7 +146,7 @@ void exactVisibleCountAndPreviewCursorSurviveMoreThanOneBindingPage(final TestNa } while (pageAfter != null); assertEquals(List.of(visible.getLast()), pageRemaining); assertEquals(10, emptyPagePages); - assertEquals(List.of(500L, 500L, 500L, 500L, 500L, 500L, 18L), observed.bindingRows()); + assertEquals(List.of(500L, 500L, 500L, 500L, 500L, 500L, 18L, 0L), observed.bindingRows()); assertEquals(500, observed.largestInList()); observed.assertBounded(); } finally { @@ -189,11 +190,15 @@ void bindingKeysetsAdvanceAcrossConceptsSharingTheSameAsset(final TestNamespace Entity.getCollectionDAO() .ontologyConceptBindingDAO() .upsert( - concept.getId(), - topic.getId(), - OntologyBindingAssetType.TOPIC.value(), - FullyQualifiedName.buildHash(topic.getFullyQualifiedName()), - "[]"); + new StoredBinding( + concept.getId().toString(), + topic.getId().toString(), + OntologyBindingAssetType.TOPIC.value(), + FullyQualifiedName.buildHash(topic.getFullyQualifiedName()), + "[]", + null, + null, + null)); } final var observed = new ScanObservation(); final var graph = observed.watch(() -> graph(admin(), ontology, "")); @@ -205,7 +210,7 @@ void bindingKeysetsAdvanceAcrossConceptsSharingTheSameAsset(final TestNamespace assertEquals(topic.getId(), cluster.getAssets().getFirst().getAsset().getId()); assertNull(cluster.getAfter()); } - assertEquals(List.of(500L, 1L), observed.bindingRows()); + assertEquals(List.of(500L, 1L, 0L), observed.bindingRows()); observed.assertBounded(); } finally { concepts.forEach( diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java new file mode 100644 index 000000000000..3561a9a57ba1 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountBoundIT.java @@ -0,0 +1,494 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.openmetadata.it.tests.NativeOntologyPageFixtures.clusterPage; +import static org.openmetadata.it.tests.NativeOntologyPageFixtures.graphPage; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertionRequest; +import static org.openmetadata.it.tests.OntologyBindingFixtures.graph; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.join; +import static org.openmetadata.it.tests.OntologyMappingFixtures.objectProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.net.URI; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.util.OssTestServer; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateTableProfile; +import org.openmetadata.schema.api.data.NativeOntologyCount; +import org.openmetadata.schema.api.data.NativeOntologyCount.State; +import org.openmetadata.schema.api.data.NativeOntologyDataGraphPage; +import org.openmetadata.schema.api.data.NativeOntologyLoadedPrefix; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.ColumnProfile; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * What the data graph says about a class that binds more tables than one read of its bindings + * keeps. A class with a hub of table rows still counts its records and the relations onto it. A + * relation from a class with other tables states the join the statements of the mapping would + * find, whatever the number of its tables, and a page of such classes runs a fixed number of + * statements, each scan of bindings well inside one scan page. + */ +@Isolated("Counts SQL statements while serving the native data graph over HTTP") +@ExtendWith(TestNamespaceExtension.class) +class NativeOntologyDataGraphCountBoundIT extends BaseOntologyApprovalIT { + private static final Logger LOG = + LoggerFactory.getLogger(NativeOntologyDataGraphCountBoundIT.class); + private static final long PROFILED_AT = 1_700_000_000_000L; + private static final int SPOKES = 59; + private static final int OTHER_ROWS_PER_SPOKE = 4; + + /** What the statements of the mapping accept, which a class over it is refused for. */ + private static final int MAX_CONTRIBUTING_TABLES = 32; + + /** One scan page of 500 rows holds the identity row and 33 contributing rows of 14 classes. */ + private static final int CLASSES_READ_BY_ONE_STATEMENT = 500 / (MAX_CONTRIBUTING_TABLES + 2); + + private static final String HOLDER_STATEMENT = "bindingrole in ("; + + /** The identity row and four others fill the five rows of the first read. */ + private static final int CLASS_CUT_BEFORE_THE_HOLDER = 5; + + @Test + void aHubOfTableRowsKeepsItsRecordsAndEveryRelationOntoItKeepsItsLinks(final TestNamespace ns) { + final Star star = star(ns, "hub", OntologyJoinStatus.CONFIRMED, 0); + insertFakeRows(star.hub(), 400, 0); + + final var observed = new NativeOntologyGraphScanProbe.ScanObservation(); + final Loaded all = observed.watch(() -> loadAll(star.ontology())); + + assertEquals(exact(77), all.records().get(star.hub().getId())); + for (int index = 0; index < SPOKES; index++) { + final UUID spoke = star.spokes().get(index).getId(); + assertEquals(exact(1000 + index), all.records().get(spoke)); + assertEquals(exact(10 + index), all.links().get(spoke)); + } + assertEquals(SPOKES, all.links().size()); + assertEquals( + 0, + observed.bindingSql().stream().filter(sql -> sql.contains(HOLDER_STATEMENT)).count(), + "No class is cut with no confirmed join, so no class is read again"); + observed.assertBounded(); + } + + @Test + void aPageOfClassesThatAreAllCutIsReadAgainInAFixedNumberOfStatements(final TestNamespace ns) { + assumeFalse(OssTestServer.isExternalMode(), "Counts the embedded server's SQL statements"); + final Star whole = star(ns, "none", OntologyJoinStatus.CONFIRMED, 0); + final Star cut = star(ns, "cut", OntologyJoinStatus.INFERRED, OTHER_ROWS_PER_SPOKE); + insertFakeRows(whole.hub(), 400, 0); + + final Loaded wholeAll = loadAll(whole.ontology()); + final var wholePage = new NativeOntologyGraphScanProbe.ScanObservation(); + wholePage.watch(() -> lastPage(whole.ontology(), wholeAll)); + final Loaded cutAll = loadAll(cut.ontology()); + final var cutPage = new NativeOntologyGraphScanProbe.ScanObservation(); + final var page = cutPage.watch(() -> lastPage(cut.ontology(), cutAll)); + + final long wholeReads = holderStatements(wholePage); + final long cutReads = holderStatements(cutPage); + LOG.info( + "Last page of {} classes: no class cut {} SELECT statements and {} second reads; every" + + " class cut {} SELECT statements and {} second reads, binding scans mapped {}", + SPOKES + 1, + wholePage.selects(), + wholeReads, + cutPage.selects(), + cutReads, + cutPage.bindingRows()); + assertEquals(0, wholeReads); + assertEquals( + Math.ceilDiv(SPOKES, CLASSES_READ_BY_ONE_STATEMENT), + cutReads, + "Every cut class is read again, in groups that fit one scan page"); + assertEquals(wholePage.selects() + cutReads, cutPage.selects()); + cutPage.assertBounded(); + wholePage.assertBounded(); + assertEquals(SPOKES, page.getTopology().getEdges().size()); + page.getTopology() + .getEdges() + .forEach(edge -> assertEquals(state(State.JOIN_NOT_CONFIRMED), edge.getLinks())); + } + + @Test + void aClassWithOtherTablesAndOnlyAnInferredJoinOnItsIdentityTableIsNotConfirmed( + final TestNamespace ns) { + final Pair pair = pair(ns, "inferred", OntologyJoinStatus.INFERRED); + bindOtherTables(ns, pair, 6); + + assertEquals(state(State.JOIN_NOT_CONFIRMED), links(pair)); + } + + @Test + void aClassWithOtherTablesAndNoJoinHasNoJoin(final TestNamespace ns) { + final Pair pair = pair(ns, "nojoin", null); + bindOtherTables(ns, pair, 6); + + assertEquals(state(State.NO_JOIN), links(pair)); + } + + @Test + void aConfirmedJoinOnADeletedContributingTableLeavesTheInferredJoinOfTheIdentityTable( + final TestNamespace ns) { + final Pair pair = pair(ns, "deleted", OntologyJoinStatus.INFERRED); + bindOtherTables(ns, pair, 6); + insertFakeRow( + pair.spoke(), + new UUID(0, 99), + List.of( + column(pair.relation(), "hub_id") + .withJoin(join(pair.hubTable(), OntologyJoinStatus.CONFIRMED, "hub_id", "id")))); + + assertEquals(state(State.JOIN_NOT_CONFIRMED), links(pair)); + } + + @Test + void aClassOverTheContributingTableLimitGivesNoJoinState(final TestNamespace ns) { + final Pair pair = pair(ns, "overlimit", OntologyJoinStatus.INFERRED); + insertFakeRows(pair.spoke(), MAX_CONTRIBUTING_TABLES + 1, 0); + + assertEquals(state(State.NOT_DERIVABLE), links(pair)); + } + + @Test + void aClassAtTheContributingTableLimitStillStatesItsJoin(final TestNamespace ns) { + final Pair pair = pair(ns, "atlimit", OntologyJoinStatus.INFERRED); + insertFakeRows(pair.spoke(), MAX_CONTRIBUTING_TABLES, 0); + + assertEquals(state(State.JOIN_NOT_CONFIRMED), links(pair)); + } + + @Test + void aDeletedContributingTableHoldsNoJoinWhenTheClassIsCutBeforeIt(final TestNamespace ns) { + assertADeletedHolderHoldsNoJoin(ns, "deletedcut", CLASS_CUT_BEFORE_THE_HOLDER); + } + + @Test + void aDeletedContributingTableHoldsNoJoinWhenItIsAmongTheFirstRows(final TestNamespace ns) { + assertADeletedHolderHoldsNoJoin(ns, "deletedfirst", 0); + } + + /** + * A real contributing table holds the only confirmed join of the relation, and the identity + * table holds an inferred one. While the table exists no count is stated, because the join sits + * on a contributing table. Soft-deleted or hard-deleted, the table holds no join, and the state + * is the inferred join of the identity table, as the statements of the mapping find it. Binding + * rows that sort before the table are inserted after its binding is put, because a put rewrites + * the rows of the class, so that with enough of them the table lies beyond the first read. + */ + private static void assertADeletedHolderHoldsNoJoin( + final TestNamespace ns, final String name, final int rowsBeforeTheHolder) { + final Pair pair = pair(ns, name, OntologyJoinStatus.INFERRED); + final Table holder = holderTable(ns, pair, name + "holder"); + put( + admin(), + pair.spoke(), + binding(holder, OntologyBindingRole.CONTRIBUTING, "id") + .withColumns( + List.of( + column(pair.relation(), "hub_id") + .withJoin( + join(pair.hubTable(), OntologyJoinStatus.CONFIRMED, "hub_id", "id")))), + 1L); + insertFakeRows(pair.spoke(), rowsBeforeTheHolder, 0); + assertEquals(2 + rowsBeforeTheHolder, bindingRows(pair.spoke()), "The class's rows"); + + assertEquals(state(State.NOT_DERIVABLE), links(pair)); + admin().tables().delete(holder.getId().toString(), Map.of("hardDelete", "false")); + assertEquals(state(State.JOIN_NOT_CONFIRMED), links(pair)); + admin().tables().restore(holder.getId()); + assertEquals(state(State.NOT_DERIVABLE), links(pair)); + admin() + .tables() + .delete(holder.getId().toString(), Map.of("hardDelete", "true", "recursive", "true")); + assertEquals(state(State.JOIN_NOT_CONFIRMED), links(pair)); + } + + private static Table holderTable(final TestNamespace ns, final Pair pair, final String name) { + final Table holder = + table( + pair.schema(), + ns.prefix(name), + column("id", ColumnDataType.BIGINT), + column("hub_id", ColumnDataType.BIGINT)); + profile(holder, columnProfile("id", 40, 0, 40), columnProfile("hub_id", 31, 0, 4)); + return holder; + } + + private static long bindingRows(final OntologyConcept concept) { + return Entity.getJdbi() + .withHandle( + handle -> + handle + .createQuery( + "SELECT COUNT(*) FROM ontology_concept_binding WHERE conceptId = :id") + .bind("id", concept.getId().toString()) + .mapTo(Long.class) + .one()); + } + + private static long holderStatements( + final NativeOntologyGraphScanProbe.ScanObservation observed) { + return observed.bindingSql().stream().filter(sql -> sql.contains(HOLDER_STATEMENT)).count(); + } + + private static NativeOntologyCount links(final Pair pair) { + final var graph = graph(admin(), pair.ontology(), ""); + assertEquals(1, graph.getEdges().size()); + return graph.getEdges().getFirst().getLinks(); + } + + private static NativeOntologyCount exact(final long value) { + return new NativeOntologyCount() + .withState(State.EXACT) + .withValue(value) + .withProfiledAt(PROFILED_AT); + } + + private static NativeOntologyCount state(final State state) { + return new NativeOntologyCount().withState(state); + } + + /** A hub class and classes that each hold a join onto the hub's identity table. */ + private record Star(Ontology ontology, OntologyConcept hub, List spokes) {} + + private static Star star( + final TestNamespace ns, + final String name, + final OntologyJoinStatus status, + final int otherRows) { + final Ontology ontology = createOntology(ns, name); + final DatabaseSchema schema = OntologyMappingFixtures.schema(ns); + final OntologyConcept hub = declareClass(ontology, "Hub", URI.create("urn:Hub")); + final Table hubTable = + table(schema, ns.prefix(name + "hub"), column("id", ColumnDataType.BIGINT)); + put(admin(), hub, binding(hubTable, OntologyBindingRole.IDENTITY, "id"), 0L); + profile(hubTable, columnProfile("id", 77, 0, 77)); + final List spokes = new ArrayList<>(); + for (int index = 0; index < SPOKES; index++) { + final URI iri = URI.create("urn:C" + index); + final OntologyConcept spoke = declareClass(ontology, "C" + index, iri); + final OntologyProperty relation = objectProperty(ontology, "r" + index, spoke, hub); + admin() + .ontologyAxioms() + .create( + assertionRequest(ontology, iri, URI.create("urn:Hub"), "ax" + index) + .withPropertyIri(relation.getIri())); + final Table spokeTable = + table( + schema, + ns.prefix(name + "c" + index), + column("id", ColumnDataType.BIGINT), + column("hub_id", ColumnDataType.BIGINT)); + put( + admin(), + spoke, + binding(spokeTable, OntologyBindingRole.IDENTITY, "id") + .withColumns( + List.of( + column(relation, "hub_id").withJoin(join(hubTable, status, "hub_id", "id")))), + 0L); + profile( + spokeTable, + columnProfile("id", 1000 + index, 0, 1000 + index), + columnProfile("hub_id", 10 + index, 0, 3)); + insertFakeRows(spoke, otherRows, 0); + spokes.add(spoke); + } + return new Star(ontology, hub, spokes); + } + + /** One class related to a hub class, over an identity table of its own. */ + private record Pair( + Ontology ontology, + OntologyConcept spoke, + Table hubTable, + Table spokeTable, + OntologyProperty relation, + DatabaseSchema schema) {} + + private static Pair pair( + final TestNamespace ns, final String name, final OntologyJoinStatus join) { + final Ontology ontology = createOntology(ns, name); + final DatabaseSchema schema = OntologyMappingFixtures.schema(ns); + final OntologyConcept hub = declareClass(ontology, "Hub", URI.create("urn:Hub")); + final OntologyConcept spoke = declareClass(ontology, "Spoke", URI.create("urn:Spoke")); + final Table hubTable = + table(schema, ns.prefix(name + "hub"), column("id", ColumnDataType.BIGINT)); + final Table spokeTable = + table( + schema, + ns.prefix(name + "spoke"), + column("id", ColumnDataType.BIGINT), + column("hub_id", ColumnDataType.BIGINT)); + final OntologyProperty relation = objectProperty(ontology, "toHub", spoke, hub); + admin() + .ontologyAxioms() + .create( + assertionRequest(ontology, URI.create("urn:Spoke"), URI.create("urn:Hub"), "axT") + .withPropertyIri(relation.getIri())); + put(admin(), hub, binding(hubTable, OntologyBindingRole.IDENTITY, "id"), 0L); + final var identity = binding(spokeTable, OntologyBindingRole.IDENTITY, "id"); + put( + admin(), + spoke, + join == null + ? identity + : identity.withColumns( + List.of(column(relation, "hub_id").withJoin(join(hubTable, join, "hub_id", "id")))), + 0L); + profile(hubTable, columnProfile("id", 5, 0, 5)); + profile(spokeTable, columnProfile("id", 9, 0, 9), columnProfile("hub_id", 9, 0, 5)); + return new Pair(ontology, spoke, hubTable, spokeTable, relation, schema); + } + + /** Real contributing tables, bound after the identity table. */ + private static void bindOtherTables(final TestNamespace ns, final Pair pair, final int count) { + for (int index = 0; index < count; index++) { + final Table other = + table( + pair.schema(), + ns.prefix( + "o" + Integer.toHexString(pair.ontology().getName().hashCode()) + "x" + index), + column("id", ColumnDataType.BIGINT)); + put( + admin(), + pair.spoke(), + binding(other, OntologyBindingRole.CONTRIBUTING, "id"), + index + 1L); + } + } + + private static ColumnProfile columnProfile( + final String name, final double values, final double nulls, final double distinct) { + return new ColumnProfile() + .withName(name) + .withTimestamp(PROFILED_AT) + .withValuesCount(values) + .withNullCount(nulls) + .withDistinctCount(distinct); + } + + private static void profile(final Table table, final ColumnProfile... columns) { + admin() + .getHttpClient() + .execute( + HttpMethod.PUT, + "/v1/tables/" + table.getId() + "/tableProfile", + new CreateTableProfile() + .withTableProfile(new TableProfile().withTimestamp(PROFILED_AT).withRowCount(999d)) + .withColumnProfile(List.of(columns)), + Table.class); + } + + /** Contributing rows to tables that do not exist, ids ascending from {@code base}. */ + private static void insertFakeRows( + final OntologyConcept concept, final int count, final long base) { + for (int index = 1; index <= count; index++) { + insertFakeRow(concept, new UUID(0, base + index), List.of()); + } + } + + private static void insertFakeRow( + final OntologyConcept concept, final UUID id, final List columns) { + Entity.getJdbi() + .useHandle( + handle -> + handle + .createUpdate( + "INSERT INTO ontology_concept_binding " + + "(conceptId, assetId, assetType, assetFqnHash, columnBindings, " + + "bindingRole) VALUES (:conceptId, :assetId, 'table', :hash, " + + columnsParameter() + + ", 'contributing')") + .bind("conceptId", concept.getId().toString()) + .bind("assetId", id.toString()) + .bind("hash", "fake-" + concept.getId() + id) + .bind("columns", JsonUtils.pojoToJson(columns)) + .execute()); + } + + private static String columnsParameter() { + return TestSuiteBootstrap.getConnectionType() == ConnectionType.POSTGRES + ? "(:columns :: jsonb)" + : ":columns"; + } + + private record Loaded( + List loaded, + Map records, + Map links, + List beforeLast, + int lastOffset) {} + + private static Loaded loadAll(final Ontology ontology) { + final OpenMetadataClient client = admin(); + List loaded = List.of(); + List beforeLast = List.of(); + final Map records = new LinkedHashMap<>(); + final Map links = new LinkedHashMap<>(); + Integer offset = 0; + int lastOffset = 0; + while (offset != null) { + beforeLast = loaded; + lastOffset = offset; + final var response = graphPage(client, ontology, loaded, clusterPage(offset, 12)); + response + .getClusters() + .forEach(cluster -> records.put(cluster.getConcept().getId(), cluster.getRecords())); + response + .getTopology() + .getEdges() + .forEach(edge -> links.put(edge.getFromConceptId(), edge.getLinks())); + loaded = response.getLoaded(); + offset = response.getNextClusterOffset(); + } + return new Loaded(loaded, records, links, beforeLast, lastOffset); + } + + private static NativeOntologyDataGraphPage lastPage(final Ontology ontology, final Loaded all) { + return graphPage(admin(), ontology, all.beforeLast(), clusterPage(all.lastOffset(), 12)); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java new file mode 100644 index 000000000000..b1c9946095ee --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphCountIT.java @@ -0,0 +1,472 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.openmetadata.it.tests.NativeOntologyGraphScanProbe.fewestReads; +import static org.openmetadata.it.tests.NativeOntologyPageFixtures.clusterPage; +import static org.openmetadata.it.tests.NativeOntologyPageFixtures.graphPage; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertionRequest; +import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.graph; +import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; +import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.join; +import static org.openmetadata.it.tests.OntologyMappingFixtures.objectProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.net.URI; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.util.OssTestServer; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateTableProfile; +import org.openmetadata.schema.api.data.NativeOntologyAssetCluster; +import org.openmetadata.schema.api.data.NativeOntologyClusterAsset; +import org.openmetadata.schema.api.data.NativeOntologyConceptEdge; +import org.openmetadata.schema.api.data.NativeOntologyCount; +import org.openmetadata.schema.api.data.NativeOntologyCount.State; +import org.openmetadata.schema.api.data.NativeOntologyDataGraph; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.ColumnProfile; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.Paging; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The records of each class and the links of each relation on {@code GET /dataGraph} and on {@code + * POST /dataGraph/pages}, read from the stored profiles of identity tables. Every case compares + * the whole graph, with each entity reference cut down to the id, type and name that identify it. + */ +@Isolated("Counts SQL statements while serving the native data graph over HTTP") +@ExtendWith(TestNamespaceExtension.class) +class NativeOntologyDataGraphCountIT extends BaseOntologyApprovalIT { + private static final Logger LOG = LoggerFactory.getLogger(NativeOntologyDataGraphCountIT.class); + private static final long PROFILED_AT = 1_700_000_000_000L; + private static final double MISLEADING_ROW_COUNT = 999d; + + @Test + void anUnfilteredClassAndItsConfirmedRelationCountFromTheStoredProfiles(final TestNamespace ns) { + final World world = world(ns, "counts", OntologyJoinStatus.CONFIRMED, false, false); + + final var expected = world.expected(exact(100), exact(50), exact(90), true, true); + assertAllEndpoints(admin(), world, expected); + } + + @Test + void aFilteredClassAndTheRelationFromItCountNothing(final TestNamespace ns) { + final World world = world(ns, "counts", OntologyJoinStatus.CONFIRMED, true, false); + + final var expected = + world.expected( + state(State.NOT_DERIVABLE), exact(50), state(State.NOT_DERIVABLE), true, true); + assertAllEndpoints(admin(), world, expected); + } + + @Test + void aRelationHeldByALinkTableCountsNothingAndItsClassStillCountsItsRecords( + final TestNamespace ns) { + final World world = world(ns, "counts", OntologyJoinStatus.CONFIRMED, false, true); + + final var expected = + world.expectedWithLinkTable(exact(100), exact(50), state(State.NOT_DERIVABLE)); + assertAllEndpoints(admin(), world, expected); + } + + @Test + void aJoinThatIsOnlyInferredIsNotConfirmed(final TestNamespace ns) { + final World world = world(ns, "counts", OntologyJoinStatus.INFERRED, false, false); + + final var expected = + world.expected(exact(100), exact(50), state(State.JOIN_NOT_CONFIRMED), true, true); + assertAllEndpoints(admin(), world, expected); + } + + @Test + void aReaderWithoutTheDataProfileRightSeesNoProfileInsteadOfACount(final TestNamespace ns) { + final World world = world(ns, "counts", OntologyJoinStatus.CONFIRMED, false, false); + try (var fixtures = new RdfAccessFixtures("countDenied" + ns.shortPrefix())) { + final var denied = fixtures.denyRole(MetadataOperation.VIEW_DATA_PROFILE, Entity.TABLE); + final OpenMetadataClient reader = + client(fixtures.userToken("noProfile", List.of(denied.getId()))); + + final var expected = + world.expected( + state(State.NO_PROFILE), + state(State.NO_PROFILE), + state(State.NO_PROFILE), + false, + false); + assertAllEndpoints(reader, world, expected); + } + } + + @Test + void aReaderWhoMayNotViewTheIdentityTableSeesItHiddenAndLearnsNothingMore( + final TestNamespace ns) { + final World world = world(ns, "counts", OntologyJoinStatus.CONFIRMED, false, false); + final Table notes = + table(world.schema(), ns.prefix("order_notes"), column("order_id", ColumnDataType.BIGINT)); + put(admin(), world.order(), binding(notes, OntologyBindingRole.CONTRIBUTING, "order_id"), 1L); + try (var fixtures = new RdfAccessFixtures("countHidden" + ns.shortPrefix())) { + final OpenMetadataClient reader = ownerReader(fixtures, Entity.TABLE); + final EntityReference owner = readerReference(reader); + own(world.customers(), owner); + own(notes, owner); + + final var expected = + world.expectedHidden(notes, state(State.IDENTITY_TABLE_HIDDEN), exact(50)); + assertAllEndpoints(reader, world, expected); + } + } + + @Test + void theStatementsOfAReadDoNotGrowWithTheClassesAndRelations(final TestNamespace ns) { + assumeFalse(OssTestServer.isExternalMode(), "Counts the embedded server's SQL statements"); + final World narrow = world(ns, "narrow", OntologyJoinStatus.CONFIRMED, false, false); + final World wide = world(ns, "wide", OntologyJoinStatus.CONFIRMED, false, false); + for (int index = 0; index < 8; index++) { + relatedClass(ns, wide, index); + } + + final int narrowReads = fewestReads(admin(), narrow.ontology()); + final int wideReads = fewestReads(admin(), wide.ontology()); + + LOG.info( + "Graph read SQL statements with counts: 2 classes={}, 10 classes={}", + narrowReads, + wideReads); + assertEquals(narrowReads, wideReads); + } + + /** A class over a table of its own, with a relation to the customers. */ + private static void relatedClass(final TestNamespace ns, final World world, final int index) { + final URI iri = URI.create("urn:Extra" + index); + final OntologyConcept extra = declareClass(world.ontology(), "Extra" + index, iri); + final OntologyProperty relation = + objectProperty(world.ontology(), "relatesTo" + index, extra, world.customer()); + admin() + .ontologyAxioms() + .create( + assertionRequest( + world.ontology(), iri, OntologyBindingFixtures.CUSTOMER, "extra" + index) + .withPropertyIri(relation.getIri())); + final Table extras = + table( + world.schema(), + ns.prefix("extra" + index), + column("id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT)); + put( + admin(), + extra, + binding(extras, OntologyBindingRole.IDENTITY, "id") + .withColumns( + List.of( + column(relation, "customer_id") + .withJoin( + join( + world.customers(), + OntologyJoinStatus.CONFIRMED, + "customer_id", + "id")))), + 0L); + profile(extras, columnProfile("id", 10, 0, 10), columnProfile("customer_id", 10, 0, 5)); + } + + private static void assertAllEndpoints( + final OpenMetadataClient caller, final World world, final NativeOntologyDataGraph expected) { + final NativeOntologyDataGraph graph = graph(caller, world.ontology(), "?limit=12"); + assertEquals(expected, slim(graph)); + final var page = graphPage(caller, world.ontology(), List.of(), clusterPage(0, 12)); + assertEquals(expected.getClusters(), slim(page.getClusters())); + assertEquals(expected.getEdges(), slimEdges(page.getTopology().getEdges())); + assertEquals(List.of(), page.getTopology().getLineageEdges()); + assertNull(page.getBindings()); + } + + private static NativeOntologyCount exact(final long value) { + return new NativeOntologyCount() + .withState(State.EXACT) + .withValue(value) + .withProfiledAt(PROFILED_AT); + } + + private static NativeOntologyCount state(final State state) { + return new NativeOntologyCount().withState(state); + } + + /** Customers and orders, with a profile for each that covered the whole table. */ + private static World world( + final TestNamespace ns, + final String name, + final OntologyJoinStatus status, + final boolean filteredOrders, + final boolean joinOnLinkTable) { + final Ontology ontology = createOntology(ns, name); + final OntologyConcept order = declareClass(ontology, "Order", OntologyBindingFixtures.ORDER); + final OntologyConcept customer = + declareClass(ontology, "Customer", OntologyBindingFixtures.CUSTOMER); + final OntologyProperty placedBy = objectProperty(ontology, "placedBy", order, customer); + admin() + .ontologyAxioms() + .create( + assertionRequest( + ontology, + OntologyBindingFixtures.ORDER, + OntologyBindingFixtures.CUSTOMER, + "placedByAxiom") + .withPropertyIri(placedBy.getIri())); + final DatabaseSchema schema = OntologyMappingFixtures.schema(ns); + final Table customers = + table(schema, ns.prefix("customers"), column("id", ColumnDataType.BIGINT)); + final Table orders = + table( + schema, + ns.prefix("orders"), + column("id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT), + column("status", ColumnDataType.VARCHAR)); + put(admin(), customer, binding(customers, OntologyBindingRole.IDENTITY, "id"), 0L); + final var joined = + column(placedBy, "customer_id").withJoin(join(customers, status, "customer_id", "id")); + var orderBinding = + binding(orders, OntologyBindingRole.IDENTITY, "id") + .withColumns(joinOnLinkTable ? List.of() : List.of(joined)); + if (filteredOrders) { + orderBinding = + orderBinding.withRowFilter( + filter("status", OntologyRowFilterOperator.NOT_EQUALS, "DELETED")); + } + put(admin(), order, orderBinding, 0L); + Table items = null; + if (joinOnLinkTable) { + items = + table( + schema, + ns.prefix("order_items"), + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT)); + put( + admin(), + order, + binding(items, OntologyBindingRole.CONTRIBUTING, "order_id").withColumns(List.of(joined)), + 1L); + } + profile(customers, columnProfile("id", 50, 0, 50)); + profile( + orders, + columnProfile("id", 100, 0, 100), + columnProfile("customer_id", 90, 10, 40), + columnProfile("status", 100, 0, 3)); + return new World(ontology, order, customer, placedBy, schema, customers, orders, items); + } + + private static ColumnProfile columnProfile( + final String name, final double values, final double nulls, final double distinct) { + return new ColumnProfile() + .withName(name) + .withTimestamp(PROFILED_AT) + .withValuesCount(values) + .withNullCount(nulls) + .withDistinctCount(distinct); + } + + private static void profile(final Table table, final ColumnProfile... columns) { + admin() + .getHttpClient() + .execute( + HttpMethod.PUT, + "/v1/tables/" + table.getId() + "/tableProfile", + new CreateTableProfile() + .withTableProfile( + new TableProfile() + .withTimestamp(PROFILED_AT) + .withRowCount(MISLEADING_ROW_COUNT)) + .withColumnProfile(List.of(columns)), + Table.class); + } + + private static void own(final Table table, final EntityReference owner) { + final var current = admin().tables().get(table.getId().toString()); + admin().tables().update(table.getId().toString(), current.withOwners(List.of(owner))); + } + + private static EntityReference slim(final EntityReference reference) { + return reference == null + ? null + : new EntityReference() + .withId(reference.getId()) + .withType(reference.getType()) + .withFullyQualifiedName(reference.getFullyQualifiedName()); + } + + private static NativeOntologyDataGraph slim(final NativeOntologyDataGraph graph) { + return graph.withClusters(slim(graph.getClusters())).withEdges(slimEdges(graph.getEdges())); + } + + private static List slim( + final List clusters) { + clusters.forEach( + cluster -> { + cluster.withConcept(slim(cluster.getConcept())); + cluster.getAssets().forEach(asset -> asset.withAsset(slim(asset.getAsset()))); + }); + return clusters.stream() + .sorted(Comparator.comparing(cluster -> cluster.getConcept().getFullyQualifiedName())) + .toList(); + } + + private static List slimEdges( + final List edges) { + edges.forEach(edge -> edge.withProperty(slim(edge.getProperty()))); + return edges; + } + + /** What the tests built: an order class over orders, a customer class over customers. */ + private record World( + Ontology ontology, + OntologyConcept order, + OntologyConcept customer, + OntologyProperty placedBy, + DatabaseSchema schema, + Table customers, + Table orders, + Table items) { + NativeOntologyDataGraph expected( + final NativeOntologyCount orderRecords, + final NativeOntologyCount customerRecords, + final NativeOntologyCount links, + final boolean orderFacts, + final boolean customerFacts) { + return graph( + List.of( + cluster(customer, asset(customers, 0, customerFacts), customerRecords), + cluster(order, asset(orders, 1, orderFacts), orderRecords)), + links); + } + + NativeOntologyDataGraph expectedWithLinkTable( + final NativeOntologyCount orderRecords, + final NativeOntologyCount customerRecords, + final NativeOntologyCount links) { + final var orderCluster = + cluster(order, asset(orders, 0, true), orderRecords) + .withAssetCount(2) + .withAssets( + Stream.of(asset(orders, 0, true), asset(items, 1, false)) + .sorted( + Comparator.comparing( + (NativeOntologyClusterAsset one) -> + one.getAsset().getId().toString())) + .toList()); + return graph( + List.of(cluster(customer, asset(customers, 0, true), customerRecords), orderCluster), + links); + } + + NativeOntologyDataGraph expectedHidden( + final Table notes, + final NativeOntologyCount orderRecords, + final NativeOntologyCount customerRecords) { + final var noFacts = + new NativeOntologyClusterAsset().withAsset(slim(notes.getEntityReference())); + return graph( + List.of( + cluster(customer, asset(customers, 0, true), customerRecords), + cluster( + order, + noFacts.withServiceType(serviceType(notes)).withColumnCount(0), + orderRecords)), + orderRecords); + } + + private NativeOntologyDataGraph graph( + final List clusters, final NativeOntologyCount links) { + return new NativeOntologyDataGraph() + .withClusters( + clusters.stream() + .sorted(Comparator.comparing(item -> item.getConcept().getFullyQualifiedName())) + .toList()) + .withEdges( + List.of( + new NativeOntologyConceptEdge() + .withFromConceptId(order.getId()) + .withToConceptId(customer.getId()) + .withPropertyIri(placedBy.getIri()) + .withLabel("placedBy") + .withProperty(slim(placedBy.getEntityReference())) + .withLinks(links))) + .withLineageEdges(List.of()) + .withPaging(new Paging().withOffset(0).withLimit(12).withTotal(clusters.size())); + } + + private static NativeOntologyAssetCluster cluster( + final OntologyConcept concept, + final NativeOntologyClusterAsset asset, + final NativeOntologyCount records) { + return new NativeOntologyAssetCluster() + .withConcept(slim(concept.getEntityReference())) + .withAssetCount(1) + .withAssets(List.of(asset)) + .withRecords(records); + } + + private static NativeOntologyClusterAsset asset( + final Table table, final int columns, final boolean facts) { + final var asset = + new NativeOntologyClusterAsset() + .withAsset(slim(table.getEntityReference())) + .withServiceType(serviceType(table)) + .withColumnCount(columns); + return facts + ? asset + .withRowCount((long) MISLEADING_ROW_COUNT) + .withProfiledAt(PROFILED_AT) + .withSampled(false) + : asset; + } + + private static String serviceType(final Table table) { + return admin().tables().get(table.getId().toString()).getServiceType().value(); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphProfileIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphProfileIT.java new file mode 100644 index 000000000000..3be8c87f97ae --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyDataGraphProfileIT.java @@ -0,0 +1,263 @@ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.NativeOntologyPageFixtures.clusterPage; +import static org.openmetadata.it.tests.NativeOntologyPageFixtures.graphPage; +import static org.openmetadata.it.tests.OntologyBindingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyBindingFixtures.admin; +import static org.openmetadata.it.tests.OntologyBindingFixtures.bindAll; +import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.graph; +import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; +import static org.openmetadata.it.tests.OntologyBindingFixtures.tables; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.factories.DatabaseSchemaTestFactory; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateTableProfile; +import org.openmetadata.schema.api.data.NativeOntologyClusterAsset; +import org.openmetadata.schema.api.data.NativeOntologyDataGraph; +import org.openmetadata.schema.api.data.NativeOntologyDataGraphPage; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** Profile facts on the tables of {@code POST /dataGraph/pages}, and who may see them. */ +@ExtendWith(TestNamespaceExtension.class) +class NativeOntologyDataGraphProfileIT extends BaseOntologyApprovalIT { + private static final long PROFILED_AT = 1_700_000_000_000L; + private static final long ROW_COUNT = 1234L; + + @Test + void aViewableProfiledTableReturnsItsFactsAndAnUnprofiledOneReturnsNone(final TestNamespace ns) { + final var fixture = profiledFixture(ns); + for (final var assets : bothEndpoints(admin(), fixture)) { + final var sampled = assets.get(fixture.sampled().getId()); + assertEquals(ROW_COUNT, sampled.getRowCount()); + assertEquals(PROFILED_AT, sampled.getProfiledAt()); + assertTrue(sampled.getSampled()); + final var whole = assets.get(fixture.whole().getId()); + assertEquals(7L, whole.getRowCount()); + assertEquals(PROFILED_AT, whole.getProfiledAt()); + assertFalse(whole.getSampled()); + assertNoFacts(assets.get(fixture.unprofiled().getId())); + } + } + + @Test + void aReaderGetsTheFactsOfTheProfiledTableTheyOwnAndNoneOfTheOthers(final TestNamespace ns) { + final var fixture = profiledFixture(ns); + try (var fixtures = new RdfAccessFixtures("profileOwner" + ns.shortPrefix())) { + final var denied = + fixtures.denyRole(MetadataOperation.VIEW_DATA_PROFILE, Entity.TABLE, "!isOwner()"); + final OpenMetadataClient reader = + client(fixtures.userToken("owner", List.of(denied.getId()))); + ownBy(fixture.sampled(), readerReference(reader)); + for (final var assets : bothEndpoints(reader, fixture)) { + assertEquals(3, assets.size()); + final var owned = assets.get(fixture.sampled().getId()); + assertEquals(ROW_COUNT, owned.getRowCount()); + assertEquals(PROFILED_AT, owned.getProfiledAt()); + assertTrue(owned.getSampled()); + assertNoFacts(assets.get(fixture.whole().getId())); + assertNoFacts(assets.get(fixture.unprofiled().getId())); + } + } + } + + @Test + void aReaderWithoutProfileViewSeesTheTablesWithoutTheFacts(final TestNamespace ns) { + final var fixture = profiledFixture(ns); + try (var fixtures = new RdfAccessFixtures("profileDenied" + ns.shortPrefix())) { + final var denied = fixtures.denyRole(MetadataOperation.VIEW_DATA_PROFILE, Entity.TABLE); + final OpenMetadataClient reader = + client(fixtures.userToken("reader", List.of(denied.getId()))); + for (final var assets : bothEndpoints(reader, fixture)) { + assertEquals(3, assets.size()); + assets.values().forEach(NativeOntologyDataGraphProfileIT::assertNoFacts); + } + } + } + + @Test + void aBindingsPageCarriesTheFactsOfEachTableItsReaderMayProfileView(final TestNamespace ns) { + final var ontology = createOntology(ns, "bindingFacts"); + final var concept = declareClass(ontology, "Customer", CUSTOMER); + final var schema = DatabaseSchemaTestFactory.createSimple(ns).getFullyQualifiedName(); + final var all = NativeOntologyPageFixtures.sortedTables(ns, schema, 7); + bindAll(concept, all); + final Table sampled = all.get(4); + final Table whole = all.get(5); + final Table unprofiled = all.get(6); + put(sampled, profile(PROFILED_AT, (double) ROW_COUNT, 10.0)); + put(whole, profile(PROFILED_AT, 7.0, null)); + + assertBindingFacts(admin(), ontology, sampled, whole, unprofiled, true, true); + try (var fixtures = new RdfAccessFixtures("bindingProfile" + ns.shortPrefix())) { + final var ownerOnly = + fixtures.denyRole(MetadataOperation.VIEW_DATA_PROFILE, Entity.TABLE, "!isOwner()"); + final OpenMetadataClient owner = + client(fixtures.userToken("bindingOwner", List.of(ownerOnly.getId()))); + ownBy(sampled, readerReference(owner)); + assertBindingFacts(owner, ontology, sampled, whole, unprofiled, true, false); + } + try (var fixtures = new RdfAccessFixtures("bindingDenied" + ns.shortPrefix())) { + final var denied = fixtures.denyRole(MetadataOperation.VIEW_DATA_PROFILE, Entity.TABLE); + final OpenMetadataClient reader = + client(fixtures.userToken("bindingReader", List.of(denied.getId()))); + assertBindingFacts(reader, ontology, sampled, whole, unprofiled, false, false); + } + } + + @Test + void aLaterClustersPageCarriesTheFactsOfItsNewTables(final TestNamespace ns) { + final var ontology = createOntology(ns, "laterPageFacts"); + final var customer = declareClass(ontology, "Customer", CUSTOMER); + final var order = declareClass(ontology, "Order", OntologyBindingFixtures.ORDER); + final var schema = DatabaseSchemaTestFactory.createSimple(ns).getFullyQualifiedName(); + final var customers = tables(ns, schema, 2); + final var orders = tables(ns, schema, 1); + bindAll(customer, customers); + bindAll(order, orders); + put(customers.get(0), profile(PROFILED_AT, 11.0, null)); + put(orders.getFirst(), profile(PROFILED_AT, (double) ROW_COUNT, 10.0)); + + final var first = graphPage(admin(), ontology, List.of(), clusterPage(0, 1)); + final var second = + graphPage( + admin(), ontology, first.getLoaded(), clusterPage(first.getNextClusterOffset(), 1)); + + assertEquals( + List.of(customer.getId()), + first.getClusters().stream().map(cluster -> cluster.getConcept().getId()).toList()); + assertEquals( + List.of(order.getId()), + second.getClusters().stream().map(cluster -> cluster.getConcept().getId()).toList()); + final var added = second.getClusters().getFirst().getAssets().getFirst(); + assertEquals(orders.getFirst().getId(), added.getAsset().getId()); + assertEquals(ROW_COUNT, added.getRowCount()); + assertEquals(PROFILED_AT, added.getProfiledAt()); + assertTrue(added.getSampled()); + } + + /** The first page holds four tables, so the rest of the class arrives as a bindings page. */ + private static void assertBindingFacts( + final OpenMetadataClient caller, + final org.openmetadata.schema.entity.data.Ontology ontology, + final Table sampled, + final Table whole, + final Table unprofiled, + final boolean seesSampled, + final boolean seesWhole) { + final var first = graphPage(caller, ontology, List.of(), page()); + final var cluster = first.getClusters().getFirst(); + final var prefix = first.getLoaded().getFirst(); + final var next = + graphPage( + caller, + ontology, + first.getLoaded(), + NativeOntologyPageFixtures.bindingsPage(prefix, 10, cluster.getAfter())); + + final var assets = + next.getBindings().getAssets().stream() + .collect(Collectors.toMap(asset -> asset.getAssetId(), Function.identity())); + assertEquals(3, assets.size()); + final var sampledAsset = assets.get(sampled.getId()); + assertEquals(seesSampled ? ROW_COUNT : null, sampledAsset.getRowCount()); + assertEquals(seesSampled ? PROFILED_AT : null, sampledAsset.getProfiledAt()); + assertEquals(seesSampled ? Boolean.TRUE : null, sampledAsset.getSampled()); + final var wholeAsset = assets.get(whole.getId()); + assertEquals(seesWhole ? 7L : null, wholeAsset.getRowCount()); + assertEquals(seesWhole ? PROFILED_AT : null, wholeAsset.getProfiledAt()); + assertEquals(seesWhole ? Boolean.FALSE : null, wholeAsset.getSampled()); + final var bare = assets.get(unprofiled.getId()); + assertNull(bare.getRowCount()); + assertNull(bare.getProfiledAt()); + assertNull(bare.getSampled()); + } + + /** The assets of {@code POST /dataGraph/pages} and of {@code GET /dataGraph}, in that order. */ + private static List> bothEndpoints( + final OpenMetadataClient caller, final Fixture fixture) { + final NativeOntologyDataGraph graph = graph(caller, fixture.ontology(), "?limit=12"); + return List.of( + assetsById(graphPage(caller, fixture.ontology(), List.of(), page())), + graph.getClusters().stream() + .flatMap(cluster -> cluster.getAssets().stream()) + .collect(Collectors.toMap(asset -> asset.getAsset().getId(), Function.identity()))); + } + + private static void ownBy(final Table table, final EntityReference owner) { + final var current = admin().tables().get(table.getId().toString()); + admin().tables().update(table.getId().toString(), current.withOwners(List.of(owner))); + } + + private static void assertNoFacts(final NativeOntologyClusterAsset asset) { + assertNull(asset.getRowCount()); + assertNull(asset.getProfiledAt()); + assertNull(asset.getSampled()); + } + + private static Map assetsById( + final NativeOntologyDataGraphPage page) { + return page.getClusters().stream() + .flatMap(cluster -> cluster.getAssets().stream()) + .collect(Collectors.toMap(asset -> asset.getAsset().getId(), Function.identity())); + } + + private static org.openmetadata.schema.api.data.NativeOntologyGraphPageSelection page() { + return clusterPage(0, 12); + } + + private static Fixture profiledFixture(final TestNamespace ns) { + final var ontology = createOntology(ns, "profileFacts"); + final var concept = declareClass(ontology, "Customer", CUSTOMER); + final var schema = DatabaseSchemaTestFactory.createSimple(ns).getFullyQualifiedName(); + final var all = tables(ns, schema, 3); + bindAll(concept, all); + put(all.get(0), profile(PROFILED_AT - 60_000L, 5.0, null)); + put(all.get(0), profile(PROFILED_AT, (double) ROW_COUNT, 10.0)); + put(all.get(1), profile(PROFILED_AT, 7.0, null)); + return new Fixture(ontology, all.get(0), all.get(1), all.get(2)); + } + + private static TableProfile profile( + final long timestamp, final double rowCount, final Double profileSample) { + return new TableProfile() + .withTimestamp(timestamp) + .withRowCount(rowCount) + .withProfileSample(profileSample); + } + + private static void put(final Table table, final TableProfile profile) { + admin() + .getHttpClient() + .execute( + HttpMethod.PUT, + "/v1/tables/" + table.getId() + "/tableProfile", + new CreateTableProfile().withTableProfile(profile).withColumnProfile(List.of()), + Table.class); + } + + private record Fixture( + org.openmetadata.schema.entity.data.Ontology ontology, + Table sampled, + Table whole, + Table unprofiled) {} +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyGraphScanProbe.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyGraphScanProbe.java index 946790c759c1..e57da1919e16 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyGraphScanProbe.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyGraphScanProbe.java @@ -256,6 +256,8 @@ static final class ScanObservation { private static final int PAGE = 500; private final List bindingRows = new CopyOnWriteArrayList<>(); private final List axiomRows = new CopyOnWriteArrayList<>(); + private final List bindingSql = new CopyOnWriteArrayList<>(); + private final AtomicInteger selects = new AtomicInteger(); private final AtomicInteger largestInList = new AtomicInteger(); private final AtomicBoolean boundedRows = new AtomicBoolean(true); @@ -281,6 +283,16 @@ List axiomRows() { return List.copyOf(axiomRows); } + /** The lower-cased text of each binding scan statement, in the order they ran. */ + List bindingSql() { + return List.copyOf(bindingSql); + } + + /** Every SELECT statement of the observed requests. */ + int selects() { + return selects.get(); + } + int largestInList() { return largestInList.get(); } @@ -290,12 +302,16 @@ private boolean record(final StatementContext statement) { if (!sql.contains("select")) { return false; } + selects.incrementAndGet(); final var lists = IN_LIST.matcher(sql); while (lists.find()) { largestInList.accumulateAndGet(lists.group(1).split(",").length, Math::max); } final var rows = scanRows(sql); if (rows != null) { + if (rows == bindingRows) { + bindingSql.add(sql); + } boundedRows.compareAndSet(true, sql.contains(" limit ")); statement.addCleanable( () -> { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java index 6775a83dcf20..459c9b4a74de 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/NativeOntologyPartialImportPropertyIT.java @@ -1,9 +1,12 @@ package org.openmetadata.it.tests; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.net.URI; +import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; @@ -17,6 +20,7 @@ import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.data.NativeOntologyImportFormat; import org.openmetadata.schema.api.data.NativeOntologyImportItem; +import org.openmetadata.schema.api.data.NativeOntologyImportItemStatus; import org.openmetadata.schema.api.data.NativeOntologyImportPreview; import org.openmetadata.schema.api.data.PreviewNativeOntologyImport; import org.openmetadata.schema.entity.data.Ontology; @@ -24,8 +28,12 @@ import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeSetState; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.models.ListParams; +import org.openmetadata.service.ontology.NativeOntologyCsvCodec; +import org.openmetadata.service.rdf.NativeOntologyRdfImporter; /** A partial import never leaves a property whose domain or range is a concept that was not kept. */ @Execution(ExecutionMode.CONCURRENT) @@ -41,6 +49,18 @@ public class NativeOntologyPartialImportPropertyIT extends BaseOntologyApprovalI ex:owns a owl:ObjectProperty ; rdfs:label "owns" ; rdfs:domain ex:Account ; rdfs:range ex:Ledger . """; + private static final String NAMES = + """ + @prefix owl: . + @prefix rdfs: . + @prefix xsd: . + @prefix ex: . + ex:Account a owl:Class ; rdfs:label "Account" . + ex:%s a owl:DatatypeProperty ; rdfs:label "% true . + """; + @Test void anAppliedPropertyWhoseDomainConceptWasLeftOutIsRefusedNamingTheOperationAndConcept( TestNamespace ns) { @@ -94,6 +114,203 @@ void droppingThePropertyWithItsConceptOrKeepingEverythingApplies(TestNamespace n assertEquals(Set.of("owns"), propertyNames(whole)); } + @Test + void aSecondDisplayNamePropertyForAClassIsSkippedByPreviewAndRefusedOnApply(TestNamespace ns) { + final var client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "displayNames"); + final NativeOntologyImportPreview first = + client.ontologies().previewImport(ontology.getId(), names(ns, "accountName")); + apply(ns, ontology, first, first.getChangeSet().getOperations(), "firstName"); + assertEquals(Set.of("accountName"), propertyNames(ontology)); + + final NativeOntologyImportPreview second = + client.ontologies().previewImport(ontology.getId(), names(ns, "accountLabel")); + final NativeOntologyImportItem skipped = + second.getSummary().getItems().stream() + .filter(item -> item.getLabel().equals("accountLabel")) + .findFirst() + .orElseThrow(); + assertEquals(NativeOntologyImportItemStatus.SKIPPED, skipped.getStatus()); + assertTrue(skipped.getReason().contains("at most one display-name property")); + assertEquals(0, second.getChangeSet().getOperations().size()); + + final OntologyChangeOperation forged = + JsonUtils.deepCopy( + first.getChangeSet().getOperations().stream() + .filter(operation -> operation.getProperty() != null) + .findFirst() + .orElseThrow(), + OntologyChangeOperation.class); + forged.setId(UUID.randomUUID()); + forged + .getProperty() + .withId(UUID.randomUUID()) + .withName("accountLabel") + .withFullyQualifiedName(ontology.getFullyQualifiedName() + ".accountLabel") + .withIri(URI.create(forged.getProperty().getIri() + "Label")); + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> apply(ns, ontology, second, List.of(forged), "secondName")); + + assertTrue( + refusal.getMessage().contains("at most one display-name property"), refusal.getMessage()); + assertEquals(Set.of("accountName"), propertyNames(ontology)); + } + + @Test + void aCsvRowThatMakesTheFlaggedPropertyAnObjectPropertyIsPreviewedAndAppliedWithoutTheFlag( + TestNamespace ns) { + final var client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "kindChange"); + final NativeOntologyImportPreview first = + client.ontologies().previewImport(ontology.getId(), names(ns, "accountName")); + apply(ns, ontology, first, first.getChangeSet().getOperations(), "flagged"); + assertEquals(true, storedProperty(ontology, "accountName").getIsDisplayName()); + + final NativeOntologyImportPreview preview = + client + .ontologies() + .previewImport( + ontology.getId(), + csvOf( + ns, + """ + ex:Account a owl:Class ; rdfs:label "Account" . + ex:accountName a owl:ObjectProperty ; rdfs:label "accountName" ; + rdfs:domain ex:Account ; rdfs:range ex:Account . + """)); + + assertEquals(1, preview.getSummary().getCounts().getUpdatedProperties()); + assertEquals(1, preview.getChangeSet().getOperations().size()); + apply(ns, ontology, preview, preview.getChangeSet().getOperations(), "toObject"); + final OntologyProperty stored = storedProperty(ontology, "accountName"); + assertEquals(OntologyPropertyKind.OBJECT, stored.getKind()); + assertNull(stored.getIsDisplayName()); + } + + @Test + void + aCsvRowThatAddsADomainClassWithADisplayNamePropertyIsRefusedByPreviewAndAForgedUpdateIsRefusedByApply( + TestNamespace ns) { + final var client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "domainSibling"); + final String both = + """ + ex:Account a owl:Class ; rdfs:label "Account" . + ex:Ledger a owl:Class ; rdfs:label "Ledger" . + ex:accountName a owl:DatatypeProperty ; rdfs:label "accountName" ; + rdfs:domain ex:Account ; rdfs:range xsd:string ; + true . + ex:ledgerName a owl:DatatypeProperty ; rdfs:label "ledgerName" ; + rdfs:domain ex:Ledger ; rdfs:range xsd:string ; + true . + """; + final NativeOntologyImportPreview first = + client.ontologies().previewImport(ontology.getId(), turtleOf(ns, both)); + apply(ns, ontology, first, first.getChangeSet().getOperations(), "twoClasses"); + + final NativeOntologyImportPreview preview = + client + .ontologies() + .previewImport( + ontology.getId(), + csvOf( + ns, + both.replace("rdfs:domain ex:Account", "rdfs:domain ex:Account, ex:Ledger"))); + + final NativeOntologyImportItem item = + preview.getSummary().getItems().stream() + .filter(candidate -> candidate.getLabel().equals("accountName")) + .findFirst() + .orElseThrow(); + assertEquals(NativeOntologyImportItemStatus.SKIPPED, item.getStatus()); + assertTrue(item.getReason().contains("at most one display-name property"), item.getReason()); + assertEquals(0, preview.getChangeSet().getOperations().size()); + final URI account = + URI.create("https://example.org/displayNames/" + ns.shortPrefix() + "/Account"); + final URI ledger = + URI.create("https://example.org/displayNames/" + ns.shortPrefix() + "/Ledger"); + assertEquals(List.of(account), storedProperty(ontology, "accountName").getDomain()); + + final NativeOntologyImportPreview described = + client + .ontologies() + .previewImport( + ontology.getId(), + csvOf( + ns, + both.replace( + "rdfs:label \"accountName\" ;", + "rdfs:label \"accountName\" ; rdfs:comment \"The account name\" ;"))); + final OntologyChangeOperation forged = + JsonUtils.deepCopy( + described.getChangeSet().getOperations().stream() + .filter(operation -> operation.getProperty() != null) + .findFirst() + .orElseThrow(), + OntologyChangeOperation.class); + assertEquals(1, described.getChangeSet().getOperations().size()); + forged.getProperty().setDomain(List.of(account, ledger)); + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> apply(ns, ontology, described, List.of(forged), "forgedDomain")); + + assertEquals(400, refusal.getStatusCode()); + assertEquals( + "Ontology validation failed: A class has at most one display-name property, but " + + account.toString().replace("/Account", "/accountName") + + " and " + + account.toString().replace("/Account", "/ledgerName") + + " both name the same class", + refusal.getMessage()); + assertEquals(List.of(account), storedProperty(ontology, "accountName").getDomain()); + } + + private static OntologyProperty storedProperty(Ontology ontology, String name) { + final var client = SdkClients.adminClient(); + final UUID id = + client + .ontologyProperties() + .list(new ListParams().addFilter("ontology", ontology.getFullyQualifiedName())) + .getData() + .stream() + .filter(item -> item.getName().equals(name)) + .findFirst() + .orElseThrow() + .getId(); + return client.ontologyProperties().get(id); + } + + private static final String PREFIXES = + """ + @prefix owl: . + @prefix rdfs: . + @prefix xsd: . + @prefix ex: . + """; + + private static PreviewNativeOntologyImport turtleOf(TestNamespace ns, String body) { + return new PreviewNativeOntologyImport() + .withFormat(NativeOntologyImportFormat.TURTLE) + .withData(PREFIXES.formatted(ns.shortPrefix()) + body); + } + + private static PreviewNativeOntologyImport csvOf(TestNamespace ns, String body) { + return new PreviewNativeOntologyImport() + .withFormat(NativeOntologyImportFormat.CSV) + .withData( + NativeOntologyCsvCodec.write( + new NativeOntologyRdfImporter().read(turtleOf(ns, body)).document())); + } + + private static PreviewNativeOntologyImport names(TestNamespace ns, String property) { + return new PreviewNativeOntologyImport() + .withFormat(NativeOntologyImportFormat.TURTLE) + .withData(NAMES.formatted(ns.shortPrefix(), property)); + } + private static Set propertyNames(Ontology ontology) { return SdkClients.adminClient() .ontologyProperties() diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyBindingFixtures.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyBindingFixtures.java index f4417b8d1ca1..40a01b9f8b76 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyBindingFixtures.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyBindingFixtures.java @@ -73,6 +73,13 @@ static void assertStatus(final int status, final Runnable request) { assertEquals(status, assertThrows(OpenMetadataException.class, request::run).getStatusCode()); } + /** The request is refused with this status and exactly this message. */ + static void assertRefused(final int status, final String message, final Runnable request) { + final OpenMetadataException refused = assertThrows(OpenMetadataException.class, request::run); + assertEquals(message, refused.getMessage()); + assertEquals(status, refused.getStatusCode()); + } + static NativeOntologyDataGraph graph( final OpenMetadataClient client, final Ontology ontology, final String query) { return client diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetBindingIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetBindingIT.java new file mode 100644 index 000000000000..02db987a89ed --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetBindingIT.java @@ -0,0 +1,578 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.apply; +import static org.openmetadata.it.tests.OntologyDraftFixtures.assertNotFound; +import static org.openmetadata.it.tests.OntologyDraftFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; +import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.boundColumn; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.discard; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.joinTo; +import static org.openmetadata.it.tests.OntologyDraftFixtures.lease; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedDataProperty; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedShape; +import static org.openmetadata.it.tests.OntologyDraftFixtures.read; +import static org.openmetadata.it.tests.OntologyDraftFixtures.replaceOperations; +import static org.openmetadata.it.tests.OntologyDraftFixtures.workingRevision; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.conceptsBoundTo; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.join; +import static org.openmetadata.it.tests.OntologyMappingFixtures.objectProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ownedTable; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeSetState; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.type.OntologyHydratedAssetBinding; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeBasis; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.service.Entity; + +/** + * A draft that carries table bindings and shapes beside the definitions they belong to: what a + * save checks, what an apply writes and with whose rights, and when an apply is refused. One + * refusal is a case of {@code ontology/sql-value-cases.json}, the one that writes its row filter + * through a change set. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetBindingIT extends BaseOntologyApprovalIT { + private static final URI INVOICE = URI.create("urn:Invoice"); + private static final URI CUSTOMER_NAME = URI.create("urn:customerName"); + private static final int BAD_REQUEST = 400; + private static final int FORBIDDEN = 403; + private static final int PRECONDITION_FAILED = 412; + private static final String NOT_A_WHOLE_NUMBER = + "The value for column qty does not parse as INT: a whole number is written in ASCII digits," + + " with a leading minus sign when negative and no leading zeros"; + + @Test + void aDraftThatProposesAClassItsPropertyItsTableAndAShapeAppliesAsOne(final TestNamespace ns) { + final Proposal proposal = propose(ns, createOntology(ns)); + + final OntologyChangeSet applied = apply(admin(), proposal.draft()); + + assertEquals(OntologyChangeSetState.APPLIED, applied.getState()); + assertEquals(4, applied.getApplicationResult().getOperationsApplied()); + assertEquals(CUSTOMER, admin().ontologyConcepts().get(proposal.customer().getId()).getIri()); + assertEquals( + List.of(CUSTOMER), admin().ontologyProperties().get(proposal.name().getId()).getDomain()); + final var bound = bindings(admin(), proposal.customer()); + assertEquals(1L, bound.getRevision()); + final OntologyHydratedAssetBinding held = bound.getAssets().getFirst(); + assertEquals(proposal.customers().getId(), held.getAssetId()); + assertEquals(OntologyBindingRole.IDENTITY, held.getRole()); + assertEquals(List.of(List.of("id")), held.getSubjectKey()); + assertEquals(proposal.name().getId(), held.getColumns().getFirst().getPropertyId()); + assertEquals(List.of("name"), held.getColumns().getFirst().getColumnPath()); + final OntologyShape shape = admin().ontologyShapes().get(proposal.named().getId()); + assertEquals(CUSTOMER, shape.getTargetConcept()); + assertEquals(CUSTOMER_NAME, shape.getConstraints().getFirst().getPath()); + assertEquals(1, shape.getConstraints().getFirst().getMinCount()); + assertEquals(OntologyShapeBasis.OBSERVED, applied.getOperations().getLast().getBasis()); + } + + @Test + void discardingTheDraftCreatesNothing(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Proposal proposal = propose(ns, ontology); + final long revision = workingRevision(ontology); + + final OntologyChangeSet discarded = discard(admin(), proposal.draft()); + + assertEquals(OntologyChangeSetState.DISCARDED, discarded.getState()); + assertNothingWasWritten(proposal); + assertEquals(revision, workingRevision(ontology)); + } + + @Test + void aDraftBuiltBeforeAnUnrelatedEditIsStillReadAndNarrowedAndIsRefusedAtApply( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Proposal proposal = propose(ns, ontology); + declareClass(ontology, "Invoice", INVOICE); + + final List read = read(admin(), proposal.draft()).getOperations(); + final OntologyEditLeaseToken lease = lease(admin(), proposal.draft()); + final OntologyChangeSet narrowed = + replaceOperations(admin(), proposal.draft(), lease, read.subList(0, 3)); + + assertEquals(4, read.size()); + assertEquals(ids(read.subList(0, 3)), ids(narrowed.getOperations())); + assertRefused( + PRECONDITION_FAILED, + "Ontology changed since this draft was created", + () -> apply(admin(), proposal.draft(), lease)); + assertNothingWasWritten(proposal); + assertEquals(OntologyChangeSetState.DRAFT, read(admin(), proposal.draft()).getState()); + } + + @Test + void aBindingIsWrittenWithTheRightsOfTheCallerWhoAppliesAndNotOfTheAuthor( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Table invoices = table(schema(ns), "invoices", column("id", ColumnDataType.BIGINT)); + try (var fixtures = new RdfAccessFixtures("applyRights" + ns.shortPrefix())) { + final OpenMetadataClient seesNoTable = + callerWithout(fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final OntologyConcept refused = proposedClass(ontology, "Invoice", INVOICE); + final OntologyChangeSet byAdmin = + draft(admin(), ns, ontology, creates(refused), binds(bindingOf(INVOICE, invoices))); + + assertRefused(FORBIDDEN, "ViewBasic", () -> apply(seesNoTable, byAdmin)); + assertNotFound(() -> admin().ontologyConcepts().get(refused.getId())); + assertEquals(List.of(), conceptsBoundTo(admin(), invoices).getLinks()); + assertEquals(OntologyChangeSetState.DRAFT, read(admin(), byAdmin).getState()); + + final OntologyConcept written = proposedClass(ontology, "Invoice", INVOICE); + final OntologyChangeSet byCaller = + draft(seesNoTable, ns, ontology, creates(written), binds(bindingOf(INVOICE, invoices))); + + assertEquals(OntologyChangeSetState.APPLIED, apply(admin(), byCaller).getState()); + assertEquals(List.of(invoices.getId()), boundTables(written)); + } + } + + @Test + void aBindingAppliedByACallerWithoutEditAllOnTheClassIsRefusedAndNothingIsWritten( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns)); + try (var fixtures = new RdfAccessFixtures("applyClass" + ns.shortPrefix())) { + final OpenMetadataClient cannotEditClass = + callerWithout(fixtures, MetadataOperation.EDIT_ALL, Entity.ONTOLOGY_CONCEPT, null); + final OntologyChangeSet draft = draft(admin(), ns, ontology, binds(bindingOf(ORDER, orders))); + final long revision = workingRevision(ontology); + + assertRefused(FORBIDDEN, "EditAll", () -> apply(cannotEditClass, draft)); + + assertEquals(List.of(), bindings(admin(), order).getAssets()); + assertEquals(revision, workingRevision(ontology)); + assertEquals(OntologyChangeSetState.DRAFT, read(admin(), draft).getState()); + assertEquals(OntologyChangeSetState.APPLIED, apply(admin(), draft).getState()); + } + } + + @Test + void aJoinAppliedByACallerWhoMayNotViewItsTargetIsRefusedAndNothingIsWritten( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept customer = declareClass(ontology, "Customer", CUSTOMER); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final OntologyProperty placedBy = objectProperty(ontology, "placedBy", order, customer); + final DatabaseSchema schema = schema(ns); + final Table customers = table(schema, "customers", column("id", ColumnDataType.BIGINT)); + try (var fixtures = new RdfAccessFixtures("applyJoin" + ns.shortPrefix())) { + final OpenMetadataClient ownTablesOnly = + callerWithout(fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, "!isOwner()"); + final Table orders = + ownedTable( + schema, + "orders", + OntologyBindingFixtures.readerReference(ownTablesOnly), + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + binds( + bindingOf(ORDER, orders) + .withColumns( + List.of( + boundColumn(placedBy.getIri(), "customer_id") + .withJoin(joinTo(customers, "customer_id", "id")))))); + final long revision = workingRevision(ontology); + + assertRefused(FORBIDDEN, "ViewBasic", () -> apply(ownTablesOnly, draft)); + + assertEquals(List.of(), bindings(admin(), order).getAssets()); + assertEquals(revision, workingRevision(ontology)); + assertEquals(OntologyChangeSetState.DRAFT, read(admin(), draft).getState()); + assertEquals(OntologyChangeSetState.APPLIED, apply(admin(), draft).getState()); + } + } + + @Test + void aRowFilterAppliedByACallerWithoutViewSampleDataIsRefusedAsItsCaseExpects( + final TestNamespace ns) { + final JsonNode json = caseWrittenThroughAChangeSet(); + final OntologyRowFilter rowFilter = rowFilterOf(json); + final Ontology ontology = createOntology(ns); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final Table people = + table( + schema(ns), + "people", + column( + rowFilter.getColumn().getFirst(), + ColumnDataType.fromValue(json.get("columnType").asText()))); + try (var fixtures = new RdfAccessFixtures("applyFilter" + ns.shortPrefix())) { + final OpenMetadataClient seesNoSample = + callerWithout(fixtures, MetadataOperation.VIEW_SAMPLE_DATA, Entity.TABLE, null); + final OntologyChangeSet draft = + draft(admin(), ns, ontology, binds(bindingOf(ORDER, people).withRowFilter(rowFilter))); + + final OpenMetadataException refusal = + assertThrows(OpenMetadataException.class, () -> apply(seesNoSample, draft)); + + assertEquals( + json.at("/expectedOutcome/status").asInt(), refusal.getStatusCode(), refusal::getMessage); + json.at("/expectedOutcome/messageContains") + .forEach( + part -> + assertTrue(refusal.getMessage().contains(part.asText()), refusal::getMessage)); + assertEquals(List.of(), bindings(admin(), order).getAssets()); + assertEquals(OntologyChangeSetState.APPLIED, apply(admin(), draft).getState()); + assertEquals(rowFilter, bindings(admin(), order).getAssets().getFirst().getRowFilter()); + } + } + + @Test + void aRowFilterValueThatDoesNotParseAsTheTypeOfItsColumnIsRefusedAtApply(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final Table orders = table(schema(ns), "orders", column("qty", ColumnDataType.INT)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + binds( + bindingOf(ORDER, orders) + .withRowFilter(filter("qty", OntologyRowFilterOperator.EQUALS, "abc")))); + + assertRefused(BAD_REQUEST, NOT_A_WHOLE_NUMBER, () -> apply(admin(), draft)); + + assertEquals(List.of(), bindings(admin(), order).getAssets()); + assertEquals(OntologyChangeSetState.DRAFT, read(admin(), draft).getState()); + } + + @Test + void aJoinThatAnOperationWritesIsStoredAsInferredEvenAfterAPersonConfirmedIt( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept customer = declareClass(ontology, "Customer", CUSTOMER); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final DatabaseSchema schema = schema(ns); + final Table customers = table(schema, "customers", column("id", ColumnDataType.BIGINT)); + final Table orders = orders(schema); + final OntologyProperty placedBy = objectProperty(ontology, "placedBy", order, customer); + final OntologyBindingChange joined = + bindingOf(ORDER, orders) + .withColumns( + List.of( + boundColumn(placedBy.getIri(), "customer_id") + .withJoin(joinTo(customers, "customer_id", "id")))); + + apply(admin(), draft(admin(), ns, ontology, binds(joined))); + + assertEquals(customers.getId(), storedJoin(order).getTargetAssetId()); + assertEquals(OntologyJoinStatus.INFERRED, storedJoin(order).getStatus()); + final OntologyColumnBinding confirmed = + column(placedBy, "customer_id") + .withJoin(join(customers, OntologyJoinStatus.CONFIRMED, "customer_id", "id")); + put(admin(), order, binding(orders).withColumns(List.of(confirmed)), 1L); + assertEquals(OntologyJoinStatus.CONFIRMED, storedJoin(order).getStatus()); + + apply(admin(), draft(admin(), ns, ontology, binds(joined).withBaseVersion(2.0))); + + assertEquals(OntologyJoinStatus.INFERRED, storedJoin(order).getStatus()); + assertEquals(3L, bindings(admin(), order).getRevision()); + } + + @Test + void aBindingOperationBuiltAgainstAnEarlierBindingRevisionIsRefusedAndAppliesOnceRebuilt( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns)); + put(admin(), order, binding(orders), 0L); + final OntologyChangeOperation keyed = + binds(keyed(orders, OntologyBindingRole.IDENTITY)).withBaseVersion(1.0); + final OntologyChangeSet draft = draft(admin(), ns, ontology, keyed); + put(admin(), order, binding(orders, OntologyBindingRole.CONTRIBUTING, "order_id"), 1L); + + assertRefused( + PRECONDITION_FAILED, + "The binding of class urn:Order to table " + + orders.getId() + + " changed since operation '" + + keyed.getId() + + "' was built: the operation carries binding revision 1 and the class is at binding" + + " revision 2", + () -> apply(admin(), draft)); + assertEquals( + OntologyBindingRole.CONTRIBUTING, + bindings(admin(), order).getAssets().getFirst().getRole()); + assertEquals(OntologyChangeSetState.DRAFT, read(admin(), draft).getState()); + + final OntologyEditLeaseToken lease = lease(admin(), draft); + replaceOperations(admin(), draft, lease, List.of(keyed.withBaseVersion(2.0))); + + assertEquals(OntologyChangeSetState.APPLIED, apply(admin(), draft, lease).getState()); + assertEquals(3L, bindings(admin(), order).getRevision()); + assertEquals( + OntologyBindingRole.IDENTITY, bindings(admin(), order).getAssets().getFirst().getRole()); + } + + @Test + void aBindingOperationBuiltWhenItsTableWasNotBoundIsRefusedOnceTheTableIsBound( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns)); + final OntologyChangeOperation keyed = binds(keyed(orders, OntologyBindingRole.IDENTITY)); + final OntologyChangeSet draft = draft(admin(), ns, ontology, keyed); + put(admin(), order, binding(orders), 0L); + + assertRefused( + PRECONDITION_FAILED, + "The binding of class urn:Order to table " + + orders.getId() + + " changed since operation '" + + keyed.getId() + + "' was built: the operation carries no binding revision and the class is at binding" + + " revision 1", + () -> apply(admin(), draft)); + assertEquals(1L, bindings(admin(), order).getRevision()); + } + + @Test + void aDraftChangesTwoBindingsOfOneClassThatItReadAtOneRevision(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final DatabaseSchema schema = schema(ns); + final Table orders = orders(schema); + final Table archive = + table(schema, "orders_archive", column("order_id", ColumnDataType.BIGINT)); + put(admin(), order, binding(orders), 0L); + put(admin(), order, binding(archive), 1L); + + final OntologyChangeSet applied = + apply( + admin(), + draft( + admin(), + ns, + ontology, + binds(keyed(orders, OntologyBindingRole.IDENTITY)).withBaseVersion(2.0), + binds(keyed(archive, OntologyBindingRole.CONTRIBUTING)).withBaseVersion(2.0))); + + assertEquals(OntologyChangeSetState.APPLIED, applied.getState()); + final var bound = bindings(admin(), order); + assertEquals(4L, bound.getRevision()); + assertEquals(OntologyBindingRole.IDENTITY, roleOf(bound.getAssets(), orders)); + assertEquals(OntologyBindingRole.CONTRIBUTING, roleOf(bound.getAssets(), archive)); + } + + @Test + void aSaveRefusesABindingOrAShapeThatNamesWhatDoesNotExist(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns)); + final UUID noTable = UUID.randomUUID(); + + assertRefused( + BAD_REQUEST, + "names the table " + noTable + ", which does not exist", + () -> + draft( + admin(), + ns, + ontology, + binds(new OntologyBindingChange().withClassIri(ORDER).withTableId(noTable)))); + assertRefused( + BAD_REQUEST, + "names the column missing, which table " + orders.getId() + " does not have", + () -> + draft( + admin(), + ns, + ontology, + binds( + bindingOf(ORDER, orders) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of("missing")))))); + assertRefused( + BAD_REQUEST, + "needs the class urn:Invoice, which the ontology does not declare and no earlier" + + " operation creates", + () -> + draft( + admin(), + ns, + ontology, + binds(bindingOf(INVOICE, orders)), + creates(proposedClass(ontology, "Invoice", INVOICE)))); + + final OntologyChangeSet draft = draft(admin(), ns, ontology, binds(bindingOf(ORDER, orders))); + final OntologyShape paid = proposedShape(ontology, "PaidInvoice", INVOICE, CUSTOMER_NAME); + assertRefused( + BAD_REQUEST, + "needs the class urn:Invoice, which the ontology does not declare and no earlier" + + " operation creates", + () -> replaceOperations(admin(), draft, lease(admin(), draft), List.of(creates(paid)))); + assertEquals(1, read(admin(), draft).getOperations().size()); + } + + /** A draft that proposes a class with the property, the table and the shape that belong to it. */ + private record Proposal( + Table customers, + OntologyConcept customer, + OntologyProperty name, + OntologyShape named, + OntologyChangeSet draft) {} + + private static Proposal propose(final TestNamespace ns, final Ontology ontology) { + final Table customers = + table( + schema(ns), + "customers", + column("id", ColumnDataType.BIGINT), + column("name", ColumnDataType.VARCHAR)); + final OntologyConcept customer = proposedClass(ontology, "Customer", CUSTOMER); + final OntologyProperty name = + proposedDataProperty(ontology, "customerName", CUSTOMER_NAME, CUSTOMER); + final OntologyShape named = proposedShape(ontology, "NamedCustomer", CUSTOMER, CUSTOMER_NAME); + final OntologyBindingChange held = + bindingOf(CUSTOMER, customers) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of("id"))) + .withColumns(List.of(boundColumn(CUSTOMER_NAME, "name"))); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + creates(customer), + creates(name), + binds(held).withRequiresConceptIris(List.of(CUSTOMER)), + creates(named) + .withBasis(OntologyShapeBasis.OBSERVED) + .withRequiresConceptIris(List.of(CUSTOMER))); + return new Proposal(customers, customer, name, named, draft); + } + + private static void assertNothingWasWritten(final Proposal proposal) { + assertNotFound(() -> admin().ontologyConcepts().get(proposal.customer().getId())); + assertNotFound(() -> admin().ontologyProperties().get(proposal.name().getId())); + assertNotFound(() -> admin().ontologyShapes().get(proposal.named().getId())); + assertEquals(List.of(), conceptsBoundTo(admin(), proposal.customers()).getLinks()); + } + + private static Table orders(final DatabaseSchema schema) { + return table( + schema, + "orders", + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT)); + } + + /** A binding of {@code table} to the order class, keyed by the order id. */ + private static OntologyBindingChange keyed(final Table table, final OntologyBindingRole role) { + return bindingOf(ORDER, table).withRole(role).withSubjectKey(List.of(List.of("order_id"))); + } + + private static List ids(final List operations) { + return operations.stream().map(OntologyChangeOperation::getId).toList(); + } + + private static OntologyBindingRole roleOf( + final List assets, final Table table) { + return assets.stream() + .filter(asset -> table.getId().equals(asset.getAssetId())) + .findFirst() + .orElseThrow() + .getRole(); + } + + private static List boundTables(final OntologyConcept concept) { + return bindings(admin(), concept).getAssets().stream() + .map(OntologyHydratedAssetBinding::getAssetId) + .toList(); + } + + /** The join of the one column the order class binds. */ + private static OntologyColumnJoin storedJoin(final OntologyConcept order) { + return bindings(admin(), order).getAssets().getFirst().getColumns().getFirst().getJoin(); + } + + /** The one case of the file whose row filter is written by applying a change set. */ + private static JsonNode caseWrittenThroughAChangeSet() { + final List cases = + OntologySqlValueCases.withOutcome("refusedAtSave").stream() + .filter(json -> "changeSet".equals(json.at("/input/via").asText())) + .toList(); + assertEquals(List.of("PRB-005"), cases.stream().map(json -> json.get("id").asText()).toList()); + assertEquals(FORBIDDEN, cases.getFirst().at("/expectedOutcome/status").asInt()); + assertEquals( + "ViewSampleData", cases.getFirst().at("/expectedOutcome/messageContains/0").asText()); + return cases.getFirst(); + } + + /** The row filter a case carries beside the path that writes it. */ + private static OntologyRowFilter rowFilterOf(final JsonNode json) { + final ObjectNode input = json.get("input").deepCopy(); + input.remove("via"); + return JsonUtils.getObjectMapper().convertValue(input, OntologyRowFilter.class); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetCommandReadIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetCommandReadIT.java new file mode 100644 index 000000000000..7e379ee1140a --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetCommandReadIT.java @@ -0,0 +1,335 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.CHANGE_SETS; +import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; +import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.lease; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.AcquireOntologyEditLock; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * Every endpoint that acts on one change set asks the draft read right, which is edit on the + * ontology it targets. An editor of change sets with no right on the ontology is refused before + * anything is written or answered, and a viewer reads no snapshot of the draft from the history. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetCommandReadIT extends BaseOntologyApprovalIT { + private static final String COLUMN = "command_read_column"; + private static final String VALUE = "command_read_value"; + private static final String LEASES = "/v1/ontologyEditLocks"; + private static final int FORBIDDEN = 403; + + private record Scene( + OntologyChangeSet draft, + Table table, + OpenMetadataClient author, + OpenMetadataClient editor, + OpenMetadataClient viewer, + OntologyEditLeaseToken authorLease, + long startedAt) { + String path() { + return CHANGE_SETS + "/" + draft.getId(); + } + + Map asAuthor() { + return Map.of("lease", authorLease); + } + + void assertNoSecretIn(final String body) { + assertFalse(body.contains(table.getId().toString()), body); + assertFalse(body.contains(COLUMN), body); + assertFalse(body.contains(VALUE), body); + } + } + + @Test + void aViewerOfChangeSetsReadsNoSnapshotOfTheDraftFromTheHistory(final TestNamespace ns) { + try (var authors = new RdfAccessFixtures("cmdHist" + ns.shortPrefix()); + var others = new RdfAccessFixtures("cmdHistOther" + ns.shortPrefix())) { + final Scene scene = scene(ns, authors, others); + send(scene.author(), HttpMethod.POST, scene.path() + "/undo", scene.asAuthor()); + send(scene.author(), HttpMethod.POST, scene.path() + "/redo", scene.asAuthor()); + final String history = + CHANGE_SETS + "/history?limit=500&startTs=" + scene.startedAt() + "&endTs=" + later(); + final String id = scene.draft().getId().toString(); + + final String viewed = send(scene.viewer(), HttpMethod.GET, history, null); + + assertFalse(viewed.contains(id), viewed); + scene.assertNoSecretIn(viewed); + for (final OpenMetadataClient reader : List.of(scene.author(), admin())) { + final String read = send(reader, HttpMethod.GET, history, null); + assertTrue(read.contains(id), read); + assertTrue(read.contains(scene.table().getId().toString()), read); + } + } + } + + @Test + void anEditorWithoutTheOntologyEditRightIsRefusedEveryCommandAndNothingChanges( + final TestNamespace ns) { + try (var authors = new RdfAccessFixtures("cmdEdit" + ns.shortPrefix()); + var others = new RdfAccessFixtures("cmdEditOther" + ns.shortPrefix())) { + final Scene scene = scene(ns, authors, others); + final String refusal = refusalOfRead(scene); + final JsonNode operations = stored(scene).path("operations"); + final Map replacement = + Map.of("lease", scene.authorLease(), "operations", operations, "undoCursor", 1); + final Map removal = + Map.of("lease", scene.authorLease(), "operations", List.of(), "undoCursor", 0); + final JsonNode before = stored(scene); + + for (final Attempt attempt : + List.of( + new Attempt("undo", HttpMethod.POST, scene.path() + "/undo", scene.asAuthor()), + new Attempt("redo", HttpMethod.POST, scene.path() + "/redo", scene.asAuthor()), + new Attempt("discard", HttpMethod.POST, scene.path() + "/discard", scene.asAuthor()), + new Attempt("replace", HttpMethod.PUT, scene.path() + "/operations", replacement), + new Attempt("replace none", HttpMethod.PUT, scene.path() + "/operations", removal), + new Attempt( + "soft delete", HttpMethod.DELETE, scene.path() + "?hardDelete=false", null), + new Attempt( + "hard delete", HttpMethod.DELETE, scene.path() + "?hardDelete=true", null), + new Attempt( + "restore", + HttpMethod.PUT, + CHANGE_SETS + "/restore", + Map.of("id", scene.draft().getId().toString())))) { + assertRefusedLikeTheRead(scene, attempt, refusal); + assertEquals(before, stored(scene), attempt.label()); + } + } + } + + @Test + void anEditorCannotTakeReadOrReleaseTheLeaseOfADraftItMayNotRead(final TestNamespace ns) { + try (var authors = new RdfAccessFixtures("cmdLease" + ns.shortPrefix()); + var others = new RdfAccessFixtures("cmdLeaseOther" + ns.shortPrefix())) { + final Scene scene = scene(ns, authors, others); + final String refusal = refusalOfRead(scene); + final String lease = LEASES + "/" + Entity.ONTOLOGY_CHANGE_SET + "/" + scene.draft().getId(); + final Object request = + new AcquireOntologyEditLock() + .withResourceType(Entity.ONTOLOGY_CHANGE_SET) + .withResourceId(scene.draft().getId()) + .withSessionId(UUID.randomUUID().toString()) + .withLeaseSeconds(60); + final String held = send(scene.author(), HttpMethod.GET, lease, null); + + for (final Attempt attempt : + List.of( + new Attempt("acquire", HttpMethod.POST, LEASES + "/acquire", request), + new Attempt("renew", HttpMethod.PUT, LEASES + "/renew", request), + new Attempt("get", HttpMethod.GET, lease, null), + new Attempt( + "release", + HttpMethod.DELETE, + lease + "?sessionId=" + scene.authorLease().getSessionId(), + null))) { + assertRefusedLikeTheRead(scene, attempt, refusal); + } + + assertEquals(held, send(scene.author(), HttpMethod.GET, lease, null)); + assertEquals( + scene.authorLease().getSessionId(), JsonUtils.readTree(held).path("sessionId").asText()); + } + } + + @Test + void theAuthorCanStillRunEveryCommandAndTheDraftAnswersWithItsOperations(final TestNamespace ns) { + try (var authors = new RdfAccessFixtures("cmdAuthor" + ns.shortPrefix()); + var others = new RdfAccessFixtures("cmdAuthorOther" + ns.shortPrefix())) { + final Scene scene = scene(ns, authors, others); + final JsonNode operations = stored(scene).path("operations"); + + for (final String command : List.of("/undo", "/redo")) { + final String answer = + send(scene.author(), HttpMethod.POST, scene.path() + command, scene.asAuthor()); + assertTrue(answer.contains(scene.table().getId().toString()), command); + } + final String replaced = + send( + scene.author(), + HttpMethod.PUT, + scene.path() + "/operations", + Map.of("lease", scene.authorLease(), "operations", operations, "undoCursor", 1)); + assertTrue(replaced.contains(scene.table().getId().toString())); + final String discarded = + send(scene.author(), HttpMethod.POST, scene.path() + "/discard", scene.asAuthor()); + assertEquals("DISCARDED", JsonUtils.readTree(discarded).path("state").asText()); + assertTrue(discarded.contains(scene.table().getId().toString())); + } + } + + @Test + void theAuthorCanStillReplaceWithNoOperationsAndDeleteAndRestoreTheDraft(final TestNamespace ns) { + try (var authors = new RdfAccessFixtures("cmdDelete" + ns.shortPrefix()); + var others = new RdfAccessFixtures("cmdDeleteOther" + ns.shortPrefix())) { + final Scene scene = scene(ns, authors, others); + + send( + scene.author(), + HttpMethod.PUT, + scene.path() + "/operations", + Map.of("lease", scene.authorLease(), "operations", List.of(), "undoCursor", 0)); + final String afterReplace = + send(admin(), HttpMethod.GET, scene.path() + "?fields=operations", null); + assertEquals(0, JsonUtils.readTree(afterReplace).path("operations").size()); + // The binding still shows in the draft's recorded change, as the value the save removed, + // which + // is how a replace with no operations can look as if it left the binding in place. + assertTrue(afterReplace.contains(COLUMN)); + assertEquals( + "operations", + JsonUtils.readTree(afterReplace) + .path("changeDescription") + .path("fieldsUpdated") + .get(0) + .path("name") + .asText()); + final String softDeleted = + send(scene.author(), HttpMethod.DELETE, scene.path() + "?hardDelete=false", null); + assertTrue(JsonUtils.readTree(softDeleted).path("deleted").asBoolean()); + final String restored = + send( + scene.author(), + HttpMethod.PUT, + CHANGE_SETS + "/restore", + Map.of("id", scene.draft().getId().toString())); + assertFalse(JsonUtils.readTree(restored).path("deleted").asBoolean()); + send(scene.author(), HttpMethod.DELETE, scene.path() + "?hardDelete=true", null); + assertEquals( + 404, + assertThrows( + OpenMetadataException.class, + () -> send(admin(), HttpMethod.GET, scene.path(), null)) + .getStatusCode()); + } + } + + private record Attempt(String label, HttpMethod method, String path, Object body) {} + + private static String refusalOfRead(final Scene scene) { + final OpenMetadataException read = + assertThrows( + OpenMetadataException.class, + () -> send(scene.editor(), HttpMethod.GET, scene.path(), null)); + assertEquals(FORBIDDEN, read.getStatusCode()); + return read.getMessage(); + } + + /** + * The editor holds the author's lease token, so a command that skipped the read right would meet + * a different refusal, and one that skipped the lease check would write. + */ + private static void assertRefusedLikeTheRead( + final Scene scene, final Attempt attempt, final String readRefusal) { + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> send(scene.editor(), attempt.method(), attempt.path(), attempt.body()), + attempt.label()); + assertEquals(FORBIDDEN, refused.getStatusCode(), attempt.label()); + assertEquals(readRefusal, refused.getMessage(), attempt.label()); + scene.assertNoSecretIn(refused.getMessage()); + } + + /** What an admin reads of the draft, with the version, the deleted flag and the operations. */ + private static JsonNode stored(final Scene scene) { + return JsonUtils.readTree( + send(admin(), HttpMethod.GET, scene.path() + "?fields=operations&include=all", null)); + } + + private static Scene scene( + final TestNamespace ns, final RdfAccessFixtures authors, final RdfAccessFixtures others) { + final long startedAt = System.currentTimeMillis() - 1000; + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final OpenMetadataClient author = + callerWithout(authors, MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final var edit = others.allowRole(MetadataOperation.EDIT_ALL, Entity.ONTOLOGY_CHANGE_SET); + final var remove = others.allowRole(MetadataOperation.DELETE, Entity.ONTOLOGY_CHANGE_SET); + final var viewAll = others.allowRole(MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_CHANGE_SET); + final var viewBasic = + others.allowRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CHANGE_SET); + final var noTables = others.denyRole(MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final OpenMetadataClient editor = + OntologyBindingFixtures.client( + others.userToken("editor", List.of(edit.getId(), remove.getId(), noTables.getId()))); + final OpenMetadataClient viewer = + OntologyBindingFixtures.client( + others.userToken( + "viewer", List.of(viewAll.getId(), viewBasic.getId(), noTables.getId()))); + final Table table = table(schema(ns), "hidden", column(COLUMN, ColumnDataType.VARCHAR)); + final OntologyChangeSet draft = + draft( + author, + ns, + ontology, + binds( + bindingOf(ORDER, table) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of(COLUMN))) + .withRowFilter(filter(COLUMN, OntologyRowFilterOperator.EQUALS, VALUE)))); + return new Scene(draft, table, author, editor, viewer, lease(author, draft), startedAt); + } + + private static long later() { + return System.currentTimeMillis() + 60_000; + } + + private static String send( + final OpenMetadataClient caller, + final HttpMethod method, + final String path, + final Object body) { + return caller.getHttpClient().executeForString(method, path, body); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadIT.java new file mode 100644 index 000000000000..bcbe402f26e0 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadIT.java @@ -0,0 +1,272 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.CHANGE_SETS; +import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; +import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyDraftFixtures.workingRevision; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyChangeSet; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * The audit log of a change set holds its operations, so it is read with the right that reads the + * draft: edit on the ontology the change set targets. View rights on change sets and on the table + * are not enough, and a deleted change set leaves only the audit-log permission. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetDraftReadIT extends BaseOntologyApprovalIT { + private static final String COLUMN = "draft_read_column"; + private static final String VALUE = "draft_read_value"; + private static final String AUDIT = "/v1/audit/logs?limit=50&entityType=ontologyChangeSet"; + private static final int FORBIDDEN = 403; + + private record Scene( + OntologyChangeSet draft, Table table, OpenMetadataClient author, OpenMetadataClient viewer) { + String fqn() { + return draft.getFullyQualifiedName(); + } + + void assertNoSecretIn(final String body) { + assertFalse(body.contains(table.getId().toString()), body); + assertFalse(body.contains(COLUMN), body); + assertFalse(body.contains(VALUE), body); + } + } + + @Test + void aUserWhoMayOnlyViewChangeSetsIsRefusedItsAuditLogAndTheEditorsAndAdminAreNot( + final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("auditRead" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("auditReadViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + awaitCreated(scene); + + final OpenMetadataException refusal = + assertThrows(OpenMetadataException.class, () -> audit(scene.viewer(), scene.fqn())); + + assertEquals(FORBIDDEN, refusal.getStatusCode()); + scene.assertNoSecretIn(refusal.getMessage()); + assertReadsTheEventsOnly(audit(scene.author(), scene.fqn()), scene); + assertReadsTheEventsOnly(audit(admin(), scene.fqn()), scene); + } + } + + @Test + void aSoftDeletedChangeSetIsStillCheckedAgainstTheDraftReadRight(final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("auditSoft" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("auditSoftViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + awaitCreated(scene); + delete(scene, false); + + final OpenMetadataException refusal = + assertThrows(OpenMetadataException.class, () -> audit(scene.viewer(), scene.fqn())); + + assertEquals(FORBIDDEN, refusal.getStatusCode()); + scene.assertNoSecretIn(refusal.getMessage()); + assertReadsTheEventsOnly(audit(scene.author(), scene.fqn()), scene); + assertReadsTheEventsOnly(audit(admin(), scene.fqn()), scene); + } + } + + @Test + void aHardDeletedChangeSetLeavesOnlyTheAuditLogPermission(final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("auditHard" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("auditHardViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + awaitCreated(scene); + delete(scene, true); + + final OpenMetadataException refusal = + assertThrows(OpenMetadataException.class, () -> audit(scene.viewer(), scene.fqn())); + assertEquals(FORBIDDEN, refusal.getStatusCode()); + scene.assertNoSecretIn(refusal.getMessage()); + assertReadsTheEventsOnly(audit(admin(), scene.fqn()), scene); + } + } + + @Test + void theServiceNamePathIsNotAWayRoundTheDraftReadRight(final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("auditService" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("auditServiceViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + awaitCreated(scene); + + for (final String serviceName : List.of(scene.fqn(), scene.draft().getName())) { + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> get(scene.viewer(), AUDIT + "&serviceName=" + serviceName)); + assertEquals(FORBIDDEN, refusal.getStatusCode(), serviceName); + scene.assertNoSecretIn(refusal.getMessage()); + } + assertReadsTheEventsOnly(get(scene.author(), AUDIT + "&serviceName=" + scene.fqn()), scene); + } + } + + @Test + void aNameFreedByAHardDeleteDoesNotOpenTheRowsOfTheDeletedDraft(final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("auditReuse" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("auditReuseViewer" + ns.shortPrefix()); + var reusers = new RdfAccessFixtures("auditReuseUser" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + awaitCreated(scene); + delete(scene, true); + final var create = reusers.allowRole(MetadataOperation.CREATE, Entity.ONTOLOGY_CHANGE_SET); + final var noTables = reusers.denyRole(MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final OpenMetadataClient reuser = + OntologyBindingFixtures.client( + reusers.userToken("reuser", List.of(create.getId(), noTables.getId()))); + final User me = JsonUtils.readValue(get(reuser, "/v1/users/loggedInUser"), User.class); + final Ontology second = + admin() + .ontologies() + .create( + request(ns) + .withName(ns.prefix("auditReuseSecond")) + .withIri(URI.create("https://example.org/model/" + ns.shortPrefix() + "r")) + .withOwners(List.of(me.getEntityReference()))); + ns.trackRoot("ontology", second); + + final OntologyChangeSet reused = + ns.trackRoot( + "ontologyChangeSet", + reuser + .ontologyChangeSets() + .create( + new CreateOntologyChangeSet() + .withName(scene.draft().getName()) + .withDisplayName("Reused name") + .withDescription("A draft that takes a name the first one freed") + .withOntology(second.getFullyQualifiedName()) + .withBaseWorkingRevision(workingRevision(second)) + .withOperations( + List.of(creates(proposedClass(second, "Customer", CUSTOMER)))))); + Awaitility.await("the audit events of both drafts") + .atMost(Duration.ofSeconds(60)) + .until(() -> entityIds(audit(admin(), scene.fqn())).size() == 2); + + assertEquals(Set.of(reused.getId().toString()), entityIds(audit(reuser, scene.fqn()))); + assertEquals( + Set.of(reused.getId().toString()), + entityIds(get(reuser, AUDIT + "&serviceName=" + scene.fqn()))); + assertEquals( + Set.of(scene.draft().getId().toString(), reused.getId().toString()), + entityIds(audit(admin(), scene.fqn()))); + scene.assertNoSecretIn(audit(reuser, scene.fqn())); + } + } + + private static Set entityIds(final String auditBody) { + return JsonUtils.readTree(auditBody).path("data").findValuesAsText("entityId").stream() + .collect(Collectors.toSet()); + } + + /** The audit rows are readable, and no row of a change set holds its operations. */ + private static void assertReadsTheEventsOnly(final String body, final Scene scene) { + assertTrue(body.contains("entityCreated"), body); + scene.assertNoSecretIn(body); + assertFalse(body.contains("operations"), body); + } + + private static Scene scene( + final TestNamespace ns, final RdfAccessFixtures fixtures, final RdfAccessFixtures viewers) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final OpenMetadataClient author = + callerWithout(fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final var viewAll = viewers.allowRole(MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_CHANGE_SET); + final var viewBasic = + viewers.allowRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CHANGE_SET); + final var noTables = viewers.denyRole(MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final OpenMetadataClient viewer = + OntologyBindingFixtures.client( + viewers.userToken( + "viewer", List.of(viewAll.getId(), viewBasic.getId(), noTables.getId()))); + final Table table = table(schema(ns), "hidden", column(COLUMN, ColumnDataType.VARCHAR)); + final OntologyChangeSet draft = + draft( + author, + ns, + ontology, + binds( + bindingOf(ORDER, table) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of(COLUMN))) + .withRowFilter(filter(COLUMN, OntologyRowFilterOperator.EQUALS, VALUE)))); + return new Scene(draft, table, author, viewer); + } + + private static void awaitCreated(final Scene scene) { + Awaitility.await("the audit event of the draft") + .atMost(Duration.ofSeconds(60)) + .until(() -> audit(admin(), scene.fqn()).contains("entityCreated")); + } + + private static void delete(final Scene scene, final boolean hard) { + admin() + .getHttpClient() + .executeForString( + HttpMethod.DELETE, + CHANGE_SETS + "/" + scene.draft().getId() + "?hardDelete=" + hard, + null); + } + + private static String audit(final OpenMetadataClient caller, final String fqn) { + return get(caller, AUDIT + "&entityFQN=" + fqn); + } + + private static String get(final OpenMetadataClient caller, final String path) { + return caller.getHttpClient().executeForString(HttpMethod.GET, path, null); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadMcpIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadMcpIT.java new file mode 100644 index 000000000000..136c0319b40a --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetDraftReadMcpIT.java @@ -0,0 +1,201 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.CHANGE_SETS; +import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; +import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.tests.mcp.McpTestBase; +import org.openmetadata.it.tests.mcp.McpTestUtils; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * get_entity_details reads a change set with the right that reads its draft, as REST does, in every + * call shape. A user with view rights on change sets and none on the ontology is refused, and the + * answer holds no table id, column or filter value of a binding operation. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetDraftReadMcpIT extends McpTestBase { + private static final String BEARER = "Bearer "; + private static final String COLUMN = "draft_read_column"; + private static final String VALUE = "draft_read_value"; + private static final String NOT_ALLOWED = "not allowed"; + + private record Scene(OntologyChangeSet draft, Table table, String editor, String viewer) { + String fqn() { + return draft.getFullyQualifiedName(); + } + + void assertRefused(final String call, final JsonNode answer) { + final String text = answer.toString(); + assertTrue(text.contains(NOT_ALLOWED), call + ": " + text); + assertFalse(text.contains(table.getId().toString()), call + ": " + text); + assertFalse(text.contains(COLUMN), call + ": " + text); + assertFalse(text.contains(VALUE), call + ": " + text); + } + + void assertAnswered(final String call, final JsonNode answer) { + final String text = answer.toString(); + assertFalse(text.contains(NOT_ALLOWED), call + ": " + text); + assertTrue(text.contains(table.getId().toString()), call + ": " + text); + } + } + + @Test + void aUserWhoMayOnlyViewChangeSetsIsRefusedInEveryCallShape(final TestNamespace ns) + throws Exception { + initAuth(); + try (var fixtures = new RdfAccessFixtures("mcpDraft" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("mcpDraftViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + + for (final var call : calls(scene).entrySet()) { + scene.assertRefused(call.getKey(), executeMcpRequest(call.getValue(), scene.viewer())); + } + } + } + + @Test + void theEditorAndAnAdminReadTheSameChangeSetInEveryCallShape(final TestNamespace ns) + throws Exception { + initAuth(); + try (var fixtures = new RdfAccessFixtures("mcpDraftEditor" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("mcpDraftEditorViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + + for (final var call : calls(scene).entrySet()) { + if (!call.getKey().startsWith("content")) { + scene.assertAnswered( + call.getKey() + " editor", executeMcpRequest(call.getValue(), scene.editor())); + scene.assertAnswered( + call.getKey() + " admin", executeMcpRequest(call.getValue(), authToken)); + } + } + } + } + + @Test + void aDeletedChangeSetIsRefusedOrMissingAndNeverReadByAViewer(final TestNamespace ns) + throws Exception { + initAuth(); + try (var fixtures = new RdfAccessFixtures("mcpDraftGone" + ns.shortPrefix()); + var viewers = new RdfAccessFixtures("mcpDraftGoneViewer" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, viewers); + final Map call = calls(scene).get("single"); + admin() + .getHttpClient() + .executeForString( + HttpMethod.DELETE, + CHANGE_SETS + "/" + scene.draft().getId() + "?hardDelete=false", + null); + + scene.assertRefused("soft deleted", executeMcpRequest(call, scene.viewer())); + + admin() + .getHttpClient() + .executeForString( + HttpMethod.DELETE, + CHANGE_SETS + "/" + scene.draft().getId() + "?hardDelete=true", + null); + final String gone = executeMcpRequest(call, scene.viewer()).toString(); + assertFalse(gone.contains(scene.table().getId().toString()), gone); + assertFalse(gone.contains(COLUMN), gone); + assertFalse(gone.contains(VALUE), gone); + } + } + + private static Map> calls(final Scene scene) { + return Map.of( + "single", + McpTestUtils.createGetEntityToolCall("ontologyChangeSet", scene.fqn()), + "batch", + McpTestUtils.createToolCallRequest( + "get_entity_details", Map.of("entities", List.of("ontologyChangeSet:" + scene.fqn()))), + "include", + McpTestUtils.createToolCallRequest( + "get_entity_details", + Map.of( + "entityType", + "ontologyChangeSet", + "fqn", + scene.fqn(), + "include", + List.of("lineage", "quality", "context", "content"))), + "content only", + McpTestUtils.createToolCallRequest( + "get_entity_details", + Map.of( + "entityType", + "ontologyChangeSet", + "fqn", + scene.fqn(), + "include", + List.of("content")))); + } + + private static Scene scene( + final TestNamespace ns, final RdfAccessFixtures fixtures, final RdfAccessFixtures viewers) { + final Ontology ontology = BaseOntologyApprovalIT.createOntology(ns); + BaseOntologyApprovalIT.declareClass(ontology, "Order", ORDER); + final String editor = + BEARER + + OntologyDraftFixtures.tokenWithout( + fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final var viewAll = viewers.allowRole(MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_CHANGE_SET); + final var viewBasic = + viewers.allowRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CHANGE_SET); + final var noTables = viewers.denyRole(MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final String viewer = + BEARER + + viewers.userToken( + "viewer", List.of(viewAll.getId(), viewBasic.getId(), noTables.getId())); + final Table table = table(schema(ns), "hidden", column(COLUMN, ColumnDataType.VARCHAR)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + binds( + bindingOf(ORDER, table) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of(COLUMN))) + .withRowFilter(filter(COLUMN, OntologyRowFilterOperator.EQUALS, VALUE)))); + return new Scene(draft, table, editor, viewer); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.java new file mode 100644 index 000000000000..32e839e846cf --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceIT.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; + +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 static org.openmetadata.it.tests.OntologyDraftFixtures.CHANGE_SETS; +import static org.openmetadata.it.tests.OntologyDraftFixtures.apply; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.discard; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.evidence; +import static org.openmetadata.it.tests.OntologyDraftFixtures.lease; +import static org.openmetadata.it.tests.OntologyDraftFixtures.path; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyDraftFixtures.read; +import static org.openmetadata.it.tests.OntologyDraftFixtures.release; +import static org.openmetadata.it.tests.OntologyDraftFixtures.replaceOperations; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ownedTable; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import com.fasterxml.jackson.databind.JsonNode; +import java.time.Duration; +import java.util.List; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.ApplyOntologyChangeSet; +import org.openmetadata.schema.api.data.OntologyChangeSetCommand; +import org.openmetadata.schema.api.data.RestoreEntity; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyChangeEvidence; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.locator.ConnectionType; + +/** + * The evidence of a draft's operations as each caller reads and writes it. Each endpoint that + * answers with operations leaves out the entries whose table its caller may not view and counts + * them. A save stores no entry about such a table and keeps the entries its writer was not shown. No + * stored change event and no recorded change carries an entry, because neither has a single reader. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetEvidenceIT extends BaseOntologyApprovalIT { + private static final List> ID_COLUMN = List.of(List.of("id")); + private static final String CREATED = "entityCreated"; + private static final String UPDATED = "entityUpdated"; + private static final String APPLIED = "ontologyChangeSetApplied"; + + @Test + void aReadLeavesOutTheEvidenceOfTablesTheReaderMayNotViewAndCountsIt(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("readEvidence" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OntologyConcept customer = proposedClass(ontology, "Customer", CUSTOMER); + final OntologyChangeOperation supported = + creates(customer).withEvidence(scene.evidenceOfBothTables()); + final OntologyChangeSet draft = draft(admin(), ns, ontology, supported); + final OntologyEditLeaseToken lease = lease(admin(), draft); + customer.setDescription("A party that buys"); + replaceOperations(admin(), draft, lease, List.of(supported)); + release(admin(), draft, lease); + + final OntologyChangeOperation seen = read(scene.reader(), draft).getOperations().getFirst(); + final OntologyChangeOperation stored = read(admin(), draft).getOperations().getFirst(); + + assertEquals(List.of(scene.aboutTheShownTable()), seen.getEvidence()); + assertEquals(1, seen.getWithheldEvidenceCount()); + assertEquals(scene.evidenceOfBothTables(), stored.getEvidence()); + assertEquals(0, stored.getWithheldEvidenceCount()); + final String versions = path(draft) + "/versions"; + scene.assertReaderView("get", get(scene.reader(), path(draft))); + scene.assertReaderView( + "list", get(scene.reader(), CHANGE_SETS + "?ontologyId=" + ontology.getId())); + scene.assertReaderView("versions", get(scene.reader(), versions)); + scene.assertReaderView("version", get(scene.reader(), versions + "/0.1")); + assertTrue(get(admin(), versions).contains(scene.hidden().getId().toString())); + assertEquals( + 2, admin().ontologyChangeSets().getVersionList(draft.getId()).getVersions().size()); + } + } + + @Test + void aWriteAnswersItsCallerWithTheSameViewAndKeepsTheEntriesTheCallerWasNotShown( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("writeEvidence" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OpenMetadataClient reader = scene.reader(); + final OntologyChangeEvidence added = + evidence(scene.shown(), OntologyChangeEvidenceKind.LINEAGE); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence(scene.evidenceOfBothTables())); + final OntologyChangeOperation seen = read(reader, draft).getOperations().getFirst(); + final OntologyEditLeaseToken lease = lease(reader, draft); + final OntologyChangeSetCommand command = new OntologyChangeSetCommand().withLease(lease); + + final OntologyChangeOperation saved = + replaceOperations( + reader, + draft, + lease, + List.of(seen.withEvidence(List.of(scene.aboutTheShownTable(), added)))) + .getOperations() + .getFirst(); + + assertEquals(List.of(scene.aboutTheShownTable(), added), saved.getEvidence()); + assertEquals(1, saved.getWithheldEvidenceCount()); + assertEquals( + List.of(scene.aboutTheShownTable(), scene.aboutTheHiddenTable(), added), + read(admin(), draft).getOperations().getFirst().getEvidence()); + scene.assertReaderView("undo", post(reader, path(draft) + "/undo", command)); + scene.assertReaderView("redo", post(reader, path(draft) + "/redo", command)); + scene.assertReaderView("submit", post(reader, path(draft) + "/submit", command)); + scene.assertReaderView( + "apply", + post(reader, path(draft) + "/apply", new ApplyOntologyChangeSet().withLease(lease))); + scene.assertReaderView( + "delete", reader.getHttpClient().executeForString(HttpMethod.DELETE, path(draft), null)); + scene.assertReaderView( + "restore", + reader + .getHttpClient() + .executeForString( + HttpMethod.PUT, + CHANGE_SETS + "/restore", + new RestoreEntity().withId(draft.getId()))); + + final OntologyChangeSet discarded = + discard( + reader, + draft( + admin(), + ns, + ontology, + creates(proposedClass(ontology, "Order", ORDER)) + .withEvidence(scene.evidenceOfBothTables()))); + assertEquals( + List.of(scene.aboutTheShownTable()), discarded.getOperations().getFirst().getEvidence()); + assertEquals(1, discarded.getOperations().getFirst().getWithheldEvidenceCount()); + } + } + + @Test + void aSaveStoresNoEvidenceAboutATableItsWriterMayNotView(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("saveEvidence" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OpenMetadataClient writer = scene.reader(); + final OntologyChangeOperation supported = + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence(scene.evidenceOfBothTables()); + + final OntologyChangeSet created = draft(writer, ns, ontology, supported); + + final OntologyChangeOperation answered = created.getOperations().getFirst(); + assertEquals(List.of(scene.aboutTheShownTable()), answered.getEvidence()); + assertEquals(0, answered.getWithheldEvidenceCount()); + assertEquals( + List.of(scene.aboutTheShownTable()), + read(admin(), created).getOperations().getFirst().getEvidence()); + + final OntologyEditLeaseToken byAdmin = lease(admin(), created); + replaceOperations(admin(), created, byAdmin, List.of(supported)); + release(admin(), created, byAdmin); + final OntologyChangeOperation reread = read(writer, created).getOperations().getFirst(); + assertEquals(1, reread.getWithheldEvidenceCount()); + final OntologyChangeOperation guessed = + replaceOperations( + writer, + created, + lease(writer, created), + List.of( + reread.withEvidence( + List.of( + scene.aboutTheShownTable(), + scene.aboutTheHiddenTable(), + evidence(scene.hidden(), OntologyChangeEvidenceKind.LINEAGE))))) + .getOperations() + .getFirst(); + + assertEquals(List.of(scene.aboutTheShownTable()), guessed.getEvidence()); + assertEquals(1, guessed.getWithheldEvidenceCount()); + assertEquals( + scene.evidenceOfBothTables(), + read(admin(), created).getOperations().getFirst().getEvidence()); + } + } + + @Test + void anEditOfEvidenceAloneIsStoredWithoutANewVersion(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Table customers = table(schema(ns), "customers", column("id", ColumnDataType.BIGINT)); + final OntologyChangeOperation supported = + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence(List.of(evidence(customers, OntologyChangeEvidenceKind.NAME))); + final OntologyChangeSet draft = draft(admin(), ns, ontology, supported); + final List profiled = + List.of(evidence(customers, OntologyChangeEvidenceKind.PROFILE).withColumns(ID_COLUMN)); + + final OntologyChangeSet edited = + replaceOperations( + admin(), draft, lease(admin(), draft), List.of(supported.withEvidence(profiled))); + + final OntologyChangeSet stored = read(admin(), draft); + assertEquals(profiled, edited.getOperations().getFirst().getEvidence()); + assertEquals(profiled, stored.getOperations().getFirst().getEvidence()); + assertEquals(draft.getVersion(), stored.getVersion()); + assertEquals( + 1, admin().ontologyChangeSets().getVersionList(draft.getId()).getVersions().size()); + } + + @Test + void noRecordedChangeAndNoStoredChangeEventCarriesTheEvidenceOfADraft(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Table customers = table(schema(ns), "customers", column("id", ColumnDataType.BIGINT)); + final OntologyConcept customer = proposedClass(ontology, "Customer", CUSTOMER); + final List named = + List.of(evidence(customers, OntologyChangeEvidenceKind.NAME)); + final OntologyChangeOperation supported = creates(customer).withEvidence(named); + final OntologyChangeSet draft = draft(admin(), ns, ontology, supported); + final OntologyEditLeaseToken lease = lease(admin(), draft); + customer.setDescription("A party that buys"); + + final OntologyChangeSet changed = replaceOperations(admin(), draft, lease, List.of(supported)); + final OntologyChangeSet applied = apply(admin(), draft, lease); + + final String recorded = JsonUtils.pojoToJson(changed.getChangeDescription()); + assertTrue(changed.getVersion() > draft.getVersion()); + assertTrue(recorded.contains(supported.getId().toString()), recorded); + assertFalse(recorded.contains(customers.getId().toString()), recorded); + final List events = storedEvents(draft, CREATED, UPDATED, APPLIED); + for (final String event : events) { + assertFalse(event.contains(customers.getId().toString()), event); + assertTrue(storedOperations(event).isMissingNode(), event); + } + for (final String type : List.of(CREATED, UPDATED, APPLIED)) { + assertFalse(ofType(events, type).isEmpty(), type); + } + assertEquals(named, applied.getOperations().getFirst().getEvidence()); + assertEquals(named, read(admin(), draft).getOperations().getFirst().getEvidence()); + } + + /** A reader who may view the tables they own and no other, with one table of each kind. */ + private record Scene(OpenMetadataClient reader, Table shown, Table hidden) { + private OntologyChangeEvidence aboutTheShownTable() { + return evidence(shown, OntologyChangeEvidenceKind.NAME); + } + + private OntologyChangeEvidence aboutTheHiddenTable() { + return evidence(hidden, OntologyChangeEvidenceKind.PROFILE).withColumns(ID_COLUMN); + } + + private List evidenceOfBothTables() { + return List.of(aboutTheShownTable(), aboutTheHiddenTable()); + } + + /** What the reader is sent: the evidence about the table it may view, and no other table. */ + private void assertReaderView(final String endpoint, final String body) { + assertTrue(body.contains(shown.getId().toString()), endpoint); + assertFalse(body.contains(hidden.getId().toString()), endpoint); + } + } + + private static Scene scene(final TestNamespace ns, final RdfAccessFixtures fixtures) { + final DatabaseSchema schema = schema(ns); + final OpenMetadataClient reader = + callerWithout(fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, "!isOwner()"); + final Table shown = + ownedTable( + schema, + "customers", + OntologyBindingFixtures.readerReference(reader), + column("id", ColumnDataType.BIGINT)); + final Table hidden = table(schema, "payments", column("id", ColumnDataType.BIGINT)); + return new Scene(reader, shown, hidden); + } + + private static String get(final OpenMetadataClient caller, final String path) { + return caller.getHttpClient().executeForString(HttpMethod.GET, path, null); + } + + private static String post( + final OpenMetadataClient caller, final String path, final Object body) { + return caller.getHttpClient().executeForString(HttpMethod.POST, path, body); + } + + /** + * The change events stored for a draft, once one of each of these types is stored. The event of a + * request is written after its response is sent. + */ + private static List storedEvents(final OntologyChangeSet draft, final String... types) { + return Awaitility.await("the change events of the draft") + .atMost(Duration.ofSeconds(30)) + .pollInterval(Duration.ofMillis(250)) + .until( + () -> eventsOf(draft), + events -> List.of(types).stream().noneMatch(type -> ofType(events, type).isEmpty())); + } + + private static List eventsOf(final OntologyChangeSet draft) { + final String sql = + TestSuiteBootstrap.getConnectionType() == ConnectionType.MYSQL + ? "SELECT CAST(json AS CHAR) FROM change_event WHERE json ->> '$.entityId' = :id" + : "SELECT json::text FROM change_event WHERE json ->> 'entityId' = :id"; + return Entity.getJdbi() + .withHandle( + handle -> + handle + .createQuery(sql) + .bind("id", draft.getId().toString()) + .mapTo(String.class) + .list()); + } + + private static List ofType(final List events, final String type) { + return events.stream() + .filter(event -> type.equals(JsonUtils.readTree(event).path("eventType").asText())) + .toList(); + } + + /** The operations of the change set an event stores. An event holds its entity as JSON text. */ + private static JsonNode storedOperations(final String event) { + final JsonNode entity = JsonUtils.readTree(event).path("entity"); + return (entity.isTextual() ? JsonUtils.readTree(entity.asText()) : entity).path("operations"); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceMcpIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceMcpIT.java new file mode 100644 index 000000000000..f31a968a5409 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetEvidenceMcpIT.java @@ -0,0 +1,158 @@ +/* + * 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; + +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 static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.evidence; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyDraftFixtures.read; +import static org.openmetadata.it.tests.OntologyDraftFixtures.tokenWithout; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ownedTable; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; +import java.util.stream.StreamSupport; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.tests.mcp.McpTestBase; +import org.openmetadata.it.tests.mcp.McpTestUtils; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.service.Entity; + +/** + * A stored change set as the entity tools hand it to a caller. get_entity_details leaves out the + * evidence about tables its caller may not view and counts it, as every REST read of a change set + * does. patch_entity refuses a change set, because a JSON Patch can copy a stored evidence entry to + * a member that every reader is shown. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetEvidenceMcpIT extends McpTestBase { + private static final String BEARER = "Bearer "; + + /** A draft whose one operation rests on a table the caller owns and on one it may not view. */ + private record Scene(String token, Table shown, Table hidden, OntologyChangeSet draft) {} + + @Test + void theEntityToolLeavesOutTheEvidenceOfTablesItsCallerMayNotView(final TestNamespace ns) + throws Exception { + initAuth(); + final Ontology ontology = BaseOntologyApprovalIT.createOntology(ns); + try (var fixtures = new RdfAccessFixtures("toolEvidence" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, ontology); + final String shown = scene.shown().getId().toString(); + final String hidden = scene.hidden().getId().toString(); + + final JsonNode stored = operationReadBy(authToken, scene.draft()); + final JsonNode seen = operationReadBy(BEARER + scene.token(), scene.draft()); + + assertEquals(List.of(shown, hidden), evidenceTables(stored)); + assertEquals(0, stored.path("withheldEvidenceCount").asInt(-1)); + assertEquals(List.of(shown), evidenceTables(seen)); + assertEquals(1, seen.path("withheldEvidenceCount").asInt(-1)); + assertFalse(seen.toString().contains(hidden), seen::toString); + } + } + + @Test + void thePatchToolRefusesAChangeSetSoNoPatchCopiesEvidenceToAMemberEveryReaderSees( + final TestNamespace ns) throws Exception { + initAuth(); + final Ontology ontology = BaseOntologyApprovalIT.createOntology(ns); + try (var fixtures = new RdfAccessFixtures("toolPatch" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures, ontology); + + final JsonNode answer = + executeMcpRequest( + McpTestUtils.createPatchEntityToolCall( + Entity.ONTOLOGY_CHANGE_SET, + scene.draft().getFullyQualifiedName(), + "[{\"op\":\"copy\",\"from\":\"/operations/0/evidence/1/tableId\"," + + "\"path\":\"/description\"}]"), + BEARER + scene.token()); + + assertTrue(answer.at("/result/isError").asBoolean(false), answer::toString); + assertTrue( + answer + .at("/result/content/0/text") + .asText() + .contains("cannot be patched through patch_entity"), + answer::toString); + assertFalse(answer.toString().contains(scene.hidden().getId().toString()), answer::toString); + assertEquals(scene.draft().getDescription(), read(admin(), scene.draft()).getDescription()); + } + } + + private static Scene scene( + final TestNamespace ns, final RdfAccessFixtures fixtures, final Ontology ontology) { + final String token = + tokenWithout(fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, "!isOwner()"); + final DatabaseSchema schema = schema(ns); + final Table shown = + ownedTable( + schema, + "customers", + OntologyBindingFixtures.readerReference(OntologyBindingFixtures.client(token)), + column("id", ColumnDataType.BIGINT)); + final Table hidden = table(schema, "payments", column("id", ColumnDataType.BIGINT)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence( + List.of( + evidence(shown, OntologyChangeEvidenceKind.NAME), + evidence(hidden, OntologyChangeEvidenceKind.PROFILE)))); + return new Scene(token, shown, hidden, draft); + } + + /** The one operation of the draft as get_entity_details answers its caller. */ + private JsonNode operationReadBy(final String bearer, final OntologyChangeSet draft) + throws Exception { + final JsonNode response = + executeMcpRequest( + McpTestUtils.createGetEntityToolCall( + Entity.ONTOLOGY_CHANGE_SET, draft.getFullyQualifiedName()), + bearer); + assertFalse(response.at("/result/isError").asBoolean(false), response::toString); + return OBJECT_MAPPER + .readTree(response.at("/result/content/0/text").asText()) + .at("/operations/0"); + } + + private static List evidenceTables(final JsonNode operation) { + return StreamSupport.stream(operation.path("evidence").spliterator(), false) + .map(entry -> entry.path("tableId").asText()) + .toList(); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetSaveSightIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetSaveSightIT.java new file mode 100644 index 000000000000..351d376a38ee --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyChangeSetSaveSightIT.java @@ -0,0 +1,301 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.evidence; +import static org.openmetadata.it.tests.OntologyDraftFixtures.lease; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyDraftFixtures.read; +import static org.openmetadata.it.tests.OntologyDraftFixtures.release; +import static org.openmetadata.it.tests.OntologyDraftFixtures.replaceOperations; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ownedTable; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyChangeEvidence; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.service.Entity; + +/** + * A save stores the evidence its writer read, so a writer whose sight of a table changed after the + * read must read again. The client sends back the number of entries its read withheld, and a save is + * a 412 when the stored operation withholds a different number from that writer now. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetSaveSightIT extends BaseOntologyApprovalIT { + private static final int PRECONDITION_FAILED = 412; + private static final List> ID_COLUMN = List.of(List.of("id")); + + @Test + void aTableDeletedAtTheReadAndRestoredBeforeTheSaveRefusesTheSaveAndKeepsItsEvidence( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Table table = table(schema(ns), "payments", column("id", ColumnDataType.BIGINT)); + final OntologyChangeOperation operation = + creates(proposedClass(ontology, "Customer", CUSTOMER)).withEvidence(List.of(about(table))); + final OntologyChangeSet draft = draft(admin(), ns, ontology, operation); + admin().tables().delete(table.getId()); + final OntologyChangeOperation seen = read(admin(), draft).getOperations().getFirst(); + assertEquals(1, seen.getWithheldEvidenceCount()); + admin().tables().restore(table.getId().toString()); + + final OpenMetadataException refusal = saveRefused(admin(), draft, seen); + + assertEquals(PRECONDITION_FAILED, refusal.getStatusCode()); + assertTrue(refusal.getMessage().contains("operation '" + operation.getId() + "'")); + assertTrue(refusal.getMessage().contains("Read the change set again")); + assertEquals( + List.of(about(table)), read(admin(), draft).getOperations().getFirst().getEvidence()); + final OntologyChangeOperation again = read(admin(), draft).getOperations().getFirst(); + assertEquals(0, again.getWithheldEvidenceCount()); + assertEquals(List.of(about(table)), save(admin(), draft, again).getEvidence()); + } + + @Test + void aPolicyThatHidesATableAfterTheReadRefusesTheSave(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("sightPolicy" + ns.shortPrefix())) { + final DatabaseSchema schema = schema(ns); + final var everything = fixtures.allowRole(MetadataOperation.ALL, "All"); + final var deny = + fixtures.denyRole( + MetadataOperation.VIEW_BASIC, Entity.TABLE, "matchAnyTag('PII.Sensitive')"); + final OpenMetadataClient writer = + OntologyBindingFixtures.client( + fixtures.userToken("writer", List.of(everything.getId(), deny.getId()))); + final Table first = table(schema, "first", column("id", ColumnDataType.BIGINT)); + final Table second = table(schema, "second", column("id", ColumnDataType.BIGINT)); + final OntologyChangeSet draft = + draft( + writer, + ns, + ontology, + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence(List.of(about(first), about(second)))); + final OntologyChangeOperation seen = read(writer, draft).getOperations().getFirst(); + assertEquals(0, seen.getWithheldEvidenceCount()); + sensitive(second); + Awaitility.await("the policy hides the table from the writer") + .atMost(Duration.ofSeconds(30)) + .until(() -> hidesFrom(writer, second)); + + final OpenMetadataException refusal = saveRefused(writer, draft, seen); + + assertEquals(PRECONDITION_FAILED, refusal.getStatusCode()); + assertEquals( + List.of(about(first), about(second)), + read(admin(), draft).getOperations().getFirst().getEvidence()); + } + } + + @Test + void aSaveThatSendsBackTheCountItsReadWithheldIsAcceptedAndKeepsTheWithheldEntry( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("sightEqual" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OntologyChangeSet draft = bothTablesDraft(ns, ontology, scene); + final OntologyChangeOperation seen = read(scene.reader(), draft).getOperations().getFirst(); + assertEquals(1, seen.getWithheldEvidenceCount()); + + final OntologyChangeOperation saved = save(scene.reader(), draft, seen); + + assertEquals(1, saved.getWithheldEvidenceCount()); + assertEquals( + List.of(about(scene.shown()), about(scene.hidden())), + read(admin(), draft).getOperations().getFirst().getEvidence()); + } + } + + @Test + void aSaveThatSendsALargerOrASmallerCountThanTheOperationWithholdsIsRefused( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("sightCount" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OntologyChangeSet draft = bothTablesDraft(ns, ontology, scene); + final OntologyChangeOperation seen = read(scene.reader(), draft).getOperations().getFirst(); + + assertEquals( + PRECONDITION_FAILED, + saveRefused(scene.reader(), draft, seen.withWithheldEvidenceCount(2)).getStatusCode()); + assertEquals( + PRECONDITION_FAILED, + saveRefused(scene.reader(), draft, seen.withWithheldEvidenceCount(0)).getStatusCode()); + assertEquals( + List.of(about(scene.shown()), about(scene.hidden())), + read(admin(), draft).getOperations().getFirst().getEvidence()); + } + } + + @Test + void aCountSentWhenNothingIsWithheldIsAcceptedAtZeroAndRefusedAboveIt(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final Table table = table(schema(ns), "payments", column("id", ColumnDataType.BIGINT)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence(List.of(about(table)))); + final OntologyChangeOperation seen = read(admin(), draft).getOperations().getFirst(); + assertEquals(0, seen.getWithheldEvidenceCount()); + + assertEquals( + PRECONDITION_FAILED, + saveRefused(admin(), draft, seen.withWithheldEvidenceCount(3)).getStatusCode()); + assertEquals( + List.of(about(table)), + save(admin(), draft, seen.withWithheldEvidenceCount(0)).getEvidence()); + } + + @Test + void aSaveThatSendsNoCountIsNotChecked(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + try (var fixtures = new RdfAccessFixtures("sightNone" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OntologyChangeSet draft = bothTablesDraft(ns, ontology, scene); + final OntologyChangeOperation seen = read(scene.reader(), draft).getOperations().getFirst(); + + final OntologyChangeOperation saved = + save(scene.reader(), draft, seen.withWithheldEvidenceCount(null)); + + assertEquals(1, saved.getWithheldEvidenceCount()); + assertEquals( + List.of(about(scene.shown()), about(scene.hidden())), + read(admin(), draft).getOperations().getFirst().getEvidence()); + } + } + + @Test + void aCountOnAnOperationTheDraftDoesNotStoreYetIsNotChecked(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyChangeSet draft = + draft(admin(), ns, ontology, creates(proposedClass(ontology, "Customer", CUSTOMER))); + final OntologyChangeOperation added = + creates(proposedClass(ontology, "Order", OntologyMappingFixtures.ORDER)) + .withWithheldEvidenceCount(4); + final List operations = + new ArrayList<>(read(admin(), draft).getOperations()); + operations.add(added); + final OntologyEditLeaseToken lease = lease(admin(), draft); + + final OntologyChangeSet saved = replaceOperations(admin(), draft, lease, operations); + release(admin(), draft, lease); + + assertEquals(2, saved.getOperations().size()); + assertNull(read(admin(), draft).getOperations().getLast().getEvidence()); + } + + private static OntologyChangeOperation save( + final OpenMetadataClient writer, + final OntologyChangeSet draft, + final OntologyChangeOperation operation) { + final OntologyEditLeaseToken lease = lease(writer, draft); + try { + return replaceOperations(writer, draft, lease, List.of(operation)).getOperations().getFirst(); + } finally { + release(writer, draft, lease); + } + } + + private static OpenMetadataException saveRefused( + final OpenMetadataClient writer, + final OntologyChangeSet draft, + final OntologyChangeOperation operation) { + return assertThrows(OpenMetadataException.class, () -> save(writer, draft, operation)); + } + + private static OntologyChangeEvidence about(final Table table) { + return evidence(table, OntologyChangeEvidenceKind.NAME).withColumns(ID_COLUMN); + } + + private static void sensitive(final Table table) { + final Table stored = admin().tables().get(table.getId().toString(), "tags"); + stored.setTags( + new ArrayList<>( + List.of( + new TagLabel() + .withTagFQN("PII.Sensitive") + .withSource(TagLabel.TagSource.CLASSIFICATION) + .withLabelType(TagLabel.LabelType.MANUAL) + .withState(TagLabel.State.CONFIRMED)))); + admin().tables().update(table.getId(), stored); + } + + private static boolean hidesFrom(final OpenMetadataClient caller, final Table table) { + try { + caller.tables().get(table.getId().toString()); + return false; + } catch (OpenMetadataException refused) { + return true; + } + } + + private static OntologyChangeSet bothTablesDraft( + final TestNamespace ns, final Ontology ontology, final Scene scene) { + return draft( + admin(), + ns, + ontology, + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence(List.of(about(scene.shown()), about(scene.hidden())))); + } + + /** A writer who may view the tables it owns and no other, with one table of each kind. */ + private record Scene(OpenMetadataClient reader, Table shown, Table hidden) {} + + private static Scene scene(final TestNamespace ns, final RdfAccessFixtures fixtures) { + final DatabaseSchema schema = schema(ns); + final OpenMetadataClient reader = + callerWithout(fixtures, MetadataOperation.VIEW_BASIC, Entity.TABLE, "!isOwner()"); + final Table shown = + ownedTable( + schema, + "customers", + OntologyBindingFixtures.readerReference(reader), + column("id", ColumnDataType.BIGINT)); + return new Scene(reader, shown, table(schema, "payments", column("id", ColumnDataType.BIGINT))); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyCheckReconcileCostIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyCheckReconcileCostIT.java new file mode 100644 index 000000000000..6356e6e73508 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyCheckReconcileCostIT.java @@ -0,0 +1,170 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.targets; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.jdbi.v3.core.Jdbi; +import org.jdbi.v3.core.statement.SqlLogger; +import org.jdbi.v3.core.statement.StatementContext; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.ActivateOntologyRelease; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.type.TaskResolutionType; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyCheckReconcileQueue; + +/** + * What a reconcile costs in statements and time for 1, 10 and 100 classes that each have one + * check: the run that proposes every check, and the run that finds nothing to write. The numbers + * are printed, and the second run is asserted to write nothing. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyCheckReconcileCostIT extends BaseOntologyApprovalIT { + private static final String JOB = "ontology-check-reconcile"; + + /** What a run costs for each class, with the margin the shared lane's caches can move it by. */ + private static final int FIRST_RUN_STATEMENTS_PER_CLASS = 170; + + private static final int SECOND_RUN_STATEMENTS_PER_CLASS = 45; + private static final int FIXED_STATEMENTS = 40; + + /** + * Counts the statements of the runs of one ontology on the reconcile threads. A run starts with + * the read of the state of its ontology, so a thread counts from that statement until the read + * of another ontology's state starts the next run. Runs of other ontologies in the same lane are + * not counted. + */ + private static final class JobCounter implements SqlLogger { + private static final String STATE = "from ontology_state"; + private final String ontologyId; + private final AtomicInteger count = new AtomicInteger(); + private final ThreadLocal mine = ThreadLocal.withInitial(() -> Boolean.FALSE); + + JobCounter(final String ontologyId) { + this.ontologyId = ontologyId; + } + + @Override + public void logBeforeExecution(final StatementContext context) { + if (!Thread.currentThread().getName().equals(JOB)) { + return; + } + if (context.getRenderedSql().toLowerCase(java.util.Locale.ROOT).contains(STATE)) { + mine.set(context.getBinding().toString().contains(ontologyId)); + } + if (mine.get()) { + count.incrementAndGet(); + } + } + } + + private static void settle() throws InterruptedException { + assertTrue(OntologyCheckReconcileQueue.instance().awaitIdle(600, TimeUnit.SECONDS)); + } + + @Test + void one(final TestNamespace ns) throws InterruptedException { + measure(ns, 1); + } + + @Test + void ten(final TestNamespace ns) throws InterruptedException { + measure(ns, 10); + } + + @Test + void hundred(final TestNamespace ns) throws InterruptedException { + measure(ns, 100); + } + + private static void measure(final TestNamespace ns, final int classes) + throws InterruptedException { + final Ontology ontology = createOntology(ns, "k" + classes); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, targets("k" + classes, classes, null))) { + fixture.bindAll(); + for (int i = 0; i < classes; i++) { + declare( + ontology, + fixture, + "S" + i, + "Target" + i, + on(fixture, "t" + i, "title" + i).withIn(literals("x"))); + } + final OntologyRelease release = capture(ontology); + final var task = submit(ns, Entity.ONTOLOGY_RELEASE, release.getFullyQualifiedName()); + org.openmetadata.it.util.SdkClients.user1Client() + .tasks() + .resolve(task.getId().toString(), decision(TaskResolutionType.Approved)); + final Jdbi jdbi = Entity.getJdbi(); + final SqlLogger previous = + jdbi.getConfig(org.jdbi.v3.core.statement.SqlStatements.class).getSqlLogger(); + final JobCounter counter = new JobCounter(ontology.getId().toString()); + jdbi.setSqlLogger(counter); + try { + final OntologyCheckReconcileQueue queue = OntologyCheckReconcileQueue.instance(); + long started = System.nanoTime(); + org.openmetadata.it.util.SdkClients.adminClient() + .ontologies() + .activate( + ontology.getId(), + new ActivateOntologyRelease() + .withReleaseId(release.getId()) + .withExpectedActivationRevision(0L)); + settle(); + final long firstMs = (System.nanoTime() - started) / 1_000_000; + final int firstStatements = counter.count.getAndSet(0); + final int firstWrites = queue.writesMade(ontology.getId()); + + started = System.nanoTime(); + queue.afterActivation(ontology.getId(), "admin"); + settle(); + final long secondMs = (System.nanoTime() - started) / 1_000_000; + final int secondStatements = counter.count.get(); + + System.out.printf( + "RECONCILE-COST classes=%d first: statements=%d ms=%d writes=%d | second: statements=%d ms=%d writes=%d%n", + classes, + firstStatements, + firstMs, + firstWrites, + secondStatements, + secondMs, + queue.writesMade(ontology.getId()) - firstWrites); + assertEquals(classes, firstWrites); + assertEquals(firstWrites, queue.writesMade(ontology.getId())); + assertTrue( + firstStatements <= FIRST_RUN_STATEMENTS_PER_CLASS * classes + FIXED_STATEMENTS, + "first run " + firstStatements); + assertTrue( + secondStatements <= SECOND_RUN_STATEMENTS_PER_CLASS * classes + FIXED_STATEMENTS, + "second run " + secondStatements); + } finally { + jdbi.setSqlLogger(previous); + } + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingFirstRowsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingFirstRowsIT.java new file mode 100644 index 000000000000..2e8a4dac74e5 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingFirstRowsIT.java @@ -0,0 +1,116 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.EntityDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.StoredBinding; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; + +/** + * The first rows of many tables, read in one call, are the first rows of each table read on its + * own: the cap counts the rows of one table, never of all of them. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyConceptBindingFirstRowsIT extends BaseOntologyApprovalIT { + private static final int CAP = 101; + private static final List TABLE_SIZES = List.of(150, 5, 101, 102); + private static final List ROLES = List.of("identity", "contributing", ""); + + @Test + void theFirstRowsOfSeveralTablesAreTheFirstRowsOfEachTableOnItsOwn() { + final OntologyConceptBindingDAO dao = Entity.getCollectionDAO().ontologyConceptBindingDAO(); + final OntologyConceptBindingStore store = + new OntologyConceptBindingStore(Entity.getCollectionDAO(), type -> "table_entity"); + final Map> written = new LinkedHashMap<>(); + TABLE_SIZES.forEach(size -> written.put(UUID.randomUUID(), new ArrayList<>())); + try { + writeRows(dao, written); + final List tables = List.copyOf(written.keySet()); + + assertEachTableReadsAsItDoesOnItsOwn(dao, grouped(store.firstForAssets(tables, CAP)), tables); + + final Map> acrossTwoChunks = + grouped(store.firstForAssets(idsSplitOverTwoChunks(tables), CAP)); + assertEachTableReadsAsItDoesOnItsOwn(dao, acrossTwoChunks, tables); + assertEquals( + List.of(CAP, 5, CAP, CAP), + tables.stream().map(t -> acrossTwoChunks.get(t).size()).toList()); + } finally { + written.forEach((table, concepts) -> concepts.forEach(concept -> dao.delete(concept, table))); + } + } + + private static void writeRows( + final OntologyConceptBindingDAO dao, final Map> written) { + final List tables = List.copyOf(written.keySet()); + for (int table = 0; table < tables.size(); table++) { + for (int row = 0; row < TABLE_SIZES.get(table); row++) { + final UUID concept = UUID.randomUUID(); + final String role = ROLES.get(row % ROLES.size()); + dao.upsert( + new StoredBinding( + concept.toString(), + tables.get(table).toString(), + "table", + "firstRows" + row, + "[]", + role.isEmpty() ? null : role, + null, + null)); + written.get(tables.get(table)).add(concept); + } + } + } + + /** Ids of the four tables, with enough others between them that a chunk ends between the two pairs. */ + private static List idsSplitOverTwoChunks(final List tables) { + final List ids = new ArrayList<>(List.of(tables.get(0), tables.get(2))); + IntStream.range(0, EntityDAO.MAX_IN_LIST_CHUNK_SIZE - 2) + .forEach(i -> ids.add(UUID.randomUUID())); + ids.add(tables.get(1)); + ids.add(tables.get(3)); + return ids; + } + + private static void assertEachTableReadsAsItDoesOnItsOwn( + final OntologyConceptBindingDAO dao, + final Map> together, + final List tables) { + for (final UUID table : tables) { + final List alone = dao.listForAssetAfter(table, "", CAP); + assertEquals(alone, together.get(table), "table " + table); + } + } + + private static Map> grouped(final List rows) { + return rows.stream() + .collect( + Collectors.groupingBy(BindingRow::assetId, LinkedHashMap::new, Collectors.toList())); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingsIT.java index 0f41706bb195..97f4a5b0e7af 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptBindingsIT.java @@ -131,6 +131,37 @@ void inheritedDataPropertyAndExactNestedPathAreValidated(TestNamespace ns) { assertEquals(1L, get(admin(), child).getRevision()); } + /** + * A class under two named classes inherits the properties of both, and of everything above each. + * The axioms are read by name, so the walk meets {@code ChildIsAFirst} before {@code + * ChildIsBSecond}, and only the second parent leads to the root. + */ + @Test + void propertiesOfTheSecondParentAndOfEverythingAboveItAreApplicable(TestNamespace ns) { + final var ontology = createOntology(ns); + final var child = declareClass(ontology, "Child", URI.create("urn:Child")); + final var first = declareClass(ontology, "First", URI.create("urn:First")); + final var second = declareClass(ontology, "Second", URI.create("urn:Second")); + final var other = declareClass(ontology, "Other", URI.create("urn:Other")); + final var root = declareClass(ontology, "Root", URI.create("urn:Root")); + final var stranger = declareClass(ontology, "Stranger", URI.create("urn:Stranger")); + subclassOf(ontology, child, first, "ChildIsAFirst"); + subclassOf(ontology, child, second, "ChildIsBSecond"); + subclassOf(ontology, first, other, "FirstIsOther"); + subclassOf(ontology, second, root, "SecondIsRoot"); + final var table = table(ns); + + assertEquals( + 1L, put(admin(), child, association(table, property(ontology, root)), 0L).getRevision()); + assertEquals( + 2L, put(admin(), child, association(table, property(ontology, second)), 1L).getRevision()); + assertEquals( + 3L, put(admin(), child, association(table, property(ontology, other)), 2L).getRevision()); + assertStatus( + 400, () -> put(admin(), child, association(table, property(ontology, stranger)), 3L)); + assertEquals(3L, get(admin(), child).getRevision()); + } + @Test void hiddenTargetsAreNotReturnedOrOverwrittenByVisibleAssetUpdates(TestNamespace ns) { final var ontology = createOntology(ns); @@ -559,6 +590,26 @@ private static int writeTogether( } } + private static void subclassOf( + Ontology ontology, OntologyConcept child, OntologyConcept parent, String name) { + admin() + .ontologyAxioms() + .create( + new CreateOntologyAxiom() + .withName(name) + .withDisplayName(name) + .withDescription("A named parent that supplies applicable property domains.") + .withOntology(ontology.getFullyQualifiedName()) + .withAxiomType(OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(child.getIri()) + .withProvenance(RelationProvenance.MANUAL) + .withExpressions( + List.of( + new OntologyExpression() + .withKind(OntologyExpressionKind.NAMED_CLASS) + .withClassIri(parent.getIri())))); + } + private static OntologyProperty property(Ontology ontology, OntologyConcept domain) { return admin() .ontologyProperties() diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptQueryIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptQueryIT.java index ff3c5a90bc56..5e8dc53d7a94 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptQueryIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyConceptQueryIT.java @@ -5,11 +5,15 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.openmetadata.it.tests.OntologyBindingFixtures.admin; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; import static org.openmetadata.it.tests.OntologyBindingFixtures.bind; import static org.openmetadata.it.tests.OntologyBindingFixtures.bindings; import static org.openmetadata.it.tests.OntologyBindingFixtures.client; import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; import static org.openmetadata.schema.api.data.OntologyConceptQueryDirection.INCOMING; import static org.openmetadata.schema.api.data.OntologyConceptQueryDirection.OUTGOING; @@ -45,8 +49,13 @@ import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.client.OpenMetadataClient; @@ -61,6 +70,13 @@ class OntologyConceptQueryIT extends BaseOntologyApprovalIT { private static final URI ACCOUNT = URI.create("urn:payments:Account"); private static final URI EMPLOYEE = URI.create("urn:payments:Employee"); private static final URI XSD_STRING = URI.create("http://www.w3.org/2001/XMLSchema#string"); + private static final String NO_VIEWABLE_TABLE = + " has no bound table you can view among its first 100 table bindings"; + private static final String PICK_IDENTITY_TABLE = + "Class urn:payments:FundsTransfer binds several tables and none is its identity table." + + " Pick its identity table"; + private static final String HIDDEN_IDENTITY_TABLE = + "The identity table of class urn:payments:FundsTransfer is not visible to you"; private record Payments( Ontology ontology, @@ -113,13 +129,11 @@ void theSqlSelectsTheBoundColumnsAndJoinsEachHopOnForeignKeys(final TestNamespac "\n", "SELECT t2.account_id", "FROM " + schema + ".transfers t0", - "JOIN " + schema + ".customers t1 ON t0.customer_id = t1.customer_id -- part of", - "JOIN " + schema + ".accounts t2 ON t1.customer_id = t2.owner_id -- holds", + "JOIN " + schema + ".customers t1 ON t0.customer_id = t1.customer_id", + "JOIN " + schema + ".accounts t2 ON t1.customer_id = t2.owner_id", "LIMIT 50"), twoHops.getSql()); - assertEquals( - List.of("part of", "holds"), - twoHops.getHops().stream().map(OntologyConceptQueryHop::getLabel).toList()); + assertEquals(List.of("part of", "holds"), labels(twoHops)); } @Test @@ -136,7 +150,9 @@ void aHopWithoutAConstraintJoinsAnObjectPropertyBindingToTheTargetIdentifier( bind( payments.transfer(), transfers, - List.of(column(transferId, "transfer_id"), column(payments.partOf(), "payer_id")), + List.of( + column(transferId, "transfer_id"), + relation(payments.partOf(), "payer_id", customers, "customer_id")), 0L); bind(payments.customer(), customers, List.of(column(customerId, "customer_id")), 0L); @@ -148,7 +164,7 @@ void aHopWithoutAConstraintJoinsAnObjectPropertyBindingToTheTargetIdentifier( + payments.schema().getName() + ".transfers t0\nJOIN " + payments.schema().getName() - + ".customers t1 ON t0.payer_id = t1.customer_id -- part of\nLIMIT 50", + + ".customers t1 ON t0.payer_id = t1.customer_id\nLIMIT 50", joined.getSql()); } @@ -236,44 +252,193 @@ void aTableTheReaderMayNotViewIsUnboundAndItsColumnsStayHidden(final TestNamespa } @Test - void aReaderWhoMayViewOnlyTheTwelfthBoundTableGetsSqlOverIt(final TestNamespace ns) { + void aClassWithOneTableBindingStartsFromThatTableWhateverItsRole(final TestNamespace ns) { final Payments payments = - payments(ns, "twelfthPayments", DatabaseServiceTestFactory.createPostgres(ns)); + payments(ns, "oneTablePayments", DatabaseServiceTestFactory.createPostgres(ns)); + final Table transfers = table(payments, "transfers", List.of("transfer_id")); + final Table customers = table(payments, "customers", List.of("customer_id")); + final Table accounts = table(payments, "accounts", List.of("account_id")); + bindData(payments.transfer(), transfers, payments.ontology(), "transfer_id"); + bindAs( + OntologyBindingRole.CONTRIBUTING, + payments.customer(), + customers, + payments.ontology(), + "customer_id"); + bindIdentity(payments.account(), accounts, payments.ontology(), "account_id"); + try (var fixtures = new RdfAccessFixtures("conceptQueryOne" + ns.shortPrefix())) { + final OpenMetadataClient reader = ownerReader(fixtures, Entity.TABLE); + final String schema = payments.schema().getName(); + + assertEquals( + "SELECT transfer_id\nFROM " + schema + ".transfers\nLIMIT 50", + query(admin(), payments.transfer()).getSql()); + assertEquals( + "SELECT customer_id\nFROM " + schema + ".customers\nLIMIT 50", + query(admin(), payments.customer()).getSql()); + assertEquals( + "SELECT account_id\nFROM " + schema + ".accounts\nLIMIT 50", + query(admin(), payments.account()).getSql()); + assertRefused( + 400, + "Concept FundsTransfer" + NO_VIEWABLE_TABLE, + () -> query(reader, payments.transfer())); + assertRefused( + 400, "Concept Customer" + NO_VIEWABLE_TABLE, () -> query(reader, payments.customer())); + assertRefused( + 400, "Concept Account" + NO_VIEWABLE_TABLE, () -> query(reader, payments.account())); + } + } + + @Test + void aClassWithSeveralTableBindingsIsRefusedUntilItsIdentityTableIsPicked( + final TestNamespace ns) { + final Payments payments = + payments(ns, "severalPayments", DatabaseServiceTestFactory.createPostgres(ns)); + final Table customers = table(payments, "customers", List.of("customer_id")); + final Table transfers = + table( + payments, + "transfers", + List.of("transfer_id", "customer_id"), + foreignKey("customer_id", customers, "customer_id")); + final Table ledger = table(payments, "ledger", List.of("entry_id")); + bindData(payments.customer(), customers, payments.ontology(), "customer_id"); + bindData(payments.transfer(), transfers, payments.ontology(), "transfer_id"); + bindAs( + OntologyBindingRole.CONTRIBUTING, + payments.transfer(), + ledger, + payments.ontology(), + "entry_id"); + try (var fixtures = new RdfAccessFixtures("conceptQuerySeveral" + ns.shortPrefix())) { + final OpenMetadataClient reader = ownerReader(fixtures, Entity.TABLE); + own(ledger, reader); + + assertRefused(409, PICK_IDENTITY_TABLE, () -> query(admin(), payments.transfer())); + assertRefused(409, PICK_IDENTITY_TABLE, () -> query(reader, payments.transfer())); + bindIdentity(payments.transfer(), transfers, payments.ontology(), "transfer_id"); + assertRefused(403, HIDDEN_IDENTITY_TABLE, () -> query(reader, payments.transfer())); + assertEquals( + String.join( + "\n", + "SELECT t1.customer_id", + "FROM " + payments.schema().getName() + ".transfers t0", + "JOIN " + + payments.schema().getName() + + ".customers t1 ON t0.customer_id = t1.customer_id", + "LIMIT 50"), + query(admin(), payments.transfer(), hop(payments.partOf(), OUTGOING, payments.customer())) + .getSql()); + } + } + + @Test + void aBindingWhoseTableWasDeletedIsNoTableBindingOfItsClass(final TestNamespace ns) { + final Payments payments = + payments(ns, "deletedPayments", DatabaseServiceTestFactory.createPostgres(ns)); + final Table transfers = table(payments, "transfers", List.of("transfer_id")); + final Table ledger = table(payments, "ledger", List.of("entry_id")); + bindData(payments.transfer(), transfers, payments.ontology(), "transfer_id"); + bindData(payments.transfer(), ledger, payments.ontology(), "entry_id"); + + assertRefused(409, PICK_IDENTITY_TABLE, () -> query(admin(), payments.transfer())); + admin().tables().delete(ledger.getId()); + + assertEquals( + "SELECT transfer_id\nFROM " + payments.schema().getName() + ".transfers\nLIMIT 50", + query(admin(), payments.transfer()).getSql()); + } + + @Test + void theSqlStartsFromTheIdentityTableWhoeverAsks(final TestNamespace ns) { + final Payments payments = + payments(ns, "identityPayments", DatabaseServiceTestFactory.createPostgres(ns)); final List
tables = - IntStream.range(0, 12) + IntStream.range(0, 3) .mapToObj(index -> table(payments, "transfers_" + index, List.of("amount_" + index))) .sorted(Comparator.comparing(table -> table.getId().toString())) .toList(); - final Table twelfth = tables.getLast(); - try (var fixtures = new RdfAccessFixtures("conceptQuery12" + ns.shortPrefix())) { + final Table identity = tables.getLast(); + final String column = identity.getColumns().getFirst().getName(); + for (final Table other : tables.subList(0, 2)) { + bindData( + payments.transfer(), other, payments.ontology(), other.getColumns().getFirst().getName()); + } + bindIdentity(payments.transfer(), identity, payments.ontology(), column); + try (var fixtures = new RdfAccessFixtures("conceptQueryRoot" + ns.shortPrefix())) { final OpenMetadataClient reader = ownerReader(fixtures, Entity.TABLE); - final var current = admin().tables().get(twelfth.getId().toString(), "owners"); - admin() - .tables() - .update(twelfth.getId().toString(), current.withOwners(List.of(readerReference(reader)))); - for (final Table table : tables) { - bindData( - payments.transfer(), - table, - payments.ontology(), - table.getColumns().getFirst().getName()); - } + own(tables.getFirst(), reader); - final OntologyConceptQuery visible = query(reader, payments.transfer()); + assertRefused(403, HIDDEN_IDENTITY_TABLE, () -> query(reader, payments.transfer())); + own(identity, reader); + final OntologyConceptQuery asReader = query(reader, payments.transfer()); + final OntologyConceptQuery asAdmin = query(admin(), payments.transfer()); assertEquals( "SELECT " - + twelfth.getColumns().getFirst().getName() + + column + "\nFROM " + payments.schema().getName() + "." - + twelfth.getName() + + identity.getName() + "\nLIMIT 50", + asReader.getSql()); + assertEquals(asReader.getSql(), asAdmin.getSql()); + assertEquals(List.of(identity.getFullyQualifiedName()), asReader.getTables()); + assertEquals(List.of(identity.getFullyQualifiedName()), asAdmin.getTables()); + } + } + + @Test + void aReaderWhoMayViewOnlyTheTwelfthTableOfAHopTargetGetsSqlOverIt(final TestNamespace ns) { + final Payments payments = + payments(ns, "twelfthPayments", DatabaseServiceTestFactory.createPostgres(ns)); + final Table customers = table(payments, "customers", List.of("customer_id")); + final List
tables = + IntStream.range(0, 12) + .mapToObj( + index -> + table( + payments, + "transfers_" + index, + List.of("amount_" + index, "customer_id"), + foreignKey("customer_id", customers, "customer_id"))) + .sorted(Comparator.comparing(table -> table.getId().toString())) + .toList(); + final Table twelfth = tables.getLast(); + bindIdentity(payments.customer(), customers, payments.ontology(), "customer_id"); + for (final Table table : tables) { + bindData( + payments.transfer(), table, payments.ontology(), table.getColumns().getFirst().getName()); + } + try (var fixtures = new RdfAccessFixtures("conceptQuery12" + ns.shortPrefix())) { + final OpenMetadataClient reader = ownerReader(fixtures, Entity.TABLE); + own(customers, reader); + own(twelfth, reader); + final OntologyConceptQueryHop toTransfers = + hop(payments.partOf(), INCOMING, payments.transfer()); + + final OntologyConceptQuery visible = query(reader, payments.customer(), toTransfers); + + assertEquals( + String.join( + "\n", + "SELECT t1." + twelfth.getColumns().getFirst().getName(), + "FROM " + payments.schema().getName() + ".customers t0", + "JOIN " + + payments.schema().getName() + + "." + + twelfth.getName() + + " t1 ON t0.customer_id = t1.customer_id", + "LIMIT 50"), visible.getSql()); - assertEquals(List.of(twelfth.getFullyQualifiedName()), visible.getTables()); assertEquals( - tables.getFirst().getFullyQualifiedName(), - query(admin(), payments.transfer()).getTables().getFirst()); + List.of(customers.getFullyQualifiedName(), twelfth.getFullyQualifiedName()), + visible.getTables()); + assertEquals( + List.of(customers.getFullyQualifiedName(), tables.getFirst().getFullyQualifiedName()), + query(admin(), payments.customer(), toTransfers).getTables()); } } @@ -306,8 +471,9 @@ void anInverseTheReaderMayViewAsItsOwnerLabelsAnIncomingHop(final TestNamespace + payments.schema().getName() + ".accounts t0\nJOIN " + payments.schema().getName() - + ".customers t1 ON t0.customer_id = t1.customer_id -- kept by\nLIMIT 50", + + ".customers t1 ON t0.customer_id = t1.customer_id\nLIMIT 50", incoming.getSql()); + assertEquals(List.of("kept by"), labels(incoming)); } } @@ -322,12 +488,14 @@ void aBoundInverseOrientsAKeyFromATableToItself(final TestNamespace ns) { assertEquals( fixture.managedBy().getIri(), admin().ontologyProperties().get(fixture.manages().getId().toString()).getInverse()); - assertEquals( - fixture.joinedOn("t0.employee_id = t1.manager_id -- manages"), - query(admin(), employee, hop(fixture.manages(), OUTGOING, employee)).getSql()); - assertEquals( - fixture.joinedOn("t0.manager_id = t1.employee_id -- managed by"), - query(admin(), employee, hop(fixture.managedBy(), OUTGOING, employee)).getSql()); + final OntologyConceptQuery overManages = + query(admin(), employee, hop(fixture.manages(), OUTGOING, employee)); + final OntologyConceptQuery overManagedBy = + query(admin(), employee, hop(fixture.managedBy(), OUTGOING, employee)); + assertEquals(fixture.joinedOn("t0.employee_id = t1.manager_id"), overManages.getSql()); + assertEquals(List.of("manages"), labels(overManages)); + assertEquals(fixture.joinedOn("t0.manager_id = t1.employee_id"), overManagedBy.getSql()); + assertEquals(List.of("managed by"), labels(overManagedBy)); } @Test @@ -335,12 +503,15 @@ void twoHopsThatDifferOnlyInDirectionJoinTheWayEachChipReads(final TestNamespace final SelfKey fixture = selfKeyEmployees(ns, "directionPayments"); final OntologyConcept employee = fixture.employee(); - assertEquals( - fixture.joinedOn("t0.manager_id = t1.employee_id -- managed by"), - query(admin(), employee, hop(fixture.managedBy(), OUTGOING, employee)).getSql()); - assertEquals( - fixture.joinedOn("t0.employee_id = t1.manager_id -- manages"), - query(admin(), employee, hop(fixture.managedBy(), INCOMING, employee)).getSql()); + final OntologyConceptQuery outgoing = + query(admin(), employee, hop(fixture.managedBy(), OUTGOING, employee)); + final OntologyConceptQuery incoming = + query(admin(), employee, hop(fixture.managedBy(), INCOMING, employee)); + + assertEquals(fixture.joinedOn("t0.manager_id = t1.employee_id"), outgoing.getSql()); + assertEquals(List.of("managed by"), labels(outgoing)); + assertEquals(fixture.joinedOn("t0.employee_id = t1.manager_id"), incoming.getSql()); + assertEquals(List.of("manages"), labels(incoming)); } private record SelfKey( @@ -383,7 +554,9 @@ private SelfKey selfKeyEmployees(final TestNamespace ns, final String name) { bind( employee, employees, - List.of(column(employeeId, "employee_id"), column(managedBy, "manager_id")), + List.of( + column(employeeId, "employee_id"), + relation(managedBy, "manager_id", employees, "employee_id")), 0L); return new SelfKey(employee, managedBy, manages, payments.schema().getName()); } @@ -401,6 +574,66 @@ private static OpenMetadataClient ownerOnlyPropertyReader(final RdfAccessFixture return client(fixtures.userToken("propertyOwner", List.of(role.getId()))); } + @Test + void theSqlKeepsOnlyTheRowsThatTheRowFilterOfATableKeeps(final TestNamespace ns) { + final Payments payments = + payments(ns, "filteredPayments", DatabaseServiceTestFactory.createPostgres(ns)); + final Table transfers = table(payments, "transfers", List.of("transfer_id", "status")); + bindFiltered(payments, transfers, "status", OntologyRowFilterOperator.NOT_EQUALS, "a'b\\c:d"); + + final OntologyConceptQuery filtered = query(admin(), payments.transfer()); + + final String selected = + "SELECT transfer_id\nFROM " + payments.schema().getName() + ".transfers\n"; + assertEquals(selected + "WHERE status <> E'a''b\\\\c:d'\nLIMIT 50", filtered.getSql()); + assertEquals(selected + "WHERE status <> E'a''b\\\\c\\:d'\nLIMIT 50", filtered.getEscapedSql()); + } + + @Test + void aStoredRowFilterWhoseValueNoLongerParsesIsABadRequestThatNamesTheTable( + final TestNamespace ns) { + final Payments payments = + payments(ns, "retypedPayments", DatabaseServiceTestFactory.createPostgres(ns)); + final Table transfers = table(payments, "transfers", List.of("transfer_id", "qty")); + bindFiltered(payments, transfers, "qty", OntologyRowFilterOperator.EQUALS, "abc"); + admin() + .tables() + .createOrUpdate( + new CreateTable() + .withName(transfers.getName()) + .withDatabaseSchema(payments.schema().getFullyQualifiedName()) + .withColumns( + List.of( + new Column().withName("transfer_id").withDataType(ColumnDataType.STRING), + new Column().withName("qty").withDataType(ColumnDataType.INT)))); + + assertBadRequest( + "The row filter of " + + transfers.getFullyQualifiedName() + + " no longer applies. The value for column qty does not parse as INT: a whole number" + + " is written in ASCII digits, with a leading minus sign when negative and no leading" + + " zeros", + () -> query(admin(), payments.transfer())); + } + + /** Binds {@code transfer_id} of the table to the transfer class, under a row filter. */ + private static void bindFiltered( + final Payments payments, + final Table transfers, + final String column, + final OntologyRowFilterOperator operator, + final String value) { + final OntologyProperty transferId = + dataProperty(payments.ontology(), "transferId", payments.transfer(), false); + put( + admin(), + payments.transfer(), + binding(transfers) + .withColumns(List.of(column(transferId, "transfer_id"))) + .withRowFilter(filter(column, operator, value)), + 0L); + } + @Test void generatingSqlWritesNothing(final TestNamespace ns) { final Payments payments = @@ -505,26 +738,77 @@ private static void bindData( bind( concept, table, - List.of(columns).stream() - .map( - name -> - column( - dataProperty( - ontology, - "p" + UUID.randomUUID().toString().substring(0, 8), - concept, - false), - name)) - .toList(), + dataColumns(concept, ontology, columns), + bindings(concept, "").getRevision()); + } + + /** Binds the table as the identity table of the concept, keyed by the first of the columns. */ + private static void bindIdentity( + final OntologyConcept concept, + final Table table, + final Ontology ontology, + final String... columns) { + bindAs(OntologyBindingRole.IDENTITY, concept, table, ontology, columns); + } + + /** Binds the table to the concept in a role, keyed by the first of the columns. */ + private static void bindAs( + final OntologyBindingRole role, + final OntologyConcept concept, + final Table table, + final Ontology ontology, + final String... columns) { + bind( + concept, + binding(table, role, columns[0]).withColumns(dataColumns(concept, ontology, columns)), bindings(concept, "").getRevision()); } + /** Each column bound to a data property of its own. */ + private static List dataColumns( + final OntologyConcept concept, final Ontology ontology, final String... columns) { + return List.of(columns).stream() + .map( + name -> + column( + dataProperty( + ontology, + "p" + UUID.randomUUID().toString().substring(0, 8), + concept, + false), + name)) + .toList(); + } + + /** Makes the reader the owner of the table, which a rule on ownership then shows them. */ + private static void own(final Table table, final OpenMetadataClient reader) { + final var current = admin().tables().get(table.getId().toString(), "owners"); + admin() + .tables() + .update(table.getId().toString(), current.withOwners(List.of(readerReference(reader)))); + } + private static OntologyColumnBinding column(final OntologyProperty property, final String name) { return new OntologyColumnBinding() .withPropertyId(property.getId()) .withColumnPath(List.of(name)); } + /** A column bound to an OBJECT property, joined to the key of the table it points at. */ + private static OntologyColumnBinding relation( + final OntologyProperty property, final String name, final Table target, final String key) { + return column(property, name) + .withJoin( + new OntologyColumnJoin() + .withTargetAssetId(target.getId()) + .withStatus(OntologyJoinStatus.CONFIRMED) + .withOn( + List.of( + new OntologyJoinColumnPair() + .withChild(List.of(name)) + .withParent(List.of(key))))); + } + private static OntologyProperty dataProperty( final Ontology ontology, final String name, @@ -592,6 +876,11 @@ private static OntologyConceptQuery query( OntologyConceptQuery.class); } + /** The relation label of each hop, which the response carries beside the SQL. */ + private static List labels(final OntologyConceptQuery query) { + return query.getHops().stream().map(OntologyConceptQueryHop::getLabel).toList(); + } + private static void assertBadRequest(final String message, final Runnable request) { final OpenMetadataException failure = assertThrows(OpenMetadataException.class, request::run); assertEquals(400, failure.getStatusCode()); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedBindingShapeIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedBindingShapeIT.java new file mode 100644 index 000000000000..fa44b11e32c4 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedBindingShapeIT.java @@ -0,0 +1,188 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; +import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.boundColumn; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedDataProperty; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedShape; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.net.URI; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.DeclineOntologyDefinitions; +import org.openmetadata.schema.api.data.MatchOntologyDeclinedDefinitions; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyDeclinedDefinition; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionMatch; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionPage; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; + +/** + * Declining a table binding and a shape of a draft, and matching later drafts against them. The + * same binding and shape under fresh ids match, and one that changed does not. + */ +@Execution(ExecutionMode.SAME_THREAD) +@ExtendWith(TestNamespaceExtension.class) +public class OntologyDeclinedBindingShapeIT extends BaseOntologyApprovalIT { + private static final URI TOTAL = URI.create("urn:total"); + + @Test + void aDeclinedBindingAndShapeMatchUnderFreshIdsAndAChangedOneDoesNot(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final DatabaseSchema schema = schema(ns); + final Table orders = orders(schema, "orders"); + final Table archive = orders(schema, "orders_archive"); + final OntologyChangeOperation binding = binds(keyed(orders, "order_id")); + final OntologyChangeOperation shape = shape(ontology, 1); + final OntologyChangeSet proposal = proposal(ns, ontology, binding, shape); + + final OntologyDeclinedDefinitionPage declined = + admin() + .ontologyDeclinedDefinitions() + .decline(ontology.getId(), decline(proposal, binding, shape)); + + assertEquals( + List.of( + OntologyChangeOperationType.UPSERT_BINDING, OntologyChangeOperationType.UPSERT_SHAPE), + declined.getRecords().stream().map(OntologyDeclinedDefinition::getOperationType).toList()); + assertEquals( + List.of(ORDER, ORDER), + declined.getRecords().stream().map(OntologyDeclinedDefinition::getIri).toList()); + final List matches = + match( + ontology, + binds(keyed(orders, "order_id")), + shape(ontology, 1), + binds(keyed(archive, "order_id")), + binds(keyed(orders, "customer_id")), + shape(ontology, 2), + binds( + keyed(orders, "order_id").withColumns(List.of(boundColumn(TOTAL, "order_id")))), + binds(keyed(orders, "order_id").withRole(OntologyBindingRole.CONTRIBUTING)), + binds(keyed(orders, "order_id").withRowFilter(statusFilter()))) + .getMatches(); + assertEquals( + List.of(true, true, false, false, false, true, false, false), + matches.stream().map(OntologyDeclinedDefinitionMatch::getDeclined).toList()); + assertEquals(binding.getId(), matches.get(0).getRecord().getOperationId()); + assertEquals(shape.getId(), matches.get(1).getRecord().getOperationId()); + assertNotEquals(matches.get(0).getPayloadDigest(), matches.get(2).getPayloadDigest()); + assertNull(matches.get(4).getRecord()); + } + + @Test + void decliningABindingTwiceKeepsOneRecord(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final Table orders = orders(schema(ns), "orders"); + final OntologyChangeOperation binding = binds(keyed(orders, "order_id")); + final OntologyChangeSet proposal = proposal(ns, ontology, binding); + + admin().ontologyDeclinedDefinitions().decline(ontology.getId(), decline(proposal, binding)); + admin().ontologyDeclinedDefinitions().decline(ontology.getId(), decline(proposal, binding)); + + assertEquals( + 1, + admin() + .ontologyDeclinedDefinitions() + .list(ontology.getId(), null, null) + .getRecords() + .size()); + } + + private static OntologyChangeSet proposal( + final TestNamespace ns, final Ontology ontology, final OntologyChangeOperation... held) { + final var total = proposedDataProperty(ontology, "total", TOTAL, ORDER); + final OntologyChangeOperation[] operations = new OntologyChangeOperation[held.length + 1]; + operations[0] = creates(total); + System.arraycopy(held, 0, operations, 1, held.length); + return draft(admin(), ns, ontology, operations); + } + + private static OntologyChangeOperation shape(final Ontology ontology, final int minCount) { + final var shape = proposedShape(ontology, "orderShape", ORDER, TOTAL); + shape.getConstraints().getFirst().setMinCount(minCount); + return creates(shape); + } + + private static OntologyRowFilter statusFilter() { + return new OntologyRowFilter() + .withColumn(List.of("customer_id")) + .withOperator(OntologyRowFilterOperator.IS_NOT_NULL); + } + + private static OntologyBindingChange keyed(final Table table, final String key) { + return bindingOf(ORDER, table) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of(key))); + } + + private static Table orders(final DatabaseSchema schema, final String name) { + return table( + schema, + name, + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT)); + } + + private static DeclineOntologyDefinitions decline( + final OntologyChangeSet draft, final OntologyChangeOperation... operations) { + final LinkedHashSet ids = new LinkedHashSet<>(); + for (final OntologyChangeOperation operation : operations) { + ids.add(operation.getId()); + } + return new DeclineOntologyDefinitions() + .withChangeSetId(draft.getId()) + .withOperationIds(ids) + .withReason("wrong table"); + } + + private static org.openmetadata.schema.type.OntologyDeclinedDefinitionMatches match( + final Ontology ontology, final OntologyChangeOperation... candidates) { + return admin() + .ontologyDeclinedDefinitions() + .match( + ontology.getId(), + new MatchOntologyDeclinedDefinitions().withCandidates(List.of(candidates))); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionIT.java new file mode 100644 index 000000000000..ab1e05a603b2 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionIT.java @@ -0,0 +1,665 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Supplier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.util.OssTestServer; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.AcquireOntologyEditLock; +import org.openmetadata.schema.api.data.ApplyOntologyChangeSet; +import org.openmetadata.schema.api.data.CreateOntologyChangeSet; +import org.openmetadata.schema.api.data.DeclineOntologyDefinitions; +import org.openmetadata.schema.api.data.MatchOntologyDeclinedDefinitions; +import org.openmetadata.schema.api.data.OntologyChangeSetCommand; +import org.openmetadata.schema.api.data.UpdateOntologyChangeSet; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationState; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyChangeSetState; +import org.openmetadata.schema.type.OntologyConceptType; +import org.openmetadata.schema.type.OntologyDeclinedDefinition; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionMatches; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionPage; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.type.OntologyEditLock; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * Declining the definitions of a draft, matching a later draft against them, and refusing to narrow + * a draft to operations that need a class only a removed operation creates. + */ +@Execution(ExecutionMode.SAME_THREAD) +@ExtendWith(TestNamespaceExtension.class) +public class OntologyDeclinedDefinitionIT extends BaseOntologyApprovalIT { + private static final URI STRING = URI.create("http://www.w3.org/2001/XMLSchema#string"); + + @Test + void decliningTwoOperationsOfADiscardedDraftWritesTwoRecordsAndDecliningAgainChangesNothing( + final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "declined"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation customer = concept(ontology, "Customer", "A buyer"); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order, customer)); + client + .ontologyChangeSets() + .discard(draft.getId(), new OntologyChangeSetCommand().withLease(lease(draft))); + + final OntologyDeclinedDefinitionPage first = + client + .ontologyDeclinedDefinitions() + .decline( + ontology.getId(), decline(draft, "out of scope", order.getId(), customer.getId())); + final OntologyDeclinedDefinitionPage again = + client + .ontologyDeclinedDefinitions() + .decline( + ontology.getId(), + decline(draft, "a different reason", order.getId(), customer.getId())); + + assertEquals(2, first.getRecords().size()); + assertEquals(first.getRecords(), again.getRecords()); + final OntologyDeclinedDefinition orderRecord = first.getRecords().getFirst(); + assertEquals(ontology.getId(), orderRecord.getOntologyId()); + assertEquals(OntologyChangeOperationType.UPSERT_CONCEPT, orderRecord.getOperationType()); + assertEquals(order.getConcept().getIri(), orderRecord.getIri()); + assertEquals(64, orderRecord.getPayloadDigest().length()); + assertEquals("out of scope", orderRecord.getReason()); + assertEquals(draft.getId(), orderRecord.getChangeSetId()); + assertEquals(order.getId(), orderRecord.getOperationId()); + assertFalse(orderRecord.getDeclinedBy().isBlank()); + final OntologyDeclinedDefinitionPage listed = + client.ontologyDeclinedDefinitions().list(ontology.getId(), null, null); + assertEquals(2, listed.getRecords().size()); + assertEquals(null, listed.getAfter()); + } + + @Test + void listsInPagesWithACursor(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "paged"); + final List operations = + List.of( + concept(ontology, "A", "a"), concept(ontology, "B", "b"), concept(ontology, "C", "c")); + final OntologyChangeSet draft = draft(ns, ontology, operations); + client + .ontologyDeclinedDefinitions() + .decline( + ontology.getId(), + decline( + draft, + null, + operations.stream().map(OntologyChangeOperation::getId).toArray(UUID[]::new))); + + final OntologyDeclinedDefinitionPage first = + client.ontologyDeclinedDefinitions().list(ontology.getId(), 2, null); + final OntologyDeclinedDefinitionPage second = + client.ontologyDeclinedDefinitions().list(ontology.getId(), 2, first.getAfter()); + + assertEquals(2, first.getRecords().size()); + assertEquals(1, second.getRecords().size()); + assertEquals(null, second.getAfter()); + assertEquals( + 3, + java.util.stream.Stream.concat(first.getRecords().stream(), second.getRecords().stream()) + .map(OntologyDeclinedDefinition::getOperationId) + .distinct() + .count()); + } + + @Test + void aNewDraftBuiltFromTheSameDefinitionsWithFreshIdsMatchesBoth(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "rematched"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation customer = concept(ontology, "Customer", "A buyer"); + final OntologyChangeSet first = draft(ns, ontology, List.of(order, customer)); + client + .ontologyDeclinedDefinitions() + .decline(ontology.getId(), decline(first, null, order.getId(), customer.getId())); + + final OntologyChangeOperation freshOrder = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation freshCustomer = concept(ontology, "Customer", "A buyer"); + final OntologyDeclinedDefinitionMatches matches = + client + .ontologyDeclinedDefinitions() + .match(ontology.getId(), candidates(freshOrder, freshCustomer)); + + assertEquals( + List.of(freshOrder.getId(), freshCustomer.getId()), + matches.getMatches().stream().map(match -> match.getOperationId()).toList()); + assertTrue(matches.getMatches().stream().allMatch(match -> match.getDeclined())); + assertEquals(order.getId(), matches.getMatches().get(0).getRecord().getOperationId()); + assertEquals(customer.getId(), matches.getMatches().get(1).getRecord().getOperationId()); + assertEquals( + matches.getMatches().get(0).getPayloadDigest(), + matches.getMatches().get(0).getRecord().getPayloadDigest()); + } + + @Test + void aChangedDefinitionDoesNotMatch(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "changed"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order)); + client + .ontologyDeclinedDefinitions() + .decline(ontology.getId(), decline(draft, null, order.getId())); + + final OntologyChangeOperation relabeled = concept(ontology, "Order", "A purchase order"); + final OntologyDeclinedDefinitionMatches matches = + client.ontologyDeclinedDefinitions().match(ontology.getId(), candidates(relabeled)); + + assertFalse(matches.getMatches().getFirst().getDeclined()); + assertEquals(null, matches.getMatches().getFirst().getRecord()); + assertEquals(order.getConcept().getIri(), matches.getMatches().getFirst().getIri()); + } + + @Test + void aCallerWithoutEditRightsCannotDeclineAndOneWithoutReadRightsCannotListOrMatch( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "guarded"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order)); + final OpenMetadataClient consumer = SdkClients.user2Client(); + + assertEquals( + 403, + statusOf( + () -> + consumer + .ontologyDeclinedDefinitions() + .decline(ontology.getId(), decline(draft, null, order.getId())))); + assertEquals( + 403, + statusOf(() -> consumer.ontologyDeclinedDefinitions().list(ontology.getId(), null, null))); + assertEquals( + 403, + statusOf( + () -> + consumer.ontologyDeclinedDefinitions().match(ontology.getId(), candidates(order)))); + assertTrue( + SdkClients.adminClient() + .ontologyDeclinedDefinitions() + .list(ontology.getId(), null, null) + .getRecords() + .isEmpty(), + "a refused decline records nothing"); + } + + @Test + void refusesAnOperationOfAnotherChangeSetAndAChangeSetOfAnotherOntology(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "scoped"); + final Ontology other = createOntology(ns, "elsewhere"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order)); + + assertEquals( + 400, + statusOf( + () -> + client + .ontologyDeclinedDefinitions() + .decline(ontology.getId(), decline(draft, null, UUID.randomUUID())))); + assertEquals( + 400, + statusOf( + () -> + client + .ontologyDeclinedDefinitions() + .decline(other.getId(), decline(draft, null, order.getId())))); + } + + @Test + void narrowingToAPropertyWithoutTheClassItNeedsIsRefusedWithTheClassIri(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "lost"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation total = property(ontology, "total", order.getConcept().getIri()); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order, total)); + final OntologyEditLeaseToken lease = lease(draft); + + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> + client + .ontologyChangeSets() + .replaceOperations(draft.getId(), narrowTo(lease, total))); + + assertEquals(400, refusal.getStatusCode()); + assertTrue(refusal.getMessage().contains(order.getConcept().getIri().toString())); + assertEquals( + 2, + client + .ontologyChangeSets() + .get(draft.getId().toString(), "operations") + .getOperations() + .size(), + "the refused replacement leaves the draft as it was"); + } + + @Test + void narrowingToAPropertyWhoseClassAlreadyExistsOrIsKeptIsAcceptedAndApplies( + final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "kept"); + final URI existing = URI.create("https://example.org/model/" + ns.shortPrefix() + "/Existing"); + declareClass(ontology, ns.prefix("Existing"), existing); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation customer = concept(ontology, "Customer", "A buyer"); + final OntologyChangeOperation placedBy = + property(ontology, "placedBy", order.getConcept().getIri()); + final OntologyChangeOperation onExisting = property(ontology, "tag", existing); + final OntologyChangeSet draft = + draft(ns, ontology, List.of(order, customer, placedBy, onExisting)); + final OntologyEditLeaseToken lease = lease(draft); + + final OntologyChangeSet narrowed = + client + .ontologyChangeSets() + .replaceOperations(draft.getId(), narrowTo(lease, order, placedBy, onExisting)); + final OntologyChangeSet applied = + client + .ontologyChangeSets() + .apply(draft.getId(), new ApplyOntologyChangeSet().withLease(lease)); + + assertEquals(3, narrowed.getOperations().size()); + assertEquals(OntologyChangeSetState.APPLIED, applied.getState()); + assertEquals(3, applied.getApplicationResult().getOperationsApplied()); + } + + @Test + void definitionsSentWithExplicitNullsAreMatchedAgainWithFreshIdsAndTheSameNulls( + final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "nulls"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation total = property(ontology, "total", order.getConcept().getIri()); + final OntologyChangeSet draft = draftSentWithNulls(ns, ontology, List.of(order, total)); + client + .ontologyDeclinedDefinitions() + .decline(ontology.getId(), decline(draft, null, order.getId(), total.getId())); + + final OntologyChangeOperation freshOrder = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation freshTotal = + property(ontology, "total", order.getConcept().getIri()); + final String withNulls = matchSentWithNulls(ontology, List.of(freshOrder, freshTotal)); + final String withoutThem = + client + .getHttpClient() + .executeForString( + HttpMethod.POST, + DECLINED + ontology.getId() + "/declinedDefinitions/match", + candidates(freshOrder, freshTotal)); + + assertEquals(List.of(true, true), declinedFlags(withNulls)); + assertEquals(List.of(true, true), declinedFlags(withoutThem)); + } + + @Test + void undoNarrowRedoAndApplyIsRefusedAtTheNarrowNamingTheClass(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "undone"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation total = property(ontology, "total", order.getConcept().getIri()); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order, total)); + final OntologyEditLeaseToken lease = lease(draft); + final OntologyChangeSetCommand command = new OntologyChangeSetCommand().withLease(lease); + client.ontologyChangeSets().undo(draft.getId(), command); + + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> + client + .ontologyChangeSets() + .replaceOperations( + draft.getId(), + new UpdateOntologyChangeSet() + .withLease(lease) + .withOperations(List.of(total)) + .withUndoCursor(0))); + + assertEquals(400, refusal.getStatusCode()); + assertTrue( + refusal + .getMessage() + .contains( + "Ontology operations need classes that only removed operations create: " + + order.getConcept().getIri() + + "."), + refusal.getMessage()); + final OntologyChangeSet unchanged = + client.ontologyChangeSets().get(draft.getId().toString(), "operations"); + assertEquals(2, unchanged.getOperations().size()); + assertEquals(1, unchanged.getUndoCursor()); + } + + @Test + void aClassKeptButUndoneIsRefusedWithTheMessageForAnUndoneClass(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "cursor"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation total = property(ontology, "total", order.getConcept().getIri()); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order, total)); + final OntologyEditLeaseToken lease = lease(draft); + + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> + client + .ontologyChangeSets() + .replaceOperations( + draft.getId(), + new UpdateOntologyChangeSet() + .withLease(lease) + .withOperations(List.of(total, order)) + .withUndoCursor(1))); + + assertEquals(400, refusal.getStatusCode()); + assertTrue( + refusal + .getMessage() + .contains( + "Ontology operations need classes that only kept operations past the undo cursor" + + " create: " + + order.getConcept().getIri() + + ". Move the undo cursor past the operation that creates each class, or" + + " remove the operations that need it."), + refusal.getMessage()); + } + + @Test + void aPermanentDeleteOfAnOntologyRemovesItsDeclinedDefinitions(final TestNamespace ns) { + assumeFalse(OssTestServer.isExternalMode(), "Counts the embedded server's rows"); + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = client.ontologies().create(request(ns).withName(ns.prefix("purged"))); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeOperation customer = concept(ontology, "Customer", "A buyer"); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order, customer)); + client + .ontologyDeclinedDefinitions() + .decline(ontology.getId(), decline(draft, null, order.getId(), customer.getId())); + assertEquals(2, declinedRows(ontology)); + + client + .ontologies() + .delete(ontology.getId().toString(), Map.of("recursive", "true", "hardDelete", "true")); + + assertEquals(0, declinedRows(ontology)); + } + + @Test + void aSoftDeleteKeepsTheDeclinedDefinitionsAndARestoreServesThemAgain(final TestNamespace ns) { + assumeFalse(OssTestServer.isExternalMode(), "Counts the embedded server's rows"); + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns, "archived"); + final OntologyChangeOperation order = concept(ontology, "Order", "A purchase"); + final OntologyChangeSet draft = draft(ns, ontology, List.of(order)); + client + .ontologyDeclinedDefinitions() + .decline(ontology.getId(), decline(draft, null, order.getId())); + + client.ontologies().delete(ontology.getId().toString(), Map.of("recursive", "true")); + assertEquals(1, declinedRows(ontology)); + client.ontologies().restore(ontology.getId()); + + assertEquals(1, declinedRows(ontology)); + assertEquals( + 1, + client + .ontologyDeclinedDefinitions() + .list(ontology.getId(), null, null) + .getRecords() + .size()); + assertTrue( + client + .ontologyDeclinedDefinitions() + .match(ontology.getId(), candidates(concept(ontology, "Order", "A purchase"))) + .getMatches() + .getFirst() + .getDeclined()); + } + + private static final String DECLINED = "/v1/ontologies/"; + private static final List CONCEPT_NULLS = + List.of( + "synonyms", + "conceptMappings", + "deleted", + "provider", + "abstract", + "deprecated", + "superClasses", + "subClasses", + "owners", + "replacedBy"); + private static final List PROPERTY_NULLS = + List.of( + "deleted", + "provider", + "enumValues", + "isIdentifier", + "characteristics", + "propertyChain", + "disjointWith", + "superProperties", + "deprecated", + "owners", + "unit", + "replacedBy"); + + private static int declinedRows(final Ontology ontology) { + return Entity.getCollectionDAO() + .ontologyDeclinedDefinitionDAO() + .listAfter(ontology.getId().toString(), false, 0L, "", "", "", 100) + .size(); + } + + /** The operations as a generator that writes every optional field as null sends them. */ + private static ArrayNode operationsWithNulls(final List operations) { + final ArrayNode nodes = JsonUtils.getObjectMapper().createArrayNode(); + for (final OntologyChangeOperation operation : operations) { + final ObjectNode node = (ObjectNode) JsonUtils.valueToTree(operation); + if (node.has("concept")) { + CONCEPT_NULLS.forEach(field -> ((ObjectNode) node.get("concept")).putNull(field)); + } + if (node.has("property")) { + PROPERTY_NULLS.forEach(field -> ((ObjectNode) node.get("property")).putNull(field)); + } + nodes.add(node); + } + return nodes; + } + + private static OntologyChangeSet draftSentWithNulls( + final TestNamespace ns, + final Ontology ontology, + final List operations) { + final var client = SdkClients.adminClient(); + final ObjectNode request = + (ObjectNode) + JsonUtils.valueToTree( + new CreateOntologyChangeSet() + .withName(ns.prefix("draft") + UUID.randomUUID()) + .withDisplayName("Proposed definitions") + .withDescription("Definitions proposed for review") + .withOntology(ontology.getFullyQualifiedName()) + .withBaseWorkingRevision( + client.ontologies().state(ontology.getId()).getWorkingRevision())); + request.set("operations", operationsWithNulls(operations)); + final String created = + client.getHttpClient().executeForString(HttpMethod.POST, "/v1/ontologyChangeSets", request); + return ns.trackRoot("ontologyChangeSet", JsonUtils.readValue(created, OntologyChangeSet.class)); + } + + private static String matchSentWithNulls( + final Ontology ontology, final List operations) { + final ObjectNode request = JsonUtils.getObjectNode(); + request.set("candidates", operationsWithNulls(operations)); + return SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.POST, DECLINED + ontology.getId() + "/declinedDefinitions/match", request); + } + + private static List declinedFlags(final String matches) { + final List flags = new java.util.ArrayList<>(); + JsonUtils.readTree(matches) + .path("matches") + .forEach(match -> flags.add(match.path("declined").asBoolean())); + return flags; + } + + private static UpdateOntologyChangeSet narrowTo( + final OntologyEditLeaseToken lease, final OntologyChangeOperation... kept) { + return new UpdateOntologyChangeSet() + .withLease(lease) + .withOperations(List.of(kept)) + .withUndoCursor(kept.length); + } + + private static DeclineOntologyDefinitions decline( + final OntologyChangeSet draft, final String reason, final UUID... operationIds) { + return new DeclineOntologyDefinitions() + .withChangeSetId(draft.getId()) + .withOperationIds(new java.util.LinkedHashSet<>(List.of(operationIds))) + .withReason(reason); + } + + private static MatchOntologyDeclinedDefinitions candidates( + final OntologyChangeOperation... operations) { + return new MatchOntologyDeclinedDefinitions().withCandidates(List.of(operations)); + } + + private static OntologyChangeOperation concept( + final Ontology ontology, final String name, final String description) { + final String shortName = name; + return upsert( + OntologyChangeOperationType.UPSERT_CONCEPT, + new OntologyConcept() + .withId(UUID.randomUUID()) + .withName(shortName) + .withFullyQualifiedName(ontology.getFullyQualifiedName() + "." + shortName) + .withDescription(description) + .withOntology(ontology.getEntityReference()) + .withIri(iri(ontology, shortName)) + .withConceptType(OntologyConceptType.OWL_CLASS) + .withVersion(0.1), + null); + } + + private static OntologyChangeOperation property( + final Ontology ontology, final String name, final URI domain) { + final String shortName = name; + return upsert( + OntologyChangeOperationType.UPSERT_PROPERTY, + null, + new OntologyProperty() + .withId(UUID.randomUUID()) + .withName(shortName) + .withFullyQualifiedName(ontology.getFullyQualifiedName() + "." + shortName) + .withOntology(ontology.getEntityReference()) + .withIri(iri(ontology, shortName)) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(domain)) + .withRange(List.of(STRING)) + .withVersion(0.1)); + } + + private static OntologyChangeOperation upsert( + final OntologyChangeOperationType type, + final OntologyConcept concept, + final OntologyProperty property) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(type) + .withState(OntologyChangeOperationState.ACTIVE) + .withConcept(concept) + .withProperty(property); + } + + private static URI iri(final Ontology ontology, final String name) { + return URI.create(ontology.getIri() + "/" + name); + } + + private static OntologyChangeSet draft( + final TestNamespace ns, + final Ontology ontology, + final List operations) { + final var client = SdkClients.adminClient(); + return ns.trackRoot( + "ontologyChangeSet", + client + .ontologyChangeSets() + .create( + new CreateOntologyChangeSet() + .withName(ns.prefix("draft") + UUID.randomUUID()) + .withDisplayName("Proposed definitions") + .withDescription("Definitions proposed for review") + .withOntology(ontology.getFullyQualifiedName()) + .withBaseWorkingRevision( + client.ontologies().state(ontology.getId()).getWorkingRevision()) + .withOperations(operations))); + } + + private static OntologyEditLeaseToken lease(final OntologyChangeSet draft) { + final OntologyEditLock lock = + SdkClients.adminClient() + .ontologyEditLocks() + .acquire( + new AcquireOntologyEditLock() + .withResourceType("ontologyChangeSet") + .withResourceId(draft.getId()) + .withSessionId(UUID.randomUUID().toString()) + .withLeaseSeconds(300)); + return new OntologyEditLeaseToken() + .withSessionId(lock.getSessionId()) + .withVersion(lock.getVersion()); + } + + private static int statusOf(final Supplier call) { + return assertThrows(OpenMetadataException.class, call::get).getStatusCode(); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionReadIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionReadIT.java new file mode 100644 index 000000000000..8317864f1669 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDeclinedDefinitionReadIT.java @@ -0,0 +1,191 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyDraftFixtures.CHANGE_SETS; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * Declining answers with the IRIs of a draft's operations and stores a record for each, so it asks + * the right that reading the draft asks, and asks it before the change set is matched to the + * ontology in the path. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyDeclinedDefinitionReadIT extends BaseOntologyApprovalIT { + private static final int FORBIDDEN = 403; + private static final String HIDDEN_IRI_PREFIX = "urn:declined:Hidden"; + + private record Scene( + Ontology ontology, + OntologyChangeSet draft, + String operationId, + String iri, + OpenMetadataClient editor) { + String draftPath() { + return CHANGE_SETS + "/" + draft.getId(); + } + + String declinePath(final Ontology target) { + return "/v1/ontologies/" + target.getId() + "/declinedDefinitions"; + } + + Map request() { + return Map.of( + "changeSetId", draft.getId().toString(), + "operationIds", List.of(operationId), + "reason", "out of scope"); + } + } + + @Test + void anEditorWhoMayNotReadTheDraftIsRefusedAsTheReadIsAndStoresNoRecord(final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("decRead" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final OpenMetadataException read = + assertThrows( + OpenMetadataException.class, + () -> send(scene.editor(), HttpMethod.GET, scene.draftPath(), null)); + assertEquals(FORBIDDEN, read.getStatusCode()); + + final OpenMetadataException declined = + assertThrows( + OpenMetadataException.class, + () -> + send( + scene.editor(), + HttpMethod.POST, + scene.declinePath(scene.ontology()), + scene.request())); + + assertEquals(FORBIDDEN, declined.getStatusCode()); + assertEquals(read.getMessage(), declined.getMessage()); + assertFalse(declined.getMessage().contains(scene.iri()), declined.getMessage()); + assertEquals(0, records(scene.ontology()).size()); + } + } + + @Test + void aCallerWhoMayNotReadTheDraftIsRefusedBeforeBeingToldItBelongsToAnotherOntology( + final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("decOther" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + final Ontology other = createOntology(ns, "elsewhere"); + final OpenMetadataException read = + assertThrows( + OpenMetadataException.class, + () -> send(scene.editor(), HttpMethod.GET, scene.draftPath(), null)); + + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + send(scene.editor(), HttpMethod.POST, scene.declinePath(other), scene.request())); + final OpenMetadataException mismatch = + assertThrows( + OpenMetadataException.class, + () -> send(admin(), HttpMethod.POST, scene.declinePath(other), scene.request())); + + assertEquals(FORBIDDEN, refused.getStatusCode()); + assertEquals(read.getMessage(), refused.getMessage()); + assertEquals(400, mismatch.getStatusCode()); + assertTrue(mismatch.getMessage().contains("does not belong"), mismatch.getMessage()); + assertEquals(0, records(other).size()); + assertEquals(0, records(scene.ontology()).size()); + } + } + + @Test + void anAdminWhoMayReadTheDraftStillDeclinesItsOperation(final TestNamespace ns) { + try (var fixtures = new RdfAccessFixtures("decAdmin" + ns.shortPrefix())) { + final Scene scene = scene(ns, fixtures); + + final String declined = + send(admin(), HttpMethod.POST, scene.declinePath(scene.ontology()), scene.request()); + + assertTrue(declined.contains(scene.iri()), declined); + assertEquals(1, records(scene.ontology()).size()); + } + } + + private static JsonNode records(final Ontology ontology) { + return JsonUtils.readTree( + send( + admin(), + HttpMethod.GET, + "/v1/ontologies/" + ontology.getId() + "/declinedDefinitions", + null)) + .path("records"); + } + + /** The editor may edit change sets and holds no right on the ontology, so it may not read. */ + private static Scene scene(final TestNamespace ns, final RdfAccessFixtures fixtures) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final var edit = fixtures.allowRole(MetadataOperation.EDIT_ALL, Entity.ONTOLOGY_CHANGE_SET); + final OpenMetadataClient editor = + OntologyBindingFixtures.client(fixtures.userToken("editor", List.of(edit.getId()))); + final URI iri = URI.create(HIDDEN_IRI_PREFIX + ns.shortPrefix()); + final OntologyChangeSet draft = + OntologyDraftFixtures.draft( + admin(), + ns, + ontology, + OntologyDraftFixtures.creates( + OntologyDraftFixtures.proposedClass(ontology, "Hidden", iri))); + final JsonNode stored = + JsonUtils.readTree( + send( + admin(), + HttpMethod.GET, + CHANGE_SETS + "/" + draft.getId() + "?fields=operations", + null)); + return new Scene( + ontology, + draft, + stored.path("operations").get(0).path("id").asText(), + iri.toString(), + editor); + } + + private static String send( + final OpenMetadataClient caller, + final HttpMethod method, + final String path, + final Object body) { + return caller.getHttpClient().executeForString(method, path, body); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftFixtures.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftFixtures.java new file mode 100644 index 000000000000..6b2d1be70d9a --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftFixtures.java @@ -0,0 +1,293 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; + +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.schema.api.data.AcquireOntologyEditLock; +import org.openmetadata.schema.api.data.ApplyOntologyChangeSet; +import org.openmetadata.schema.api.data.CreateOntologyChangeSet; +import org.openmetadata.schema.api.data.OntologyChangeSetCommand; +import org.openmetadata.schema.api.data.UpdateOntologyChangeSet; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeEvidence; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationState; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyColumnBindingChange; +import org.openmetadata.schema.type.OntologyConceptType; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.type.OntologyEditLock; +import org.openmetadata.schema.type.OntologyJoinChange; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; + +/** REST helpers shared by the tests of change sets that carry table bindings, shapes and evidence. */ +final class OntologyDraftFixtures { + static final String CHANGE_SETS = "/v1/ontologyChangeSets"; + private static final URI XSD_STRING = URI.create("http://www.w3.org/2001/XMLSchema#string"); + private static final String CHANGE_SET = "ontologyChangeSet"; + private static final String EVERY_RESOURCE = "All"; + private static final int LEASE_SECONDS = 60; + + private OntologyDraftFixtures() {} + + /** + * A caller who holds every right on every resource but one. The tests give a role that denies + * the right under test, so a refusal can come from that right alone. + */ + static OpenMetadataClient callerWithout( + final RdfAccessFixtures fixtures, + final MetadataOperation denied, + final String resource, + final String condition) { + return OntologyBindingFixtures.client(tokenWithout(fixtures, denied, resource, condition)); + } + + /** The token of such a caller, for a request that no SDK client sends. */ + static String tokenWithout( + final RdfAccessFixtures fixtures, + final MetadataOperation denied, + final String resource, + final String condition) { + final var everything = fixtures.allowRole(MetadataOperation.ALL, EVERY_RESOURCE); + final var without = fixtures.denyRole(denied, resource, condition); + return fixtures.userToken("caller", List.of(everything.getId(), without.getId())); + } + + static OntologyChangeSet draft( + final OpenMetadataClient author, + final TestNamespace ns, + final Ontology ontology, + final OntologyChangeOperation... operations) { + return ns.trackRoot( + CHANGE_SET, + author + .ontologyChangeSets() + .create( + new CreateOntologyChangeSet() + .withName(ns.prefix("draft") + UUID.randomUUID()) + .withDisplayName("Proposed mapping") + .withDescription("Definitions with the tables that hold them") + .withOntology(ontology.getFullyQualifiedName()) + .withBaseWorkingRevision(workingRevision(ontology)) + .withOperations(List.of(operations)))); + } + + static long workingRevision(final Ontology ontology) { + return admin().ontologies().state(ontology.getId()).getWorkingRevision(); + } + + /** The lease that every command on a draft carries. One caller holds one lease on a draft. */ + static OntologyEditLeaseToken lease( + final OpenMetadataClient caller, final OntologyChangeSet draft) { + final OntologyEditLock lock = + caller + .ontologyEditLocks() + .acquire( + new AcquireOntologyEditLock() + .withResourceType(CHANGE_SET) + .withResourceId(draft.getId()) + .withSessionId(UUID.randomUUID().toString()) + .withLeaseSeconds(LEASE_SECONDS)); + return new OntologyEditLeaseToken() + .withSessionId(lock.getSessionId()) + .withVersion(lock.getVersion()); + } + + /** + * Applies under a lease of the caller's own. A refused apply keeps its lease, so this gives the + * lease up before it reports the refusal and another caller can apply the same draft. + */ + static OntologyChangeSet apply(final OpenMetadataClient caller, final OntologyChangeSet draft) { + final OntologyEditLeaseToken lease = lease(caller, draft); + try { + return apply(caller, draft, lease); + } catch (final OpenMetadataException refused) { + release(caller, draft, lease); + throw refused; + } + } + + static OntologyChangeSet apply( + final OpenMetadataClient caller, + final OntologyChangeSet draft, + final OntologyEditLeaseToken lease) { + return caller + .ontologyChangeSets() + .apply(draft.getId(), new ApplyOntologyChangeSet().withLease(lease)); + } + + static void release( + final OpenMetadataClient caller, + final OntologyChangeSet draft, + final OntologyEditLeaseToken lease) { + caller.ontologyEditLocks().release(CHANGE_SET, draft.getId(), lease.getSessionId()); + } + + /** Replaces the operations of a draft and leaves every one of them active. */ + static OntologyChangeSet replaceOperations( + final OpenMetadataClient caller, + final OntologyChangeSet draft, + final OntologyEditLeaseToken lease, + final List operations) { + return caller + .ontologyChangeSets() + .replaceOperations( + draft.getId(), + new UpdateOntologyChangeSet() + .withLease(lease) + .withOperations(operations) + .withUndoCursor(operations.size())); + } + + static OntologyChangeSet discard(final OpenMetadataClient caller, final OntologyChangeSet draft) { + return caller + .ontologyChangeSets() + .discard(draft.getId(), new OntologyChangeSetCommand().withLease(lease(caller, draft))); + } + + static String path(final OntologyChangeSet draft) { + return CHANGE_SETS + "/" + draft.getId(); + } + + static OntologyChangeSet read(final OpenMetadataClient reader, final OntologyChangeSet draft) { + return reader.ontologyChangeSets().get(draft.getId().toString()); + } + + static OntologyChangeOperation creates(final OntologyConcept concept) { + return operation(OntologyChangeOperationType.UPSERT_CONCEPT).withConcept(concept); + } + + static OntologyChangeOperation creates(final OntologyProperty property) { + return operation(OntologyChangeOperationType.UPSERT_PROPERTY).withProperty(property); + } + + static OntologyChangeOperation creates(final OntologyShape shape) { + return operation(OntologyChangeOperationType.UPSERT_SHAPE).withShape(shape); + } + + static OntologyChangeOperation binds(final OntologyBindingChange binding) { + return operation(OntologyChangeOperationType.UPSERT_BINDING).withBinding(binding); + } + + private static OntologyChangeOperation operation(final OntologyChangeOperationType type) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(type) + .withState(OntologyChangeOperationState.ACTIVE); + } + + /** A class that a draft proposes and that the ontology does not declare yet. */ + static OntologyConcept proposedClass(final Ontology ontology, final String name, final URI iri) { + return new OntologyConcept() + .withId(UUID.randomUUID()) + .withName(name) + .withFullyQualifiedName(ontology.getFullyQualifiedName() + "." + name) + .withOntology(ontology.getEntityReference()) + .withIri(iri) + .withConceptType(OntologyConceptType.OWL_CLASS) + .withVersion(0.1); + } + + static OntologyProperty proposedDataProperty( + final Ontology ontology, final String name, final URI iri, final URI domain) { + return new OntologyProperty() + .withId(UUID.randomUUID()) + .withName(name) + .withFullyQualifiedName(ontology.getFullyQualifiedName() + "." + name) + .withOntology(ontology.getEntityReference()) + .withIri(iri) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(domain)) + .withRange(List.of(XSD_STRING)) + .withVersion(0.1); + } + + /** A shape that requires at least one value of {@code path} on every record of the class. */ + static OntologyShape proposedShape( + final Ontology ontology, final String name, final URI targetClass, final URI path) { + return new OntologyShape() + .withId(UUID.randomUUID()) + .withName(name) + .withDisplayName(name) + .withDescription("Every record states the value") + .withFullyQualifiedName(ontology.getFullyQualifiedName() + "." + name) + .withOntology(ontology.getEntityReference()) + .withTargetConcept(targetClass) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints( + List.of(new OntologyShapeConstraint().withId("stated").withPath(path).withMinCount(1))) + .withVersion(0.1); + } + + static OntologyBindingChange bindingOf(final URI classIri, final Table table) { + return new OntologyBindingChange().withClassIri(classIri).withTableId(table.getId()); + } + + static OntologyColumnBindingChange boundColumn(final URI propertyIri, final String column) { + return new OntologyColumnBindingChange() + .withPropertyIri(propertyIri) + .withColumnPath(List.of(column)); + } + + static OntologyJoinChange joinTo(final Table target, final String child, final String parent) { + return new OntologyJoinChange() + .withTargetAssetId(target.getId()) + .withOn( + List.of( + new OntologyJoinColumnPair() + .withChild(List.of(child)) + .withParent(List.of(parent)))); + } + + static OntologyChangeEvidence evidence(final Table table, final OntologyChangeEvidenceKind kind) { + return new OntologyChangeEvidence().withTableId(table.getId()).withKind(kind); + } + + /** The refusal of a request, which must answer {@code status} with {@code message} in its text. */ + static OpenMetadataException assertRefused( + final int status, final String message, final Runnable request) { + final var refused = assertThrows(OpenMetadataException.class, request::run); + assertEquals(status, refused.getStatusCode(), refused::getMessage); + assertTrue( + refused.getMessage().contains(message), + () -> "expects '" + message + "' in " + refused.getMessage()); + return refused; + } + + static void assertNotFound(final Runnable read) { + assertEquals(404, assertThrows(OpenMetadataException.class, read::run).getStatusCode()); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftScene.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftScene.java new file mode 100644 index 000000000000..6ec714c1bb51 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyDraftScene.java @@ -0,0 +1,99 @@ +/* + * 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; + +import static org.openmetadata.it.tests.OntologyDraftFixtures.CHANGE_SETS; +import static org.openmetadata.it.tests.OntologyDraftFixtures.bindingOf; +import static org.openmetadata.it.tests.OntologyDraftFixtures.binds; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.lease; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyDraftFixtures.replaceOperations; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.util.ArrayList; +import java.util.List; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.sdk.network.HttpMethod; + +/** + * A draft with one table binding, built and run by an admin, for tests in other packages that + * watch what leaves the server about it. Its table, key column and filter value are strings no + * other draft holds. + */ +public final class OntologyDraftScene extends BaseOntologyApprovalIT { + public static final String COLUMN = "scene_key_column_4417"; + public static final String VALUE = "scene_filter_value_4417"; + + /** The draft with the table it binds, and the lease its builder holds. */ + public record Built(OntologyChangeSet draft, Table table, Ontology ontology) {} + + private OntologyDraftScene() {} + + public static Built build(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + declareClass(ontology, "Order", ORDER); + final Table table = table(schema(ns), "scenehidden", column(COLUMN, ColumnDataType.VARCHAR)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + binds( + bindingOf(ORDER, table) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of(COLUMN))) + .withRowFilter(filter(COLUMN, OntologyRowFilterOperator.EQUALS, VALUE)))); + return new Built(draft, table, ontology); + } + + /** Adds a class to the draft in a second save, then applies it. */ + public static OntologyChangeSet saveAgainAndApply(final Built scene) { + final OntologyEditLeaseToken lease = lease(admin(), scene.draft()); + final List operations = new ArrayList<>(scene.draft().getOperations()); + operations.add(creates(proposedClass(scene.ontology(), "Customer", CUSTOMER))); + replaceOperations(admin(), scene.draft(), lease, operations); + return OntologyDraftFixtures.apply(admin(), scene.draft(), lease); + } + + /** The draft as its reader sees it, operations included. */ + public static String read(final Built scene) { + return admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, CHANGE_SETS + "/" + scene.draft().getId() + "?fields=operations", null); + } + + public static String versions(final Built scene) { + return admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, CHANGE_SETS + "/" + scene.draft().getId() + "/versions", null); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java new file mode 100644 index 000000000000..65366c6636aa --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyExpandPagingIT.java @@ -0,0 +1,291 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.ENTRIES_OF_FIRST_ACCOUNT; +import static org.openmetadata.service.ontology.OntologyMappingShapes.JSON_KEY_ITEMS; +import static org.openmetadata.service.ontology.OntologyMappingShapes.PAGED_COMPOSITE_RELATED_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.TRIPLE_KEY_ITEMS; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; + +/** + * Pages through the records one record relates to, as a client does: it reads the first rows, takes + * the key of the last row it keeps from the columns that the plan names, and sends it as {@code + * after}. The pages must follow each other with no gap and no repeat, and the engine must be the + * one to compare and to order. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyExpandPagingIT extends BaseOntologyApprovalIT { + private static final int PAGE = 25; + private static final String NOT_A_WHOLE_NUMBER = + " does not parse as INT: a whole number is written in ASCII digits, with a leading minus" + + " sign when negative and no leading zeros"; + + @Test + void threePagesOverSixtyRelatedRecordsOfATwoColumnKeyHoldEveryRecordOnce(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "threePages"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, PAGED_COMPOSITE_RELATED_KEY).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + final Ask first = PAGED_COMPOSITE_RELATED_KEY.ask("expand-inverse"); + + final OntologyStatementPlan firstPlan = fixture.ask(admin(), first, null); + final List> firstRows = OntologyShapeFixture.run(firstPlan.getSql()); + final List afterFirst = lastKey(firstPlan, firstRows.subList(0, PAGE)); + final OntologyStatementPlan secondPlan = + fixture.ask(admin(), first.withAfter(afterFirst), null); + final List> secondRows = OntologyShapeFixture.run(secondPlan.getSql()); + final List afterSecond = lastKey(secondPlan, secondRows.subList(0, PAGE)); + final OntologyStatementPlan thirdPlan = + fixture.ask(admin(), first.withAfter(afterSecond), null); + final List> thirdRows = OntologyShapeFixture.run(thirdPlan.getSql()); + + assertEquals(List.of(1, 2), firstPlan.getOrderedBy()); + assertEquals(List.of("a", "25"), afterFirst); + assertEquals(List.of("b", "10"), afterSecond); + assertEquals(entries(1, 27), firstRows); + assertEquals(entries(26, 52), secondRows); + assertEquals(entries(51, 61), thirdRows); + final List> together = new ArrayList<>(firstRows.subList(0, PAGE)); + together.addAll(secondRows.subList(0, PAGE)); + together.addAll(thirdRows); + assertEquals(entries(1, 61), together); + assertEquals(ENTRIES_OF_FIRST_ACCOUNT, together.size()); + } + } + + @Test + void aKeyThatIsAWholeNumberOrdersAsANumberAndNotAsText(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "numberKey"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, COLUMN_RELATION).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + final Ask orders = COLUMN_RELATION.ask("expand-inverse-page"); + + final List> first = + OntologyShapeFixture.run(fixture.ask(admin(), orders, null).getSql()); + final List> afterNine = + OntologyShapeFixture.run( + fixture.ask(admin(), orders.withAfter(List.of(9)), null).getSql()); + + assertEquals(orderRows(1, 27), first); + assertEquals(orderRows(10, 31), afterNine); + } + } + + @Test + void aTextKeyOfMixedCaseFollowsTheOrderOfTheEngineItsPagesAreReadFrom(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "mixedCase"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, PAGED_COMPOSITE_RELATED_KEY).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + final Ask mixed = PAGED_COMPOSITE_RELATED_KEY.ask("expand-inverse").withKey(List.of(2)); + final List> engine = + OntologyShapeFixture.run( + "SELECT " + + fixture.name("account_id") + + ", " + + fixture.name("ledger") + + ", " + + fixture.name("seq") + + " FROM " + + fixture.from("entries") + + " WHERE " + + fixture.name("account_id") + + " = 2 ORDER BY " + + fixture.name("ledger") + + ", " + + fixture.name("seq")); + + final List> all = + OntologyShapeFixture.run(fixture.ask(admin(), mixed, null).getSql()); + final List> afterX = + OntologyShapeFixture.run( + fixture.ask(admin(), mixed.withAfter(List.of("x", 2)), null).getSql()); + + assertEquals(engine, all); + assertEquals(engine.subList(2, 6), afterX); + if (fixture.family().equals("mysql")) { + assertEquals( + List.of( + List.of("2", "x", "1"), + List.of("2", "x", "2"), + List.of("2", "Y", "1"), + List.of("2", "Y", "2"), + List.of("2", "z", "1"), + List.of("2", "z", "2")), + all); + } + } + } + + @Test + void anAfterPastTheLastRelatedRecordGivesNoRow(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "pastTheEnd"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, PAGED_COMPOSITE_RELATED_KEY).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + final Ask first = PAGED_COMPOSITE_RELATED_KEY.ask("expand-inverse"); + + assertEquals( + List.of(), + OntologyShapeFixture.run( + fixture.ask(admin(), first.withAfter(List.of("b", 20)), null).getSql())); + assertEquals( + entries(60, 61), + OntologyShapeFixture.run( + fixture.ask(admin(), first.withAfter(List.of("b", 19)), null).getSql())); + } + } + + @Test + void anAfterOfTheWrongTypeOrTheWrongNumberOfPartsIsRefusedWithTheMessageOfAKey( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "badAfter"); + final Ask first = PAGED_COMPOSITE_RELATED_KEY.ask("expand-inverse"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, PAGED_COMPOSITE_RELATED_KEY)) { + fixture.bindAll(); + + assertRefused( + 400, + "The value for column seq" + NOT_A_WHOLE_NUMBER, + () -> fixture.ask(admin(), first.withAfter(List.of("a", "twenty")), DRAFT)); + assertRefused( + 400, + "The after key has 2 columns but the request gives 1 value", + () -> fixture.ask(admin(), first.withAfter(List.of("a")), DRAFT)); + assertRefused( + 400, + "The after key has 2 columns but the request gives 3 values", + () -> fixture.ask(admin(), first.withAfter(List.of("a", 1, 2)), DRAFT)); + assertRefused( + 400, + "The after key has 1 column but the request gives 2 values", + () -> + fixture.ask( + admin(), + PAGED_COMPOSITE_RELATED_KEY.ask("expand-forward").withAfter(List.of(1, 2)), + DRAFT)); + assertTrue( + fixture + .ask(admin(), first.withAfter(List.of("a", 1)), DRAFT) + .getSql() + .contains("ORDER BY")); + } + } + + @Test + void aKeyOfThreeColumnsPagesWithinOneOwnerAndNeverReadsAnotherOwnersRows(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "threeColumns"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, TRIPLE_KEY_ITEMS).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + final Ask first = TRIPLE_KEY_ITEMS.ask("expand-inverse"); + final List after = List.of("m", 5, 5); + + final OntologyStatementPlan plan = fixture.ask(admin(), first, null); + final List> all = OntologyShapeFixture.run(plan.getSql()); + final List> ownerOne = + OntologyShapeFixture.run(fixture.ask(admin(), first.withAfter(after), null).getSql()); + final List> ownerTwo = + OntologyShapeFixture.run( + fixture.ask(admin(), first.withKey(List.of(2)).withAfter(after), null).getSql()); + + assertEquals(List.of(1, 2, 3), plan.getOrderedBy()); + assertEquals(first.rows(), all); + assertEquals( + List.of( + List.of("1", "m", "5", "6.00"), + List.of("1", "m", "6", "0.00"), + List.of("1", "n", "0", "0.00")), + ownerOne); + assertEquals( + List.of( + List.of("2", "m", "5", "7.00"), + List.of("2", "m", "7", "0.00"), + List.of("2", "o", "0", "0.00")), + ownerTwo); + } + } + + @Test + void aRelatedKeyOfAColumnTypeThatTakesNoValueIsAnsweredWithoutAnOrder(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "jsonKey"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, JSON_KEY_ITEMS).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + final Ask first = JSON_KEY_ITEMS.ask("expand-inverse"); + + final OntologyStatementPlan plan = fixture.ask(admin(), first, null); + final List> rows = OntologyShapeFixture.run(plan.getSql()); + + assertEquals(2, rows.size()); + assertEquals(List.of(), plan.getOrderedBy()); + assertTrue(!plan.getSql().contains("ORDER BY"), plan.getSql()); + assertRefused( + 400, + "SQL generation does not support column type JSON of column id", + () -> fixture.ask(admin(), first.withAfter(List.of("1")), DRAFT)); + } + } + + /** The values of the columns that the plan names as the key, in the last row a client keeps. */ + private static List lastKey( + final OntologyStatementPlan plan, final List> kept) { + final List last = kept.getLast(); + return new ArrayList<>(plan.getOrderedBy().stream().map(last::get).toList()); + } + + /** The entries of account 1 from {@code from} to {@code to}, exclusive, by position in key order. */ + private static List> entries(final int from, final int to) { + final List> rows = new ArrayList<>(); + for (int position = from; position < to; position++) { + rows.add( + position <= 40 + ? List.of("1", "a", String.valueOf(position)) + : List.of("1", "b", String.valueOf(position - 40))); + } + return rows; + } + + private static List> orderRows(final int from, final int to) { + final List> rows = new ArrayList<>(); + for (int order = from; order < to; order++) { + rows.add(List.of("1", String.valueOf(order))); + } + return rows; + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyLinkCountIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyLinkCountIT.java new file mode 100644 index 000000000000..3e0a71abc26a --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyLinkCountIT.java @@ -0,0 +1,356 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.schema.api.data.OntologyStatementDirection.FORWARD; +import static org.openmetadata.schema.api.data.OntologyStatementMeasure.LINK_COUNT; +import static org.openmetadata.schema.api.data.OntologyStatementMeasure.TOP_RECORDS; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.columnPlan; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.function.Executable; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementRelation; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyLinkShapes; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * Asks the aggregate endpoint for the number of links of a relation, over each of seven mappings of + * a relation with the tables created in the database this suite runs on, and runs the statement + * that comes back. A statement must be the golden text of its engine family, and the number it + * returns must be the one that a person worked out from the rows. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyLinkCountIT extends BaseOntologyApprovalIT { + private static final String ORDER = "https://example.org/columnRelation#Order"; + private static final String CUSTOMER = "https://example.org/columnRelation#Customer"; + private static final String PLACED_BY = "https://example.org/columnRelation#placedBy"; + private static final String MEASURE_OF_A_RELATION = + "A measure belongs to a relation. A count of the class takes no measure"; + private static final String RELATION_OR_COUNT = + "An aggregate over a relation takes the relation and the direction together. A count of the" + + " class takes neither, and no related class"; + + @Test + void aRelationHeldInAColumnCountsEachDistinctPairWithAKeyOnBothSides(final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("4")), List.of(List.of("3"))), + links(ns, OntologyLinkShapes.COLUMN)); + } + + @Test + void aLinkCountsOnlyARecordThatPassesTheRowFilterOfTheClassThatBindsTheRelation( + final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("4")), List.of(List.of("2"))), + links(ns, OntologyLinkShapes.FILTERED_START)); + } + + @Test + void aRelationHeldInTwoColumnsCountsAPairOnlyWhenNeitherColumnIsNull(final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("4")), List.of(List.of("3"))), + links(ns, OntologyLinkShapes.COMPOSITE_KEY)); + } + + @Test + void aLinkTableThatRepeatsAPairCountsItOnce(final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("4")), List.of(List.of("3"))), + links(ns, OntologyLinkShapes.LINK_TABLE)); + } + + @Test + void aLinkTableOverATwoColumnKeyCountsEachPairOnce(final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("4")), List.of(List.of("3"))), + links(ns, OntologyLinkShapes.COMPOSITE_LINK_TABLE)); + } + + @Test + void aLinkTableOfAFilteredClassCountsOnlyTheLinksOfTheRecordsThatItKeeps(final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("3")), List.of(List.of("2"))), + links(ns, OntologyLinkShapes.FILTERED_LINK_TABLE)); + } + + @Test + void aTableThatHoldsARelationWithARowFilterOfItsOwnCountsOnlyTheRowsItKeeps( + final TestNamespace ns) { + assertEquals( + List.of(List.of(List.of("2")), List.of(List.of("1"))), + links(ns, OntologyLinkShapes.FILTERED_CONTRIBUTING)); + } + + @Test + void aRequestWithNoMeasureStillGivesTheRecordsThatRelateToTheMost(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "defaultMeasure"); + final Ask top = COLUMN_RELATION.ask("aggregate-inverse"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, COLUMN_RELATION).withRows()) { + fixture.bindAll(); + activate(ns, ontology); + + final OntologyStatementPlan byDefault = fixture.ask(admin(), top, null); + final OntologyStatementPlan named = fixture.ask(admin(), top.withMeasure(TOP_RECORDS), null); + + assertEquals(fixture.golden(top), byDefault.getSql() + "\n"); + assertEquals(byDefault, named); + assertEquals(TOP_RECORDS, byDefault.getMeasure()); + assertEquals(8, byDefault.getRowCap()); + assertNull( + fixture.ask(admin(), COLUMN_RELATION.ask("count"), null).getMeasure(), + "A class count names no measure"); + } + } + + @Test + void aMeasureBelongsToARelation(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "measureOfAClass"); + final Ask count = COLUMN_RELATION.ask("count"); + final Ask forward = COLUMN_RELATION.ask("aggregate-forward").withMeasure(LINK_COUNT); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + + assertRefused( + 400, + MEASURE_OF_A_RELATION, + () -> fixture.ask(admin(), count.withMeasure(LINK_COUNT), DRAFT)); + assertRefused( + 400, + MEASURE_OF_A_RELATION, + () -> fixture.ask(admin(), count.withMeasure(TOP_RECORDS), DRAFT)); + assertRefused( + 400, RELATION_OR_COUNT, () -> fixture.ask(admin(), withoutDirection(forward), DRAFT)); + assertEquals( + OntologyStatementKind.AGGREGATE, fixture.ask(admin(), forward, DRAFT).getStatement()); + } + } + + @Test + void aLinkCountIsRefusedLikeTheRecordsThatRelateToTheMost(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "linkRefusals"); + final BindingSpec orders = COLUMN_RELATION.binding("Order", "orders"); + final List both = + List.of( + COLUMN_RELATION.ask("aggregate-forward").withMeasure(LINK_COUNT), + COLUMN_RELATION.ask("aggregate-inverse").withMeasure(LINK_COUNT)); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bind(COLUMN_RELATION.binding("Customer", "customers")); + + fixture.bind(withColumns(orders, List.of(orders.columns().getFirst()))); + both.forEach( + ask -> + assertRefused( + 409, + "Relation " + + PLACED_BY + + " has no join from class " + + ORDER + + " to the identity table of class " + + CUSTOMER, + () -> fixture.ask(admin(), ask, DRAFT))); + fixture.bind( + withColumns( + orders, + List.of( + orders.columns().getFirst(), + new ColumnBindingSpec( + "placedBy", + "customer_id", + new JoinSpec( + "customers", + OntologyJoinStatus.INFERRED, + List.of("customer_id"), + List.of("id")))))); + both.forEach( + ask -> + assertRefused( + 409, + "The join of relation " + + PLACED_BY + + " from class " + + ORDER + + " to class " + + CUSTOMER + + " is not confirmed", + () -> fixture.ask(admin(), ask, DRAFT))); + fixture.bind(orders); + both.forEach( + ask -> + assertEquals( + OntologyStatementKind.AGGREGATE, + fixture.ask(admin(), ask, DRAFT).getStatement())); + } + } + + @Test + void aReaderWhoMayNotViewAnIdentityTableIsRefusedByClassAndNeverByTable(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "linkHidden"); + final Ask forward = COLUMN_RELATION.ask("aggregate-forward").withMeasure(LINK_COUNT); + final Ask inverse = COLUMN_RELATION.ask("aggregate-inverse").withMeasure(LINK_COUNT); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var first = new RdfAccessFixtures("linkCustomers" + ns.shortPrefix()); + var second = new RdfAccessFixtures("linkOrders" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient seesCustomers = ownerReader(first, Entity.TABLE); + fixture.ownedBy(seesCustomers, "customers"); + final OpenMetadataClient seesOrders = ownerReader(second, Entity.TABLE); + fixture.ownedBy(seesOrders, "orders"); + + assertRefused( + 403, + "The identity table of class " + ORDER + " is not visible to you", + () -> fixture.ask(seesCustomers, forward, null)); + assertRefused( + 403, + "The identity table of class " + CUSTOMER + " is not visible to you", + () -> fixture.ask(seesOrders, inverse, null)); + assertEquals( + OntologyStatementKind.AGGREGATE, fixture.ask(admin(), forward, null).getStatement()); + } + } + + @Test + void aReaderWhoMayNotViewTheLinkTableOfARelationIsRefusedWithoutItBeingNamed( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "linkHiddenTable"); + final Ask forward = LINK_TABLE.ask("aggregate-forward").withMeasure(LINK_COUNT); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("linkItems" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient reader = ownerReader(access, Entity.TABLE); + fixture.ownedBy(reader, "orders", "products"); + + assertRefused( + 403, + "The table that links class https://example.org/linkTable#Order to class" + + " https://example.org/linkTable#Product for relation" + + " https://example.org/linkTable#contains is not visible to you", + () -> fixture.ask(reader, forward, null)); + } + } + + /** + * Binds the shape over real tables, activates a release and asks the link count of each + * direction as a request that names no version. + * + * @return the rows of each ask, forward first + */ + private static List>> links(final TestNamespace ns, final Shape shape) { + final Ontology ontology = createOntology(ns, shape.name()); + final List>> rows = new ArrayList<>(); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, shape).withRows()) { + fixture.bindAll(); + final OntologyRelease release = current(activate(ns, ontology)); + assertAll( + shape.asks().stream() + .map(ask -> (Executable) () -> rows.add(answered(fixture, shape, ask, release)))); + } + return List.copyOf(rows); + } + + private static List> answered( + final OntologyShapeFixture fixture, + final Shape shape, + final Ask ask, + final OntologyRelease release) { + final OntologyStatementPlan plan = fixture.ask(admin(), ask, null); + final String name = shape.name() + " " + ask.name(); + + assertEquals(fixture.golden(ask), plan.getSql() + "\n", name + " sql"); + assertEquals(plan.getSql(), plan.getEscapedSql(), name + " escapedSql"); + assertFalse(plan.getSql().contains("ORDER BY"), name + " has an order"); + assertFalse(plan.getSql().contains("LIMIT"), name + " has a limit"); + assertFalse(plan.getSql().contains("TOP"), name + " has a limit"); + assertEquals(OntologyStatementKind.AGGREGATE, plan.getStatement(), name + " statement"); + assertEquals(LINK_COUNT, plan.getMeasure(), name + " measure"); + assertEquals(fixture.family(), plan.getFamily().value(), name + " family"); + assertEquals(fixture.tablesOf(ask), plan.getTables(), name + " tables"); + assertEquals(ask.columns(), columnPlan(plan.getColumns()), name + " columns"); + assertEquals(1, plan.getRowCap(), name + " rowCap"); + assertFalse(plan.getExtraRow(), name + " extraRow"); + assertEquals(relationOf(shape, ask), plan.getRelation(), name + " relation"); + assertEquals( + List.of(fixture.revisionOf(ask.type()), fixture.revisionOf(relatedTo(shape, ask))), + plan.getBindingRevisions(), + name + " revisions"); + assertEquals(release.getId(), plan.getVersion().getReleaseId(), name + " release"); + final List> rows = OntologyShapeFixture.run(plan.getSql()); + assertEquals(ask.rows(), rows, name + " rows"); + return rows; + } + + private static OntologyStatementRelation relationOf(final Shape shape, final Ask ask) { + return new OntologyStatementRelation() + .withPropertyIri(shape.iri(ask.relation())) + .withDirection(ask.direction()) + .withRelatedClassIri(shape.iri(relatedTo(shape, ask))); + } + + /** The class at the far end of the relation: its range forward and its domain going back. */ + private static String relatedTo(final Shape shape, final Ask ask) { + final PropertySpec relation = shape.property(ask.relation()); + return ask.direction() == FORWARD ? relation.range() : relation.domain(); + } + + private static Ask withoutDirection(final Ask ask) { + return new Ask( + ask.name(), + ask.kind(), + ask.type(), + ask.matchText(), + ask.key(), + ask.relation(), + null, + ask.columns(), + ask.rows(), + ask.measure()); + } + + private static BindingSpec withColumns( + final BindingSpec spec, final List columns) { + return new BindingSpec( + spec.type(), spec.table(), spec.role(), spec.key(), spec.filter(), columns); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyMappingFixtures.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyMappingFixtures.java new file mode 100644 index 000000000000..fe7f50b21217 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyMappingFixtures.java @@ -0,0 +1,260 @@ +package org.openmetadata.it.tests; + +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.openmetadata.it.factories.DatabaseSchemaTestFactory; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.CreateTable; +import org.openmetadata.schema.api.data.OntologyMappingHealth; +import org.openmetadata.schema.api.data.OntologyMappingHealthEntry; +import org.openmetadata.schema.api.data.UpdateOntologyConceptBinding; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyAssetBinding; +import org.openmetadata.schema.type.OntologyAssetConceptLinks; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyConceptBindingsResponse; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; + +/** REST helpers shared by the table binding, mapping source and mapping health tests. */ +final class OntologyMappingFixtures { + static final URI CUSTOMER = URI.create("urn:Customer"); + static final URI ORDER = URI.create("urn:Order"); + private static final URI XSD_STRING = URI.create("http://www.w3.org/2001/XMLSchema#string"); + + private OntologyMappingFixtures() {} + + static OpenMetadataClient admin() { + return SdkClients.adminClient(); + } + + /** A schema in a database of its own, so two calls give two databases. */ + static DatabaseSchema schema(final TestNamespace ns) { + return DatabaseSchemaTestFactory.createSimple(ns); + } + + static Table table(final DatabaseSchema schema, final String name, final Column... columns) { + return admin() + .tables() + .create( + new CreateTable() + .withName(name) + .withDatabaseSchema(schema.getFullyQualifiedName()) + .withColumns(List.of(columns))); + } + + static Table ownedTable( + final DatabaseSchema schema, + final String name, + final EntityReference owner, + final Column... columns) { + return admin() + .tables() + .create( + new CreateTable() + .withName(name) + .withDatabaseSchema(schema.getFullyQualifiedName()) + .withOwners(List.of(owner)) + .withColumns(List.of(columns))); + } + + static Column column(final String name, final ColumnDataType type) { + final Column column = new Column().withName(name).withDataType(type); + return type == ColumnDataType.VARCHAR ? column.withDataLength(64) : column; + } + + static OntologyProperty dataProperty( + final Ontology ontology, final String name, final OntologyConcept domain) { + return admin() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName(name) + .withOntology(ontology.getFullyQualifiedName()) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(domain.getIri())) + .withRange(List.of(XSD_STRING))); + } + + static OntologyProperty objectProperty( + final Ontology ontology, + final String name, + final OntologyConcept domain, + final OntologyConcept range) { + return admin() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName(name) + .withOntology(ontology.getFullyQualifiedName()) + .withKind(OntologyPropertyKind.OBJECT) + .withDomain(List.of(domain.getIri())) + .withRange(List.of(range.getIri()))); + } + + static OntologyAssetBinding binding(final Table table) { + return new OntologyAssetBinding() + .withAssetType(OntologyBindingAssetType.TABLE) + .withAssetId(table.getId()); + } + + static OntologyAssetBinding binding( + final Table table, final OntologyBindingRole role, final String... keyColumns) { + return binding(table) + .withRole(role) + .withSubjectKey(List.of(keyColumns).stream().map(List::of).toList()); + } + + static OntologyColumnBinding column(final OntologyProperty property, final String name) { + return new OntologyColumnBinding() + .withPropertyId(property.getId()) + .withColumnPath(List.of(name)); + } + + static OntologyRowFilter filter( + final String column, final OntologyRowFilterOperator operator, final Object value) { + return new OntologyRowFilter() + .withColumn(List.of(column)) + .withOperator(operator) + .withValue(value); + } + + static OntologyColumnJoin join( + final Table target, + final OntologyJoinStatus status, + final String child, + final String parent) { + return new OntologyColumnJoin() + .withTargetAssetId(target.getId()) + .withStatus(status) + .withOn( + List.of( + new OntologyJoinColumnPair() + .withChild(List.of(child)) + .withParent(List.of(parent)))); + } + + static String bindingsPath(final OntologyConcept concept) { + return "/v1/ontologyConcepts/" + concept.getId() + "/bindings"; + } + + static OntologyConceptBindingsResponse put( + final OpenMetadataClient client, + final OntologyConcept concept, + final OntologyAssetBinding asset, + final long revision) { + return client + .getHttpClient() + .execute( + HttpMethod.PUT, + bindingsPath(concept), + new UpdateOntologyConceptBinding().withExpectedRevision(revision).withAsset(asset), + OntologyConceptBindingsResponse.class); + } + + static OntologyConceptBindingsResponse bindings( + final OpenMetadataClient client, final OntologyConcept concept) { + return client + .getHttpClient() + .execute( + HttpMethod.GET, bindingsPath(concept), null, OntologyConceptBindingsResponse.class); + } + + /** The classes a table is bound to, each with the columns bound to it. */ + static OntologyAssetConceptLinks conceptsBoundTo( + final OpenMetadataClient client, final Table table) { + return client + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/ontologyConcepts/boundTo/table/" + table.getId(), + null, + OntologyAssetConceptLinks.class); + } + + static void unbind( + final OpenMetadataClient client, + final OntologyConcept concept, + final Table table, + final long revision) { + client + .getHttpClient() + .execute( + HttpMethod.DELETE, + bindingsPath(concept) + "/table/" + table.getId() + "?expectedRevision=" + revision, + null, + OntologyConceptBindingsResponse.class); + } + + static Ontology setMappingSource( + final OpenMetadataClient client, final Ontology ontology, final EntityReference database) { + final var patch = JsonUtils.getObjectMapper().createArrayNode(); + final var value = + JsonUtils.getObjectMapper().createObjectNode().put("type", database.getType()); + if (database.getId() != null) { + value.put("id", database.getId().toString()); + } + patch.addObject().put("op", "add").put("path", "/mappingSource").set("value", value); + return patch(client, ontology.getId(), patch); + } + + static Ontology clearMappingSource(final OpenMetadataClient client, final Ontology ontology) { + final var patch = JsonUtils.getObjectMapper().createArrayNode(); + patch.addObject().put("op", "remove").put("path", "/mappingSource"); + return patch(client, ontology.getId(), patch); + } + + private static Ontology patch( + final OpenMetadataClient client, final UUID ontologyId, final Object patch) { + return client + .getHttpClient() + .execute(HttpMethod.PATCH, "/v1/ontologies/" + ontologyId, patch, Ontology.class); + } + + static EntityReference mappingSource(final OpenMetadataClient client, final Ontology ontology) { + return client.ontologies().get(ontology.getId().toString(), "mappingSource").getMappingSource(); + } + + static OntologyMappingHealth health( + final OpenMetadataClient client, final Ontology ontology, final String query) { + return client + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/ontologies/" + ontology.getId() + "/mappingHealth" + query, + null, + OntologyMappingHealth.class); + } + + /** Each finding as its type, class and table names, the shape most assertions compare. */ + static List summary(final List entries) { + return entries.stream() + .map( + entry -> + "%s %s %s" + .formatted( + entry.getType().value(), + entry.getConcept() == null ? "-" : entry.getConcept().getName(), + entry.getAsset() == null ? "-" : entry.getAsset().getName())) + .toList(); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java index bed150f37bbd..adaac37d55ca 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyPropertyResourceIT.java @@ -1,13 +1,16 @@ package org.openmetadata.it.tests; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.net.URI; import java.util.List; import java.util.Map; 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; @@ -19,12 +22,15 @@ import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.type.OntologyLiteral; import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.schema.type.RelationshipCharacteristic; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.models.ListParams; import org.openmetadata.sdk.models.ListResponse; import org.openmetadata.sdk.services.ontology.OntologyPropertyService; +import org.openmetadata.service.ontology.OntologyReleaseContent; +import org.openmetadata.service.ontology.OntologyReleaseManifest; @Execution(ExecutionMode.CONCURRENT) public class OntologyPropertyResourceIT @@ -78,6 +84,176 @@ void dataValuesRoundTripAndEditsCreateANewVersion(TestNamespace ns) { assertTrue(updated.getVersion() > created.getVersion()); } + @Test + void aDataPropertyCanBeItsClassDisplayNameAndEachClassHasOne(TestNamespace ns) { + final var request = createMinimalRequest(ns).withKind(OntologyPropertyKind.DATA); + final var ontology = SdkClients.adminClient().ontologies().getByName(request.getOntology()); + final URI customer = + URI.create("https://example.org/display/" + ns.shortPrefix() + "/Customer"); + final URI order = URI.create("https://example.org/display/" + ns.shortPrefix() + "/Order"); + BaseOntologyApprovalIT.declareClass(ontology, "Customer", customer); + BaseOntologyApprovalIT.declareClass(ontology, "Order", order); + + final OntologyProperty first = + createEntity(request.withDomain(List.of(customer)).withIsDisplayName(true)); + assertEquals(true, getEntity(first.getId().toString()).getIsDisplayName()); + + final CreateOntologyProperty second = + createRequest(ns.prefix("secondName"), ns) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(customer)) + .withIsDisplayName(true); + final OpenMetadataException rejected = + assertThrows(OpenMetadataException.class, () -> createEntity(second)); + assertEquals(400, rejected.getStatusCode()); + assertTrue(rejected.getMessage().contains("at most one display-name property")); + + final OntologyProperty other = createEntity(second.withDomain(List.of(order))); + assertEquals(true, getEntity(other.getId().toString()).getIsDisplayName()); + other.setDomain(List.of(customer)); + assertPropertyFieldRejected(other, "domain", List.of(customer)); + assertEquals(List.of(order), getEntity(other.getId().toString()).getDomain()); + + final OntologyProperty cleared = getEntity(first.getId().toString()); + cleared.setIsDisplayName(null); + final OntologyProperty updated = entityService().update(cleared.getId().toString(), cleared); + assertEquals(null, updated.getIsDisplayName()); + final var move = JsonUtils.getObjectMapper().createArrayNode(); + move.addObject() + .put("op", "replace") + .put("path", "/domain/0") + .put("value", customer.toString()); + assertEquals( + customer.toString(), + entityService().patch(other.getId(), move).getDomain().getFirst().toString()); + } + + @Test + void theFlagCanBeSetOnAnExistingPropertyAndASecondOneIsRefusedByPutAndPatch(TestNamespace ns) { + final var request = createMinimalRequest(ns).withKind(OntologyPropertyKind.DATA); + final var ontology = SdkClients.adminClient().ontologies().getByName(request.getOntology()); + final URI customer = URI.create("https://example.org/display/" + ns.shortPrefix() + "/Buyer"); + BaseOntologyApprovalIT.declareClass(ontology, "Buyer", customer); + final OntologyProperty first = createEntity(request.withDomain(List.of(customer))); + final OntologyProperty second = + createEntity( + createRequest(ns.prefix("buyerCode"), ns) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(customer))); + assertEquals(null, getEntity(first.getId().toString()).getIsDisplayName()); + + final var flag = JsonUtils.getObjectMapper().createArrayNode(); + flag.addObject().put("op", "add").put("path", "/isDisplayName").put("value", true); + assertEquals(true, entityService().patch(first.getId(), flag).getIsDisplayName()); + assertEquals(true, getEntity(first.getId().toString()).getIsDisplayName()); + + final CreateOntologyProperty flagSecond = + createRequest(second.getName(), ns) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(customer)) + .withIsDisplayName(true); + final OpenMetadataException put = + assertThrows( + OpenMetadataException.class, + () -> SdkClients.adminClient().ontologyProperties().upsert(flagSecond)); + assertEquals(400, put.getStatusCode()); + assertEquals( + "Ontology validation failed: A class has at most one display-name property, but " + + flagSecond.getIri() + + " and " + + first.getIri() + + " both name the same class", + put.getMessage()); + assertEquals(null, getEntity(second.getId().toString()).getIsDisplayName()); + final OpenMetadataException patch = + assertThrows( + OpenMetadataException.class, () -> entityService().patch(second.getId(), flag)); + assertEquals(400, patch.getStatusCode()); + assertEquals(null, getEntity(second.getId().toString()).getIsDisplayName()); + } + + @Test + void restoringAFlaggedPropertyIntoAClassThatAlreadyHasOneIsRefused(TestNamespace ns) { + final var request = createMinimalRequest(ns).withKind(OntologyPropertyKind.DATA); + final var ontology = SdkClients.adminClient().ontologies().getByName(request.getOntology()); + final URI shop = URI.create("https://example.org/display/" + ns.shortPrefix() + "/Shop"); + BaseOntologyApprovalIT.declareClass(ontology, "Shop", shop); + final OntologyProperty original = + createEntity(request.withDomain(List.of(shop)).withIsDisplayName(true)); + deleteEntity(original.getId().toString()); + final OntologyProperty replacement = + createEntity( + createRequest(ns.prefix("shopName"), ns) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(shop)) + .withIsDisplayName(true)); + + final OpenMetadataException refused = + assertThrows(OpenMetadataException.class, () -> restoreEntity(original.getId().toString())); + assertEquals(400, refused.getStatusCode()); + assertTrue(refused.getMessage().contains("at most one display-name property")); + assertEquals(true, getEntity(replacement.getId().toString()).getIsDisplayName()); + } + + @Test + void aFalseFlagIsStoredAsAnAbsentFlagAndProjectsLikeOne(TestNamespace ns) { + final OntologyProperty explicit = + createEntity( + createMinimalRequest(ns).withKind(OntologyPropertyKind.DATA).withIsDisplayName(false)); + final OntologyProperty absent = + createEntity( + createRequest(ns.prefix("absentFlag"), ns).withKind(OntologyPropertyKind.DATA)); + final OntologyProperty storedExplicit = getEntity(explicit.getId().toString()); + final OntologyProperty storedAbsent = getEntity(absent.getId().toString()); + + assertEquals(null, storedExplicit.getIsDisplayName()); + assertFalse(JsonUtils.valueToTree(storedExplicit).has("isDisplayName")); + assertEquals(sealedDigest(storedAbsent), sealedDigest(storedExplicit)); + + final OntologyProperty flagged = storedExplicit.withIsDisplayName(true); + assertEquals( + true, entityService().update(flagged.getId().toString(), flagged).getIsDisplayName()); + final OntologyProperty cleared = getEntity(flagged.getId().toString()).withIsDisplayName(false); + assertEquals( + null, entityService().update(cleared.getId().toString(), cleared).getIsDisplayName()); + } + + /** The digest of the sealed content of a property, with the identity fields made equal. */ + private static String sealedDigest(OntologyProperty property) { + final ObjectNode content = OntologyReleaseContent.project(property); + content.put("id", "00000000-0000-0000-0000-0000000000b1"); + content.put("name", "sealed"); + content.put("fullyQualifiedName", "sealed"); + content.put("iri", "https://example.org/sealed"); + content.with("ontology").put("id", "00000000-0000-0000-0000-0000000000c1"); + return OntologyReleaseManifest.digest( + List.of( + OntologyReleaseManifest.member( + UUID.fromString("00000000-0000-0000-0000-0000000000a1"), + OntologyReleaseMember.MemberKind.PROPERTY, + UUID.fromString("00000000-0000-0000-0000-0000000000b1"), + content))); + } + + @Test + void onlyADataPropertyMayBeADisplayName(TestNamespace ns) { + final var request = createMinimalRequest(ns).withIsDisplayName(true); + for (final OntologyPropertyKind kind : + List.of(OntologyPropertyKind.OBJECT, OntologyPropertyKind.ANNOTATION)) { + assertEquals( + 400, + assertThrows(OpenMetadataException.class, () -> createEntity(request.withKind(kind))) + .getStatusCode()); + } + } + + @Test + void aPropertyWithoutTheFlagReadsBackWithoutIt(TestNamespace ns) { + final OntologyProperty created = + createEntity(createMinimalRequest(ns).withKind(OntologyPropertyKind.DATA)); + assertEquals(null, getEntity(created.getId().toString()).getIsDisplayName()); + } + @Test void enumerationMetadataIsValidatedOnEveryWrite(TestNamespace ns) { final CreateOntologyProperty request = diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java new file mode 100644 index 000000000000..2b5877b82a34 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRecordStatementIT.java @@ -0,0 +1,433 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertAll; +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 static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.FILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.PAGED_COMPOSITE_RELATED_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.columnPlan; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.function.Executable; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyStatementBindingRevision; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementRelation; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * Asks the four statement endpoints of a class about each mapping shape, with the tables of the + * shape created in the database this suite runs on, and runs every statement that comes back. A + * statement must be the golden text of its engine family, and must return the rows that the shape + * says its tables hold. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyRecordStatementIT extends BaseOntologyApprovalIT { + /** The rows a statement may return: its row cap, and whether it asks for one row more. */ + private record Limit(int rowCap, boolean extraRow) { + int rows() { + return extraRow ? rowCap + 1 : rowCap; + } + } + + private static final Limit FIND = new Limit(25, false); + private static final Limit OPEN = new Limit(100, true); + private static final Limit EXPAND = new Limit(25, true); + private static final Limit TOP_RECORDS = new Limit(8, false); + private static final Limit COUNT = new Limit(1, false); + + @Test + void anIdentityTableWithoutAFilterAnswersEveryStatement(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, UNFILTERED_IDENTITY); + + assertEquals(List.of(List.of("3")), rows.get("count")); + } + + @Test + void twoClassesOverOneFilteredTableEachAnswerWithTheirOwnRows(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, FILTERED_IDENTITY); + + assertEquals(List.of(List.of("2")), rows.get("person-count")); + assertEquals(List.of(List.of("2")), rows.get("organization-count")); + } + + @Test + void aTwoColumnKeyPairsWithItsContributingTableByPosition(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, COMPOSITE_KEY); + + assertEquals(List.of(List.of("eu", "42", "Northwind", "gold")), rows.get("open")); + } + + @Test + void aContributingTableWithSeveralRowsForOneKeyGivesSeveralRows(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, REPEATED_CONTRIBUTION); + + assertEquals(3, rows.get("open").size()); + } + + @Test + void aRelationHeldInAColumnIsFollowedBothWaysAndPagedByOneExtraRow(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, COLUMN_RELATION); + + assertEquals(26, rows.get("expand-inverse-page").size()); + assertEquals(25, rows.get("find").size()); + assertEquals(List.of(List.of("31", "2", "Grace Hopper")), rows.get("expand-forward")); + assertEquals(List.of(List.of("31", "2", "Grace Hopper")), rows.get("expand-forward-after")); + } + + @Test + void aRelationHeldInALinkTableIsFollowedBothWays(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, LINK_TABLE); + + assertEquals( + List.of( + List.of("A-1", "Anvil", "2"), + List.of("B-2", "Bolt", "1"), + List.of("C-3", "Crate", "1")), + rows.get("aggregate-inverse")); + assertEquals( + List.of(List.of("1", "B-2", "Bolt"), List.of("1", "C-3", "Crate")), + rows.get("expand-forward-after")); + } + + @Test + void aRelatedKeyOfTwoColumnsIsFollowedBothWaysAndStartsAfterAGivenKey(final TestNamespace ns) { + final Map>> rows = everyStatement(ns, PAGED_COMPOSITE_RELATED_KEY); + + assertEquals(List.of(List.of("b", "7", "1", "Main Ledger")), rows.get("expand-forward")); + assertEquals(List.of(List.of("b", "7", "1", "Main Ledger")), rows.get("expand-forward-after")); + } + + @Test + void aContributingTableTheReaderMayNotViewLeavesTheStatementAndIsNamedNowhere( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "hiddenContribution"); + final Ask open = REPEATED_CONTRIBUTION.ask("open"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, REPEATED_CONTRIBUTION).withRows(); + var access = new RdfAccessFixtures("stmtRecord" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient reader = ownerReader(access, Entity.TABLE); + fixture.ownedBy(reader, "customers"); + + final OntologyStatementPlan asReader = fixture.ask(reader, open, null); + final String answer = fixture.answer(reader, open, null); + final OntologyStatementPlan asAdmin = fixture.ask(admin(), open, null); + + assertEquals( + String.join( + "\n", + "SELECT t0." + fixture.name("id") + ", t0." + fixture.name("name"), + "FROM " + fixture.from("customers") + " t0", + "WHERE t0." + fixture.name("id") + " = 1", + "LIMIT 101"), + asReader.getSql()); + assertEquals( + List.of("0 key Customer part 0", "1 displayName Customer customerName"), + columnPlan(asReader.getColumns())); + assertEquals( + List.of(fixture.table("customers").getFullyQualifiedName()), asReader.getTables()); + assertEquals( + List.of(List.of("1", "Ada Lovelace")), OntologyShapeFixture.run(asReader.getSql())); + assertNamesNothingOf(fixture.table("customer_addresses"), answer); + // The hidden table and both properties bound on it have "address" in their names. + assertFalse(answer.contains("address"), answer); + assertEquals(asReader.getColumns(), asAdmin.getColumns().subList(0, 2)); + assertEquals(open.columns(), columnPlan(asAdmin.getColumns())); + } + } + + @Test + void aStatementReadsTheVersionThatItsRequestNames(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "versions"); + final Ask open = LINK_TABLE.ask("open"); + final Ask products = LINK_TABLE.ask("count"); + final Ask contained = LINK_TABLE.ask("expand-forward"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, LINK_TABLE).withRows()) { + fixture.bind(LINK_TABLE.binding("Order", "orders")); + final OntologyRelease release = current(activate(ns, ontology)); + fixture.bind(LINK_TABLE.binding("Product", "products")); + fixture.bind(LINK_TABLE.binding("Order", "order_items")); + final String inRelease = + " is not in the active release of ontology " + ontology.getFullyQualifiedName(); + + final OntologyStatementPlan released = + fixture.ask(admin(), open, OntologyStatementVersion.RELEASE); + final OntologyStatementPlan drafted = + fixture.ask(admin(), open, OntologyStatementVersion.DRAFT); + + assertRefused( + 404, + "Class https://example.org/linkTable#Product" + inRelease, + () -> fixture.ask(admin(), products, OntologyStatementVersion.RELEASE)); + assertRefused( + 404, + "Relation https://example.org/linkTable#contains" + inRelease, + () -> fixture.ask(admin(), contained, OntologyStatementVersion.RELEASE)); + assertEquals( + List.of("0 key Order part 0", "1 property Order orderChannel"), + columnPlan(released.getColumns())); + assertEquals(List.of(fixture.table("orders").getFullyQualifiedName()), released.getTables()); + assertEquals(List.of(List.of("1", "web")), OntologyShapeFixture.run(released.getSql())); + assertEquals(releaseRead(release), released.getVersion()); + assertEquals(open.columns(), columnPlan(drafted.getColumns())); + assertRows(open, OPEN, OntologyShapeFixture.run(drafted.getSql())); + assertEquals( + new OntologyStatementVersionRead() + .withKind(OntologyStatementVersion.DRAFT) + .withWorkingRevision( + admin().ontologies().state(ontology.getId()).getWorkingRevision()), + drafted.getVersion()); + assertEquals( + List.of(List.of("4")), + OntologyShapeFixture.run( + fixture.ask(admin(), products, OntologyStatementVersion.DRAFT).getSql())); + assertRows( + contained, + EXPAND, + OntologyShapeFixture.run( + fixture.ask(admin(), contained, OntologyStatementVersion.DRAFT).getSql())); + } + } + + @Test + void theDisplayNameFlagComesFromTheVersionThatARequestNames(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "displayNameVersions"); + final Ask find = UNFILTERED_IDENTITY.ask("find"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, UNFILTERED_IDENTITY)) { + fixture.bindAll(); + activate(ns, ontology); + final String name = fixture.property("customerName").getId().toString(); + admin() + .ontologyProperties() + .update(name, admin().ontologyProperties().get(name).withIsDisplayName(false)); + + assertEquals( + List.of( + "0 key Customer part 0", + "1 displayName Customer customerName", + "2 property Customer customerEmail"), + columnPlan(fixture.ask(admin(), find, OntologyStatementVersion.RELEASE).getColumns())); + assertEquals( + List.of( + "0 key Customer part 0", + "1 property Customer customerEmail", + "2 property Customer customerName"), + columnPlan(fixture.ask(admin(), find, OntologyStatementVersion.DRAFT).getColumns())); + } + } + + @Test + void aBindingWriteMovesTheBindingRevisionOfTheNextPlan(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "revisions"); + final Ask find = UNFILTERED_IDENTITY.ask("find"); + final BindingSpec bound = UNFILTERED_IDENTITY.binding("Customer", "customers"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, UNFILTERED_IDENTITY)) { + fixture.bindAll(); + + final OntologyStatementPlan first = + fixture.ask(admin(), find, OntologyStatementVersion.DRAFT); + fixture.bind( + new BindingSpec( + bound.type(), + bound.table(), + bound.role(), + bound.key(), + null, + List.of(bound.columns().getLast()))); + final OntologyStatementPlan second = + fixture.ask(admin(), find, OntologyStatementVersion.DRAFT); + + assertEquals(List.of(fixture.revision("Customer", 1L)), first.getBindingRevisions()); + assertEquals(find.columns(), columnPlan(first.getColumns())); + assertEquals(List.of(fixture.revision("Customer", 2L)), second.getBindingRevisions()); + assertEquals( + List.of("0 key Customer part 0", "1 displayName Customer customerName"), + columnPlan(second.getColumns())); + } + } + + /** + * Binds the shape over real tables, activates a release and asks every statement of the shape as + * a request that names no version. + * + * @return the rows each statement returned, by the name of its ask + */ + private static Map>> everyStatement( + final TestNamespace ns, final Shape shape) { + final Ontology ontology = createOntology(ns, shape.name()); + final Map>> rows = new ConcurrentHashMap<>(); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, shape).withRows()) { + fixture.bindAll(); + final OntologyRelease release = current(activate(ns, ontology)); + assertAll( + shape.asks().stream() + .map( + ask -> + (Executable) + () -> rows.put(ask.name(), answered(fixture, shape, ask, release)))); + } + return rows; + } + + /** Checks the plan of one statement, runs the statement and checks its rows. */ + private static List> answered( + final OntologyShapeFixture fixture, + final Shape shape, + final Ask ask, + final OntologyRelease release) { + final OntologyStatementPlan plan = fixture.ask(admin(), ask, null); + final Limit limit = limitOf(ask); + final String name = ask.name(); + + assertEquals(fixture.golden(ask), plan.getSql() + "\n", name + " sql"); + assertEquals(plan.getSql(), plan.getEscapedSql(), name + " escapedSql"); + assertEquals(ask.kind(), plan.getStatement(), name + " statement"); + assertEquals(fixture.family(), plan.getFamily().value(), name + " family"); + assertEquals(fixture.dialect(), plan.getDialect(), name + " dialect"); + assertEquals(fixture.service().getName(), plan.getService(), name + " service"); + assertEquals( + fixture.service().getServiceType().value(), plan.getServiceType(), name + " serviceType"); + assertEquals(fixture.tablesOf(ask), plan.getTables(), name + " tables"); + assertEquals(ask.columns(), columnPlan(plan.getColumns()), name + " columns"); + assertEquals(relationOf(shape, ask), plan.getRelation(), name + " relation"); + assertEquals(limit.rowCap(), plan.getRowCap(), name + " rowCap"); + assertEquals(limit.extraRow(), plan.getExtraRow(), name + " extraRow"); + assertEquals(orderedBy(shape, ask), plan.getOrderedBy(), name + " orderedBy"); + assertEquals(releaseRead(release), plan.getVersion(), name + " version"); + assertEquals(revisionsOf(fixture, shape, ask), plan.getBindingRevisions(), name + " revisions"); + final List> rows = OntologyShapeFixture.run(plan.getSql()); + assertRows(ask, limit, rows); + return rows; + } + + private static Limit limitOf(final Ask ask) { + return switch (ask.kind()) { + case FIND -> FIND; + case OPEN -> OPEN; + case EXPAND -> EXPAND; + case AGGREGATE -> ask.relation() == null ? COUNT : TOP_RECORDS; + }; + } + + /** + * An aggregate returns exactly its rows, in order. Any other statement returns rows that the + * shape lists, each as often as the shape lists it, and stops at its row limit. + */ + private static void assertRows(final Ask ask, final Limit limit, final List> rows) { + if (ask.kind() == OntologyStatementKind.AGGREGATE) { + assertEquals(ask.rows(), rows, ask.name() + " rows"); + return; + } + if (ask.kind() == OntologyStatementKind.EXPAND) { + final int kept = Math.min(ask.rows().size(), limit.rows()); + assertEquals(ask.rows().subList(0, kept), rows, ask.name() + " rows"); + return; + } + final List> listed = new ArrayList<>(ask.rows()); + for (final List row : rows) { + assertTrue(listed.remove(row), () -> ask.name() + " returned " + row); + } + assertEquals(Math.min(ask.rows().size(), limit.rows()), rows.size(), ask.name() + " row count"); + } + + /** + * The result columns that hold the key of the related record when the statement is an expand, + * and none for another statement. + */ + private static List orderedBy(final Shape shape, final Ask ask) { + if (ask.kind() != OntologyStatementKind.EXPAND) { + return List.of(); + } + final String related = "key " + relatedTo(shape, ask) + " part"; + return IntStream.range(0, ask.columns().size()) + .filter(index -> ask.columns().get(index).contains(related)) + .boxed() + .toList(); + } + + /** What a plan says about the relation that the ask follows, and null when it follows none. */ + private static OntologyStatementRelation relationOf(final Shape shape, final Ask ask) { + return ask.relation() == null + ? null + : new OntologyStatementRelation() + .withPropertyIri(shape.iri(ask.relation())) + .withDirection(ask.direction()) + .withRelatedClassIri(shape.iri(relatedTo(shape, ask))); + } + + /** The class at the far end of the relation: its range forward and its domain going back. */ + private static String relatedTo(final Shape shape, final Ask ask) { + final PropertySpec relation = shape.property(ask.relation()); + return ask.direction() == OntologyStatementDirection.FORWARD + ? relation.range() + : relation.domain(); + } + + /** The binding revision of each class the statement reads, as the bindings endpoint gives it. */ + private static List revisionsOf( + final OntologyShapeFixture fixture, final Shape shape, final Ask ask) { + return ask.relation() == null + ? List.of(fixture.revisionOf(ask.type())) + : List.of(fixture.revisionOf(ask.type()), fixture.revisionOf(relatedTo(shape, ask))); + } + + private static OntologyStatementVersionRead releaseRead(final OntologyRelease release) { + return new OntologyStatementVersionRead() + .withKind(OntologyStatementVersion.RELEASE) + .withReleaseId(release.getId()) + .withReleaseRevision(release.getReleaseRevision()) + .withSemanticVersion(release.getSemanticVersion()); + } + + private static void assertNamesNothingOf(final Table hidden, final String answer) { + assertFalse(answer.contains(hidden.getName()), answer); + assertFalse(answer.contains(hidden.getId().toString()), answer); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRowFilterValueIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRowFilterValueIT.java new file mode 100644 index 000000000000..e4cd19bccc0e --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyRowFilterValueIT.java @@ -0,0 +1,293 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.ORDER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; +import static org.openmetadata.schema.type.OntologyRowFilterOperator.EQUALS; +import static org.openmetadata.schema.type.OntologyRowFilterOperator.GREATER_THAN; +import static org.openmetadata.schema.type.OntologyRowFilterOperator.GREATER_THAN_OR_EQUALS; +import static org.openmetadata.schema.type.OntologyRowFilterOperator.IN; +import static org.openmetadata.schema.type.OntologyRowFilterOperator.IS_NOT_NULL; +import static org.openmetadata.schema.type.OntologyRowFilterOperator.LESS_THAN; +import static org.openmetadata.schema.type.OntologyRowFilterOperator.NOT_EQUALS; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.function.Executable; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.service.Entity; + +/** + * What a write of a row filter does with the value of the filter. It parses the value as the data + * type of the filter column, refuses a value that does not parse, and stores a value that parses + * as it was written. The refused values and the refused callers are the cases of {@code + * ontology/sql-value-cases.json}. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyRowFilterValueIT extends BaseOntologyApprovalIT { + private static final int BAD_REQUEST = 400; + private static final int FORBIDDEN = 403; + private static final String NOT_A_WHOLE_NUMBER = + "The value for column qty does not parse as INT: a whole number is written in ASCII digits," + + " with a leading minus sign when negative and no leading zeros"; + private static final String NOT_A_DECIMAL_NUMBER = + "does not parse as DECIMAL: a decimal number is written in ASCII digits with at most one" + + " decimal point, a leading minus sign when negative, and no exponent or leading zeros"; + + @Test + void aWriteRefusesEachCaseValueThatDoesNotParseAsTheDataTypeOfItsColumn(final TestNamespace ns) { + final List cases = refusedWith(BAD_REQUEST); + final OntologyConcept order = declareClass(createOntology(ns), "Order", ORDER); + final Table orders = table(schema(ns), "orders", columnsOf(cases)); + + assertEquals(47, cases.size()); + assertAll( + cases.stream() + .map(json -> refusal(json, () -> save(order, orders, filterBesideItsValue(json))))); + assertEquals(List.of(), bindings(admin(), order).getAssets()); + } + + @Test + void aRefusalNamesTheColumnItsDataTypeAndTheFormThatTheTypeExpects(final TestNamespace ns) { + final OntologyConcept order = declareClass(createOntology(ns), "Order", ORDER); + final Table orders = orders(schema(ns)); + + assertRejected(NOT_A_WHOLE_NUMBER, () -> save(order, orders, filter("qty", EQUALS, "abc"))); + assertRejected( + NOT_A_WHOLE_NUMBER, () -> save(order, orders, filter("qty", IN, List.of(1, "2 OR 1=1")))); + assertRejected( + "The value for column qty does not parse as INT: the type holds whole numbers from" + + " -2147483648 to 2147483647", + () -> save(order, orders, filter("qty", EQUALS, "2147483648"))); + assertRejected( + "The value for column amount " + NOT_A_DECIMAL_NUMBER, + () -> save(order, orders, filter("amount", GREATER_THAN, "1e3"))); + assertRejected( + "The value for column active does not parse as BOOLEAN: a boolean is the JSON value true" + + " or false", + () -> save(order, orders, filter("active", EQUALS, "true"))); + assertRejected( + "The value for column created_on does not parse as DATE: a date is written YYYY-MM-DD and" + + " names a real calendar day", + () -> save(order, orders, filter("created_on", LESS_THAN, "2024-02-30"))); + assertRejected( + "The value for column created_at does not parse as TIMESTAMP: a timestamp is written" + + " YYYY-MM-DD hh:mm:ss with at most six fraction digits and no offset", + () -> save(order, orders, filter("created_at", EQUALS, "2024-01-01T10:30:00Z"))); + assertRejected( + "SQL generation does not support column type JSON of column payload", + () -> save(order, orders, filter("payload", EQUALS, "{}"))); + assertEquals(List.of(), bindings(admin(), order).getAssets()); + } + + @Test + void aValueOfTheDataTypeOfItsColumnIsStoredAsItWasWrittenAndReadBack(final TestNamespace ns) { + final OntologyConcept order = declareClass(createOntology(ns), "Order", ORDER); + final Table orders = orders(schema(ns)); + final List filters = + List.of( + filter("qty", EQUALS, "42"), + filter("qty", IN, List.of(1, 2)), + filter("amount", GREATER_THAN, "0.10"), + filter("active", EQUALS, true), + filter("created_on", LESS_THAN, "2024-02-29"), + filter("created_at", GREATER_THAN_OR_EQUALS, "2024-01-01T10:30:00"), + filter("status", NOT_EQUALS, "O'Brien"), + filter("payload", IS_NOT_NULL, null)); + + long revision = 0L; + for (final OntologyRowFilter filter : filters) { + final var saved = put(admin(), order, binding(orders).withRowFilter(filter), revision); + revision = saved.getRevision(); + + assertEquals(filter, saved.getAssets().getFirst().getRowFilter()); + assertEquals(filter, bindings(admin(), order).getAssets().getFirst().getRowFilter()); + } + } + + /** + * One case of the file writes through a change set. OntologyChangeSetBindingIT applies that + * change set, so this test leaves the case out. + */ + @Test + void aCallerWithoutViewSampleDataSetsAndChangesNoRowFilterOfTheCases(final TestNamespace ns) { + final List cases = + refusedWith(FORBIDDEN).stream().filter(json -> !json.get("input").has("via")).toList(); + final OntologyConcept order = declareClass(createOntology(ns), "Order", ORDER); + final Table people = + table( + schema(ns), + "people", + column("salary", ColumnDataType.DECIMAL), + column("ssn", ColumnDataType.VARCHAR)); + final OntologyRowFilter stored = filter("salary", LESS_THAN, 1); + try (var fixtures = new RdfAccessFixtures("filterValue" + ns.shortPrefix())) { + final var noSamples = fixtures.denyRole(MetadataOperation.VIEW_SAMPLE_DATA, Entity.TABLE); + final var editor = fixtures.allowRole(MetadataOperation.EDIT_ALL, Entity.ONTOLOGY_CONCEPT); + final var client = + OntologyBindingFixtures.client( + fixtures.userToken("editor", List.of(noSamples.getId(), editor.getId()))); + + assertEquals(4, cases.size()); + assertAll(refusals(cases, client, order, people, 0L)); + put(admin(), order, binding(people).withRowFilter(stored), 0L); + assertAll(refusals(cases, client, order, people, 1L)); + assertRejected( + "The value for column salary " + NOT_A_DECIMAL_NUMBER, + () -> + put( + client, + order, + binding(people).withRowFilter(filter("salary", GREATER_THAN, "1e6")), + 1L)); + assertEquals(stored, bindings(admin(), order).getAssets().getFirst().getRowFilter()); + } + } + + private static Table orders(final DatabaseSchema schema) { + return table( + schema, + "orders", + column("status", ColumnDataType.VARCHAR), + column("qty", ColumnDataType.INT), + column("amount", ColumnDataType.DECIMAL), + column("active", ColumnDataType.BOOLEAN), + column("created_on", ColumnDataType.DATE), + column("created_at", ColumnDataType.TIMESTAMP), + column("payload", ColumnDataType.JSON)); + } + + /** The cases that a write must refuse with {@code status}. */ + private static List refusedWith(final int status) { + return OntologySqlValueCases.withOutcome("refusedAtSave").stream() + .filter(json -> json.at("/expectedOutcome/status").asInt() == status) + .toList(); + } + + /** One column for each column that the cases name, of the data type that the cases give it. */ + private static Column[] columnsOf(final List cases) { + final Map types = new LinkedHashMap<>(); + cases.forEach( + json -> + types.merge( + json.get("column").get(0).asText(), + ColumnDataType.fromValue(json.get("columnType").asText()), + (first, second) -> { + assertEquals(first, second, json.get("id").asText()); + return first; + })); + return types.entrySet().stream() + .map(entry -> accepted(entry.getKey(), entry.getValue())) + .toArray(Column[]::new); + } + + /** A column that the catalog accepts: a binary column has a length and an array a member type. */ + private static Column accepted(final String name, final ColumnDataType type) { + final Column column = column(name, type); + return switch (type) { + case BINARY -> column.withDataLength(64); + case ARRAY -> column.withArrayDataType(ColumnDataType.INT); + default -> column; + }; + } + + /** The row filter of a case that gives the column and the operator beside the value. */ + private static OntologyRowFilter filterBesideItsValue(final JsonNode json) { + return filter( + json.get("column").get(0).asText(), + OntologyRowFilterOperator.fromValue(json.get("operator").asText()), + JsonUtils.getObjectMapper().convertValue(json.get("input"), Object.class)); + } + + /** The row filter of a case that gives the whole filter as the request carries it. */ + private static OntologyRowFilter whole(final JsonNode json) { + return JsonUtils.getObjectMapper().convertValue(json.get("input"), OntologyRowFilter.class); + } + + private static void save( + final OntologyConcept concept, final Table table, final OntologyRowFilter filter) { + put(admin(), concept, binding(table).withRowFilter(filter), 0L); + } + + /** What each case expects when {@code client} sends its row filter at {@code revision}. */ + private static Stream refusals( + final List cases, + final OpenMetadataClient client, + final OntologyConcept concept, + final Table table, + final long revision) { + return cases.stream() + .map( + json -> + refusal( + json, + () -> + put(client, concept, binding(table).withRowFilter(whole(json)), revision))); + } + + /** The refusal that a case expects: its status, and a message that holds each part it names. */ + private static Executable refusal(final JsonNode json, final Runnable request) { + final List parts = new ArrayList<>(); + json.at("/expectedOutcome/messageContains").forEach(part -> parts.add(part.asText())); + return () -> + assertRefused( + json.get("id").asText(), json.at("/expectedOutcome/status").asInt(), parts, request); + } + + private static void assertRejected(final String message, final Runnable request) { + assertRefused(message, BAD_REQUEST, List.of(message), request); + } + + private static void assertRefused( + final String what, final int status, final List parts, final Runnable request) { + final var refused = assertThrows(OpenMetadataException.class, request::run, what); + assertEquals(status, refused.getStatusCode(), () -> what + ": " + refused.getMessage()); + parts.forEach( + part -> + assertTrue( + refused.getMessage().contains(part), + () -> what + " expects '" + part + "' in " + refused.getMessage())); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java new file mode 100644 index 000000000000..a0b60fd33321 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckAnswerIT.java @@ -0,0 +1,600 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertStatus; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.CUSTOM_SQL; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.MEMBERS; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.PARTIES; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.addRows; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.answer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.assertCounts; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.check; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.countParameters; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.data; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declareKey; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identity; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identityTable; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.integer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.keyList; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.mapping; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.part; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.read; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.reference; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.row; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.table; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.targets; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.text; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.CHECK; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.HELD_BY_MAPPING; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.NOT_ENFORCEABLE; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.NOT_MAPPED; +import static org.openmetadata.schema.api.data.OntologyShapePart.CLASS; +import static org.openmetadata.schema.api.data.OntologyShapePart.DATATYPE; +import static org.openmetadata.schema.api.data.OntologyShapePart.IN; +import static org.openmetadata.schema.api.data.OntologyShapePart.MAX_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.MIN_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.PATTERN; +import static org.openmetadata.schema.api.data.OntologyShapePart.RANGE; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.RELEASE; +import static org.openmetadata.schema.type.OntologyRowFilterOperator.NOT_EQUALS; + +import java.net.URI; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyAxiom; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposal; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposalState; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyAxiom; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyAxiomType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyExpression; +import org.openmetadata.schema.type.OntologyExpressionKind; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.RelationProvenance; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * What {@code GET /v1/ontologyConcepts/{id}/shapeChecks} answers for each outcome: a test with its + * statement, a part that the mapping holds, a property with no binding, a part with no exact test, + * and the version that a request names. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckAnswerIT extends BaseOntologyApprovalIT { + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + private static final String TABLE_LINK = "<#E::table::%s>"; + private static final String POSTGRES = "postgres"; + + /** One table whose declared key is its subject key, so each row is one record. */ + private static final Shape ACCOUNTS = + mapping( + "accounts", + List.of( + table( + "accounts", List.of(integer("id"), text("email"), text("nick"), integer("age")))), + List.of("Account"), + List.of( + data("accountNo", "Account"), + data("accountEmail", "Account"), + data("accountNick", "Account"), + data("accountAge", "Account"), + data("accountNote", "Account")), + identityTable( + "Account", + "accounts", + List.of("id"), + null, + bound("accountNo", "id"), + bound("accountEmail", "email"), + bound("accountNick", "nick"), + bound("accountAge", "age"))); + + /** The accounts table and the shape of its class, as the parts of an answer name them. */ + private record Accounts(OntologyShapeFixture fixture, OntologyShape shape) { + private String tableName() { + return fixture.table("accounts").getFullyQualifiedName(); + } + + private OntologyShapeCheckBinding binding() { + return read(fixture, "Account", "accounts", 1L); + } + + /** A test of the table, with the list of keys that its statement counts. */ + OntologyShapeCheck test(final String column, final String count) { + return new OntologyShapeCheck() + .withTable(reference(fixture, "accounts")) + .withColumns(List.of(List.of(column))) + .withReadBindings(List.of(binding())) + .withProposal( + new OntologyShapeCheckProposal().withState(OntologyShapeCheckProposalState.NONE)) + .withTestDefinition(CUSTOM_SQL) + .withEntityLink(TABLE_LINK.formatted(tableName())) + .withParameterValues(countParameters(count)) + .withInspectionQuery(keyList(count)); + } + + /** The statement that counts the accounts whose value in a column breaks {@code test}. */ + String countWhere(final String column, final String test) { + final String id = fixture.name("id"); + return String.join( + "\n", + "SELECT COUNT(*) AS violations", + "FROM (", + " SELECT DISTINCT t0." + id + " AS k0", + " FROM " + fixture.from("accounts") + " t0", + " WHERE t0." + id + " IS NOT NULL", + " AND " + test.replace("{}", "t0." + fixture.name(column)), + ") c"); + } + + /** The statement that counts the accounts with no value in a column. */ + String countWithout(final String column) { + final String id = fixture.name("id"); + return String.join( + "\n", + "SELECT COUNT(*) AS violations", + "FROM (", + " SELECT k.k0", + " FROM (", + " SELECT DISTINCT t0." + id + " AS k0, t0." + fixture.name(column) + " AS v0", + " FROM " + fixture.from("accounts") + " t0", + " WHERE t0." + id + " IS NOT NULL", + " ) k", + " GROUP BY k.k0", + " HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1", + ") c"); + } + + /** A part that one test checks, which takes its name from what it checks. */ + OntologyCheckedPart checked( + final String constraint, final OntologyShapePart part, final OntologyShapeCheck test) { + final List column = test.getColumns().getFirst(); + return entry(part, CHECK) + .withChecks( + List.of(test.withIdentity(identity(shape, constraint, part, binding(), column)))); + } + + OntologyCheckedConstraint constraint( + final String id, final String property, final OntologyCheckedPart... parts) { + return new OntologyCheckedConstraint() + .withId(id) + .withPath(fixture.property(property).getIri()) + .withParts(List.of(parts)); + } + } + + private static OntologyCheckedPart entry( + final OntologyShapePart part, final OntologyShapeCheckOutcome outcome) { + return new OntologyCheckedPart().withPart(part).withOutcome(outcome); + } + + private static OntologyShapeCheckOutcome outcome( + final OntologyShapeChecks checks, final String constraint, final OntologyShapePart part) { + return part(checks, constraint, part).getOutcome(); + } + + private static OntologyShapeCheckReason reason( + final OntologyShapeChecks checks, final String constraint, final OntologyShapePart part) { + return part(checks, constraint, part).getReason(); + } + + @Test + void aTableWhoseRowsAreItsRecordsGetsAStatementForEveryCheckToo(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "accounts"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + fixture.property("accountNote"); + declareKey(fixture, "accounts", List.of("id"), "email"); + final boolean postgres = POSTGRES.equals(fixture.family()); + final OntologyConcept account = fixture.type("Account"); + final Accounts accounts = + new Accounts( + fixture, + declare( + ontology, + fixture, + "AccountShape", + "Account", + on(fixture, "no-required", "accountNo").withMinCount(1), + on(fixture, "email-count", "accountEmail").withMinCount(1).withMaxCount(1), + on(fixture, "email-listed", "accountEmail").withIn(literals("a", "b")), + on(fixture, "nick-listed", "accountNick").withIn(literals("x")), + on(fixture, "nick-pattern", "accountNick").withPattern("^[0-9]{3}$"), + on(fixture, "age-range", "accountAge") + .withDatatypeIri(URI.create(XSD + "integer")) + .withMinInclusive(limit("0")) + .withMaxInclusive(limit("120")), + on(fixture, "email-type", "accountEmail") + .withDatatypeIri(URI.create(XSD + "date")), + on(fixture, "note-required", "accountNote").withMinCount(1), + on(fixture, "nick-class", "accountNick").withClassIri(account.getIri()))); + final OntologyCheckedPart requiredPart = + accounts.checked( + "email-count", MIN_COUNT, accounts.test("email", accounts.countWithout("email"))); + final OntologyCheckedPart emailListedPart = + accounts.checked( + "email-listed", + IN, + accounts.test("email", accounts.countWhere("email", "{} NOT IN ('a', 'b')"))); + final OntologyCheckedPart nickListedPart = + accounts.checked( + "nick-listed", + IN, + accounts.test("nick", accounts.countWhere("nick", "{} NOT IN ('x')"))); + // A pattern is matched on Postgres only, and no other engine gets a statement for one. + final OntologyCheckedPart matched = + postgres + ? accounts.checked( + "nick-pattern", + PATTERN, + accounts.test( + "nick", + accounts.countWhere( + "nick", "NOT (CAST({} AS text) COLLATE \"C\" ~ '^[0-9]{3}$')"))) + : entry(PATTERN, NOT_ENFORCEABLE) + .withReason(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED); + final OntologyCheckedPart rangedPart = + accounts.checked( + "age-range", + RANGE, + accounts.test("age", accounts.countWhere("age", "({} < 0 OR {} > 120)"))); + final List constraints = + List.of( + accounts.constraint("no-required", "accountNo", entry(MIN_COUNT, HELD_BY_MAPPING)), + accounts.constraint( + "email-count", "accountEmail", requiredPart, entry(MAX_COUNT, HELD_BY_MAPPING)), + accounts.constraint("email-listed", "accountEmail", emailListedPart), + accounts.constraint("nick-listed", "accountNick", nickListedPart), + accounts.constraint("nick-pattern", "accountNick", matched), + accounts.constraint( + "age-range", "accountAge", entry(DATATYPE, HELD_BY_MAPPING), rangedPart), + accounts.constraint( + "email-type", + "accountEmail", + entry(DATATYPE, NOT_ENFORCEABLE) + .withReason(OntologyShapeCheckReason.DATATYPE_MISMATCH)), + accounts.constraint("note-required", "accountNote", entry(MIN_COUNT, NOT_MAPPED)), + accounts.constraint( + "nick-class", + "accountNick", + entry(CLASS, NOT_ENFORCEABLE) + .withReason(OntologyShapeCheckReason.NOT_A_RELATION))); + final OntologyShapeChecks expected = + new OntologyShapeChecks() + .withConceptId(account.getId()) + .withClassIri(account.getIri()) + .withVersion( + new OntologyStatementVersionRead() + .withKind(DRAFT) + .withWorkingRevision( + admin().ontologies().state(ontology.getId()).getWorkingRevision())) + .withShapes( + List.of( + new OntologyCheckedShape() + .withId(accounts.shape().getId()) + .withName("AccountShape") + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints(constraints))); + + assertEquals( + JsonUtils.readTree(JsonUtils.pojoToJson(expected)), + JsonUtils.readTree(answer(admin(), account, DRAFT))); + + // The table has no row yet, and a statement counts nothing on an empty table. + final OntologyShapeChecks checks = checks(admin(), account, DRAFT); + final OntologyShapeCheck required = check(checks, "email-count", MIN_COUNT); + final OntologyShapeCheck emailListed = check(checks, "email-listed", IN); + final OntologyShapeCheck nickListed = check(checks, "nick-listed", IN); + final OntologyShapeCheck ranged = check(checks, "age-range", RANGE); + final List run = List.of(required, emailListed, nickListed, ranged); + run.forEach(check -> assertCounts("0", List.of(), check)); + + // Account 2 has no nick, and a null breaks no list. + addRows(fixture, "accounts", row(1, "a", "x", 10), row(2, "b", null, 120)); + run.forEach(check -> assertCounts("0", List.of(), check)); + + // One account breaks each part. The catalog says that email holds no null and that id is + // the key, and the table holds a null email and a row with no id all the same. + addRows( + fixture, + "accounts", + row(3, null, "x", 30), + row(4, "c", "x", 40), + row(5, "a", "y", 50), + row(6, "a", "x", 121), + row(null, "c", "y", 500)); + assertCounts("1", List.of(List.of("3")), required); + assertCounts("1", List.of(List.of("4")), emailListed); + assertCounts("1", List.of(List.of("5")), nickListed); + assertCounts("1", List.of(List.of("6")), ranged); + if (postgres) { + // Account 2 has no nick and account 8 has one of three digits. + addRows(fixture, "accounts", row(7, "a", "12x", 1), row(8, "a", "123", 1)); + assertCounts( + "6", + List.of( + List.of("1"), List.of("3"), List.of("4"), List.of("5"), List.of("6"), List.of("7")), + check(checks, "nick-pattern", PATTERN)); + } + } + } + + @Test + void aSubclassOnTheFilteredTableOfTheNamedClassLeavesNoExactTest(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "subclass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, PARTIES)) { + fixture.bindAll(); + declare( + ontology, + fixture, + "OrderShape", + "Order", + on(fixture, "placed-by", "placedBy").withClassIri(fixture.type("Person").getIri())); + assertEquals( + CHECK, outcome(checks(admin(), fixture.type("Order"), DRAFT), "placed-by", CLASS)); + + final OntologyAxiom subclass = + admin() + .ontologyAxioms() + .create( + new CreateOntologyAxiom() + .withName("organizationIsPerson") + .withDisplayName("organizationIsPerson") + .withDescription("An organization is a person before the law") + .withOntology(ontology.getFullyQualifiedName()) + .withAxiomType(OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(fixture.type("Organization").getIri()) + .withProvenance(RelationProvenance.MANUAL) + .withExpressions( + List.of( + new OntologyExpression() + .withKind(OntologyExpressionKind.NAMED_CLASS) + .withClassIri(fixture.type("Person").getIri())))); + final OntologyShapeChecks drafted = checks(admin(), fixture.type("Order"), DRAFT); + assertEquals(NOT_ENFORCEABLE, outcome(drafted, "placed-by", CLASS)); + assertEquals( + OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE, reason(drafted, "placed-by", CLASS)); + assertNull(part(drafted, "placed-by", CLASS).getChecks()); + + activate(ns, ontology); + admin().ontologyAxioms().delete(subclass.getId().toString()); + + // The release still holds the subclass step that the draft lost. + assertEquals( + OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE, + reason(checks(admin(), fixture.type("Order"), RELEASE), "placed-by", CLASS)); + assertEquals( + CHECK, outcome(checks(admin(), fixture.type("Order"), DRAFT), "placed-by", CLASS)); + } + } + + @Test + void aCrowdOnOneFilteredTableOfADraftDoesNotHideASubclassOnAnotherFromTheCap( + final TestNamespace ns) { + assertBothClassPartsShareTheirTables(ns, DRAFT); + } + + @Test + void aCrowdOnOneFilteredTableOfAReleaseDoesNotHideASubclassOnAnotherFromTheCap( + final TestNamespace ns) { + assertBothClassPartsShareTheirTables(ns, RELEASE); + } + + /** + * Target0's table holds 101 identity bindings of classes that are no subclass of it, which is one + * more than the cap. Target1's table holds one subclass of Target1. A cap that counted both tables + * together would leave one of them unread and answer {@code check} for its class. + */ + private static void assertBothClassPartsShareTheirTables( + final TestNamespace ns, final OntologyStatementVersion version) { + final String name = "cap" + version.value(); + final Ontology ontology = createOntology(ns, name); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture( + ns, ontology, targets(name, 2, new FilterSpec("title", NOT_EQUALS, "x")))) { + fixture.bindAll(); + for (int crowd = 0; crowd < 101; crowd++) { + sharesTable(fixture, "Crowd" + crowd, name + "_targets0"); + } + sharesTable(fixture, "Sub1", name + "_targets1"); + subclassOf(ontology, fixture.type("Sub1"), fixture.type("Target1")); + declare( + ontology, + fixture, + "Targets", + "Order", + on(fixture, "class0", "reaches0").withClassIri(fixture.type("Target0").getIri()), + on(fixture, "class1", "reaches1").withClassIri(fixture.type("Target1").getIri())); + if (version == RELEASE) { + activate(ns, ontology); + } + final OntologyShapeChecks answered = checks(admin(), fixture.type("Order"), version); + + for (final String constraint : List.of("class0", "class1")) { + assertEquals(NOT_ENFORCEABLE, outcome(answered, constraint, CLASS), constraint); + assertEquals( + OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE, + reason(answered, constraint, CLASS), + constraint); + } + } + } + + private static void sharesTable( + final OntologyShapeFixture fixture, final String type, final String table) { + fixture.bind( + new BindingSpec( + type, table, OntologyBindingRole.IDENTITY, List.of("sku"), null, List.of())); + } + + private static void subclassOf( + final Ontology ontology, final OntologyConcept child, final OntologyConcept parent) { + admin() + .ontologyAxioms() + .create( + new CreateOntologyAxiom() + .withName(child.getName() + "Is" + parent.getName()) + .withDisplayName(child.getName() + "Is" + parent.getName()) + .withDescription("A subclass step of a class that shares a table") + .withOntology(ontology.getFullyQualifiedName()) + .withAxiomType(OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(child.getIri()) + .withProvenance(RelationProvenance.MANUAL) + .withExpressions( + List.of( + new OntologyExpression() + .withKind(OntologyExpressionKind.NAMED_CLASS) + .withClassIri(parent.getIri())))); + } + + @Test + void aRelationBoundOnlyOnItsInverseIsNotEnforceableFromThisSide(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "inverse"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, PARTIES)) { + fixture.bindAll(); + final OntologyProperty places = + admin() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName("places") + .withIri(PARTIES.iri("places")) + .withOntology(ontology.getFullyQualifiedName()) + .withKind(OntologyPropertyKind.OBJECT) + .withDomain(List.of(fixture.type("Person").getIri())) + .withRange(List.of(fixture.type("Order").getIri())) + .withInverse(fixture.property("placedBy").getIri())); + declare( + ontology, + fixture, + "PersonShape", + "Person", + new OntologyShapeConstraint() + .withId("places") + .withPath(places.getIri()) + .withMinCount(1) + .withMaxCount(5), + new OntologyShapeConstraint() + .withId("unknown") + .withPath(PARTIES.iri("neverDeclared")) + .withMinCount(1)); + + final OntologyShapeChecks checks = checks(admin(), fixture.type("Person"), DRAFT); + + assertEquals(NOT_ENFORCEABLE, outcome(checks, "places", MIN_COUNT)); + assertEquals(OntologyShapeCheckReason.BOUND_ON_INVERSE, reason(checks, "places", MIN_COUNT)); + assertEquals(OntologyShapeCheckReason.BOUND_ON_INVERSE, reason(checks, "places", MAX_COUNT)); + assertEquals(NOT_MAPPED, outcome(checks, "unknown", MIN_COUNT)); + } + } + + @Test + void anAnswerReadsTheVersionThatItsRequestNames(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "versions"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, MEMBERS)) { + fixture.bindAll(); + final OntologyShape released = + declare( + ontology, + fixture, + "ReleasedShape", + "Member", + on(fixture, "email-required", "memberEmail").withMinCount(1)); + final OntologyRelease release = current(activate(ns, ontology)); + declare( + ontology, + fixture, + "DraftedShape", + "Member", + on(fixture, "age-range", "memberAge").withMinInclusive(limit("0"))); + final OntologyConcept later = fixture.type("Later"); + final String lacks = + "Class https://example.org/members#Later is not in the active release of ontology " + + ontology.getFullyQualifiedName(); + + final OntologyShapeChecks byDefault = checks(admin(), fixture.type("Member"), null); + final OntologyShapeChecks drafted = checks(admin(), fixture.type("Member"), DRAFT); + + assertEquals( + new OntologyStatementVersionRead() + .withKind(RELEASE) + .withReleaseId(release.getId()) + .withReleaseRevision(release.getReleaseRevision()) + .withSemanticVersion(release.getSemanticVersion()), + byDefault.getVersion()); + assertEquals( + List.of(released.getId()), + byDefault.getShapes().stream().map(OntologyCheckedShape::getId).toList()); + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(byDefault), + OntologyShapeCheckFixtures.withoutProposals( + checks(admin(), fixture.type("Member"), RELEASE))); + assertEquals(DRAFT, drafted.getVersion().getKind()); + assertEquals( + List.of("DraftedShape", "ReleasedShape"), + drafted.getShapes().stream().map(OntologyCheckedShape::getName).toList()); + assertRefused(404, lacks, () -> checks(admin(), later, RELEASE)); + assertEquals(List.of(), checks(admin(), later, DRAFT).getShapes()); + assertStatus( + 400, + () -> + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/ontologyConcepts/" + + fixture.type("Member").getId() + + "/shapeChecks?version=latest", + null)); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java new file mode 100644 index 000000000000..7b13bb1e08af --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckDefinitionRightsIT.java @@ -0,0 +1,547 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.answer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.parts; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.HIDDEN; +import static org.openmetadata.schema.api.data.OntologyShapePart.CLASS; +import static org.openmetadata.schema.api.data.OntologyShapePart.IN; +import static org.openmetadata.schema.api.data.OntologyShapePart.MAX_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.MIN_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.RANGE; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.RELEASE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; + +import java.util.Arrays; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; + +/** + * What a reader who may not view a shape, or the property a constraint is about, reads from {@code + * GET /v1/ontologyConcepts/{id}/shapeChecks}. A shape the reader may not view is left out. A + * constraint about a property the reader may not view says only {@code hidden} for each part it + * states, and does not name the property. Every reader here holds every other right, so each + * reads the working draft too. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckDefinitionRightsIT extends BaseOntologyApprovalIT { + private static final String ORDER_SHAPE = "OrderShape"; + private static final String LINE_SHAPE = "LineShape"; + private static final String EVERY_RESOURCE = "All"; + private static final String NOT_THE_OWNER = "!isOwner()"; + private static final String FILTER_TEXT = "SecretProductFilter"; + private static final String OTHER_FILTER_TEXT = "OtherProductFilter"; + private static final List VERSIONS = List.of(RELEASE, DRAFT); + private static final List PROPERTIES = + List.of("orderChannel", "contains", "itemQuantity"); + + /** The parts that each constraint of the two shapes states, by the id of the constraint. */ + private static final Map> STATED = + Map.of( + "onChannel", List.of(IN), + "onProducts", List.of(MIN_COUNT, MAX_COUNT, CLASS), + "channelRequired", List.of(MIN_COUNT), + "onQuantity", List.of(RANGE)); + + /** + * Two shapes of the order class of the link table mapping, with an active release. Between them + * they state a part about each of its three properties, and they differ in name and severity. + */ + private record Scene(OntologyShapeFixture fixture, OntologyShape orders, OntologyShape lines) { + static Scene released( + final TestNamespace ns, final Ontology ontology, final OntologyShapeFixture fixture) { + fixture.bindAll(); + final OntologyShape orders = + declare( + ontology, + fixture, + ORDER_SHAPE, + "Order", + on(fixture, "onChannel", "orderChannel").withIn(literals("web", "store")), + on(fixture, "onProducts", "contains") + .withMinCount(1) + .withMaxCount(1) + .withClassIri(fixture.type("Product").getIri())); + final OntologyShape lines = + admin() + .ontologyShapes() + .create( + new CreateOntologyShape() + .withName(LINE_SHAPE) + .withDisplayName(LINE_SHAPE) + .withDescription("What the lines of an order must satisfy") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(fixture.type("Order").getIri()) + .withSeverity(OntologyShapeSeverity.WARNING) + .withConstraints( + List.of( + on(fixture, "channelRequired", "orderChannel").withMinCount(1), + on(fixture, "onQuantity", "itemQuantity") + .withMinInclusive(limit("1"))))); + activate(ns, ontology); + return new Scene(fixture, orders, lines); + } + + OntologyConcept order() { + return fixture.type("Order"); + } + + /** The answer as an administrator reads it now, which masks and leaves out nothing. */ + OntologyShapeChecks whole(final OntologyStatementVersion version) { + final OntologyShapeChecks whole = checks(admin(), order(), version); + assertEquals( + List.of(LINE_SHAPE, ORDER_SHAPE), + whole.getShapes().stream().map(OntologyCheckedShape::getName).toList()); + return whole; + } + + /** The whole answer with only the shape of this name. */ + OntologyShapeChecks only(final OntologyStatementVersion version, final String shape) { + final OntologyShapeChecks whole = whole(version); + return whole.withShapes( + whole.getShapes().stream().filter(found -> found.getName().equals(shape)).toList()); + } + + /** + * The whole answer with each of these constraints as a reader who may not view its property + * reads it: its id, and {@code hidden} for each part it states. + */ + OntologyShapeChecks masking(final OntologyStatementVersion version, final String... ids) { + final OntologyShapeChecks whole = whole(version); + for (final OntologyCheckedShape shape : whole.getShapes()) { + shape.setConstraints( + shape.getConstraints().stream() + .map(found -> Arrays.asList(ids).contains(found.getId()) ? hidden(found) : found) + .toList()); + } + return whole; + } + + /** + * The whole answer with the constraint of this id as a reader who may not view the class of + * its class part reads it: hidden for each part it states, and its path kept. + */ + OntologyShapeChecks maskingClassOf(final OntologyStatementVersion version, final String id) { + final OntologyShapeChecks whole = whole(version); + for (final OntologyCheckedShape shape : whole.getShapes()) { + shape.setConstraints( + shape.getConstraints().stream() + .map(found -> found.getId().equals(id) ? hiddenWithPath(found) : found) + .toList()); + } + return whole; + } + + private static OntologyCheckedConstraint hiddenWithPath(final OntologyCheckedConstraint found) { + return hidden(found).withPath(found.getPath()); + } + + private static OntologyCheckedConstraint hidden(final OntologyCheckedConstraint found) { + return new OntologyCheckedConstraint() + .withId(found.getId()) + .withParts( + STATED.get(found.getId()).stream() + .map(part -> new OntologyCheckedPart().withPart(part).withOutcome(HIDDEN)) + .toList()); + } + + void assertNamesNothingOf(final String body, final OntologyShape denied) { + assertFalse(body.contains(denied.getId().toString()), body); + assertFalse(body.contains(denied.getName()), body); + assertFalse(body.contains(denied.getSeverity().value()), body); + } + + void assertNamesNothingOf(final String body, final String property) { + final OntologyProperty denied = fixture.property(property); + assertFalse(body.contains(denied.getId().toString()), body); + assertFalse(body.contains(denied.getName()), body); + assertFalse(body.contains(denied.getIri().toString()), body); + } + } + + private static void assertAnswer(final OntologyShapeChecks expected, final String body) { + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(expected), + OntologyShapeCheckFixtures.withoutProposals(body)); + } + + private static void owns(final OpenMetadataClient reader, final OntologyShape shape) { + final String id = shape.getId().toString(); + admin() + .ontologyShapes() + .update( + id, + admin() + .ontologyShapes() + .get(id, "owners") + .withOwners(List.of(readerReference(reader)))); + } + + private static void owns(final OpenMetadataClient reader, final OntologyConcept type) { + final String id = type.getId().toString(); + admin() + .ontologyConcepts() + .update( + id, + admin() + .ontologyConcepts() + .get(id, "owners") + .withOwners(List.of(readerReference(reader)))); + } + + private static void owns(final OpenMetadataClient reader, final OntologyProperty property) { + final String id = property.getId().toString(); + admin() + .ontologyProperties() + .update( + id, + admin() + .ontologyProperties() + .get(id, "owners") + .withOwners(List.of(readerReference(reader)))); + } + + @Test + void aReaderWhoMayViewNoShapeReadsAnAnswerWithNoShape(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deniedShapes"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var basic = new RdfAccessFixtures("chkShB" + ns.shortPrefix()); + var all = new RdfAccessFixtures("chkShA" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + final List readers = + List.of( + callerWithout(basic, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_SHAPE, null), + callerWithout(all, MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_SHAPE, null)); + + for (final OntologyStatementVersion version : VERSIONS) { + for (final OpenMetadataClient reader : readers) { + final String body = answer(reader, scene.order(), version); + + assertAnswer(scene.whole(version).withShapes(List.of()), body); + scene.assertNamesNothingOf(body, scene.orders()); + scene.assertNamesNothingOf(body, scene.lines()); + } + } + } + } + + @Test + void aReaderWhoMayViewNoPropertyReadsHiddenForEveryConstraintAndNoPath(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deniedProperties"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var basic = new RdfAccessFixtures("chkPrB" + ns.shortPrefix()); + var all = new RdfAccessFixtures("chkPrA" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + final List readers = + List.of( + callerWithout(basic, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_PROPERTY, null), + callerWithout(all, MetadataOperation.VIEW_ALL, Entity.ONTOLOGY_PROPERTY, null)); + + for (final OntologyStatementVersion version : VERSIONS) { + for (final OpenMetadataClient reader : readers) { + final String body = answer(reader, scene.order(), version); + + assertAnswer( + scene.masking(version, "onChannel", "onProducts", "channelRequired", "onQuantity"), + body); + assertFalse(body.contains("\"path\""), body); + PROPERTIES.forEach(property -> scene.assertNamesNothingOf(body, property)); + } + } + } + } + + @Test + void aReaderReadsTheShapesAndThePropertiesTheyMayViewAsAnyoneReadsThem(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "ownedDefinitions"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var shapes = new RdfAccessFixtures("chkShO" + ns.shortPrefix()); + var properties = new RdfAccessFixtures("chkPrO" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + final OpenMetadataClient ofOneShape = + callerWithout(shapes, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_SHAPE, NOT_THE_OWNER); + final OpenMetadataClient ofTwoProperties = + callerWithout( + properties, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_PROPERTY, NOT_THE_OWNER); + owns(ofOneShape, scene.orders()); + owns(ofTwoProperties, fixture.property("orderChannel")); + owns(ofTwoProperties, fixture.property("itemQuantity")); + + for (final OntologyStatementVersion version : VERSIONS) { + final String oneShape = answer(ofOneShape, scene.order(), version); + final String twoProperties = answer(ofTwoProperties, scene.order(), version); + + assertAnswer(scene.only(version, ORDER_SHAPE), oneShape); + scene.assertNamesNothingOf(oneShape, scene.lines()); + assertAnswer(scene.masking(version, "onProducts"), twoProperties); + scene.assertNamesNothingOf(twoProperties, "contains"); + } + } + } + + /** Product's identity binding with a row filter whose value is {@code filterValue}. */ + private static void filterProducts(final OntologyShapeFixture fixture, final String filterValue) { + fixture.bind( + new BindingSpec( + "Product", + "products", + OntologyBindingRole.IDENTITY, + List.of("sku"), + new FilterSpec("title", OntologyRowFilterOperator.NOT_EQUALS, filterValue), + List.of(bound("productTitle", "title")))); + } + + @Test + void aReaderWhoMayNotViewTheClassOfAClassPartReadsHiddenAndNothingOfThatClass( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deniedClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("chkCl" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + filterProducts(fixture, FILTER_TEXT); + final OpenMetadataClient reader = + callerWithout( + access, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CONCEPT, NOT_THE_OWNER); + owns(reader, scene.order()); + final OntologyConcept product = fixture.type("Product"); + final Table products = fixture.table("products"); + + for (final OntologyStatementVersion version : VERSIONS) { + final String body = answer(reader, scene.order(), version); + final String whole = answer(admin(), scene.order(), version); + + assertAnswer(scene.maskingClassOf(version, "onProducts"), body); + final OntologyCheckedConstraint masked = + checks(reader, scene.order(), version).getShapes().stream() + .flatMap(shape -> shape.getConstraints().stream()) + .filter(found -> found.getId().equals("onProducts")) + .findFirst() + .orElseThrow(); + assertEquals(fixture.property("contains").getIri(), masked.getPath()); + assertEquals( + List.of(MIN_COUNT, MAX_COUNT, CLASS), + masked.getParts().stream().map(OntologyCheckedPart::getPart).toList()); + masked + .getParts() + .forEach( + part -> { + assertEquals(HIDDEN, part.getOutcome()); + assertNull(part.getChecks()); + }); + assertAbsent( + body, + product.getId().toString(), + product.getIri().toString(), + products.getId().toString(), + products.getName(), + products.getFullyQualifiedName(), + "sku", + FILTER_TEXT); + assertTrue(whole.contains(product.getId().toString()), whole); + assertTrue(whole.contains(products.getName()), whole); + assertTrue(whole.contains(FILTER_TEXT), whole); + assertEquals( + OntologyShapeCheckOutcome.CHECK, + parts(checks(admin(), scene.order(), version), "onProducts", CLASS) + .getFirst() + .getOutcome()); + } + } + } + + @Test + void aWriteToTheBindingOfAClassThatAReaderMayNotViewChangesNothingTheReaderReads( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deniedClassRevision"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("chkCv" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + filterProducts(fixture, FILTER_TEXT); + final OpenMetadataClient reader = + callerWithout( + access, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CONCEPT, NOT_THE_OWNER); + owns(reader, scene.order()); + final Map before = + new EnumMap<>(OntologyStatementVersion.class); + final Map adminBefore = + new EnumMap<>(OntologyStatementVersion.class); + for (final OntologyStatementVersion version : VERSIONS) { + before.put(version, answer(reader, scene.order(), version)); + adminBefore.put(version, answer(admin(), scene.order(), version)); + } + + filterProducts(fixture, OTHER_FILTER_TEXT); + + for (final OntologyStatementVersion version : VERSIONS) { + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(before.get(version)), + OntologyShapeCheckFixtures.withoutProposals(answer(reader, scene.order(), version))); + assertNotEquals(adminBefore.get(version), answer(admin(), scene.order(), version)); + } + } + } + + private static void assertAbsent(final String body, final String... texts) { + for (final String text : texts) { + assertFalse(body.contains(text), text + " in " + body); + } + } + + @Test + void aReaderWhoMayViewEverythingReadsTheBytesAnAdministratorReads(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "allowedReader"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("chkAll" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + final var everything = access.allowRole(MetadataOperation.ALL, EVERY_RESOURCE); + final OpenMetadataClient reader = + client(access.userToken("reader", List.of(everything.getId()))); + + for (final OntologyStatementVersion version : VERSIONS) { + final String body = answer(reader, scene.order(), version); + + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(answer(admin(), scene.order(), version)), + OntologyShapeCheckFixtures.withoutProposals(body)); + assertTrue(body.contains(scene.orders().getId().toString()), body); + assertTrue(body.contains(scene.lines().getId().toString()), body); + PROPERTIES.forEach( + property -> + assertTrue(body.contains(fixture.property(property).getIri().toString()), body)); + } + } + } + + @Test + void aReleasedShapeIsReadAsReleasedAfterItsWorkingRowIsDeleted(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedShape"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var owned = new RdfAccessFixtures("chkShD" + ns.shortPrefix()); + var denied = new RdfAccessFixtures("chkShN" + ns.shortPrefix())) { + final Scene scene = Scene.released(ns, ontology, fixture); + final OpenMetadataClient owner = + callerWithout(owned, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_SHAPE, NOT_THE_OWNER); + final OpenMetadataClient ofNoShape = + callerWithout(denied, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_SHAPE, null); + owns(owner, scene.lines()); + final String ownerRead = answer(owner, scene.order(), RELEASE); + final String everyoneRead = answer(admin(), scene.order(), RELEASE); + assertAnswer(scene.only(RELEASE, LINE_SHAPE), ownerRead); + + admin().ontologyShapes().delete(scene.lines().getId().toString()); + + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(ownerRead), + OntologyShapeCheckFixtures.withoutProposals(answer(owner, scene.order(), RELEASE))); + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(everyoneRead), + OntologyShapeCheckFixtures.withoutProposals(answer(admin(), scene.order(), RELEASE))); + scene.assertNamesNothingOf(answer(ofNoShape, scene.order(), RELEASE), scene.lines()); + assertEquals( + List.of(ORDER_SHAPE), + checks(admin(), scene.order(), DRAFT).getShapes().stream() + .map(OntologyCheckedShape::getName) + .toList()); + } + } + + @Test + void aReleasedClassPartIsReadAsReleasedAfterItsClassIsDeleted(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("chkClD" + ns.shortPrefix())) { + fixture.bindAll(); + fixture.bind( + new BindingSpec( + "Stock", "products", OntologyBindingRole.IDENTITY, List.of("sku"), null, List.of())); + final OntologyConcept stock = fixture.type("Stock"); + final OntologyShape shape = + declare( + ontology, + fixture, + ORDER_SHAPE, + "Order", + on(fixture, "onStock", "contains").withClassIri(stock.getIri())); + final OpenMetadataClient owner = + callerWithout( + access, MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CONCEPT, NOT_THE_OWNER); + owns(owner, fixture.type("Order")); + owns(owner, stock); + activate(ns, ontology); + final String ownerRead = answer(owner, fixture.type("Order"), RELEASE); + final String everyoneRead = answer(admin(), fixture.type("Order"), RELEASE); + assertEquals( + OntologyShapeCheckOutcome.CHECK, + parts(checks(owner, fixture.type("Order"), RELEASE), "onStock", CLASS) + .getFirst() + .getOutcome()); + + admin().ontologyShapes().delete(shape.getId().toString()); + admin().ontologyConcepts().delete(stock.getId().toString()); + + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(ownerRead), + OntologyShapeCheckFixtures.withoutProposals( + answer(owner, fixture.type("Order"), RELEASE))); + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(everyoneRead), + OntologyShapeCheckFixtures.withoutProposals( + answer(admin(), fixture.type("Order"), RELEASE))); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java new file mode 100644 index 000000000000..ad05386b82de --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckFixtures.java @@ -0,0 +1,552 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import org.apache.commons.codec.digest.DigestUtils; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyMappingShapes.TableSpec; + +/** + * What the tests of {@code GET /v1/ontologyConcepts/{id}/shapeChecks} share: a mapping written as + * its tables, classes and bindings, the shapes of a class, the answer of the endpoint, and a check + * run against the database of the suite as the test runner would send it. + */ +final class OntologyShapeCheckFixtures { + static final String CUSTOM_SQL = "tableCustomSQLQuery"; + private static final String GOLDEN_CHECKS = "/ontology/shape-checks/%s/%s.sql"; + private static final String COUNT_OPENING = "SELECT COUNT(*) AS violations\nFROM (\n"; + private static final String COUNT_CLOSING = "\n) c"; + + /** One table with no declared key, so its rows are not its records one for one. */ + static final Shape MEMBERS = + mapping( + "members", + List.of( + table( + "members", + List.of(integer("id"), text("email"), integer("age")), + row(1, "ada@example.org", 30), + row(2, "grace@example.org", 40))), + List.of("Member"), + List.of(data("memberEmail", "Member"), data("memberAge", "Member")), + identityTable( + "Member", + "members", + List.of("id"), + null, + bound("memberEmail", "email"), + bound("memberAge", "age"))); + + /** People and organizations share one table, and an order names the person who placed it. */ + static final Shape PARTIES = + mapping( + "parties", + List.of( + table( + "parties", + List.of(integer("id"), text("kind"), text("name")), + row(1, "person", "Ada"), + row(2, "person", "Grace"), + row(10, "org", "Initech")), + table( + "orders", + List.of(integer("id"), integer("party_id"), decimal("total")), + row(100, 1, new BigDecimal("10.00")), + row(101, 1, new BigDecimal("20.00")), + row(102, 2, new BigDecimal("5.00")))), + List.of("Person", "Organization", "Order"), + List.of( + data("personName", "Person"), + data("organizationName", "Organization"), + relation("placedBy", "Order", "Person")), + identityTable( + "Person", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "person"), + bound("personName", "name")), + identityTable( + "Organization", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "org"), + bound("organizationName", "name")), + identityTable( + "Order", + "orders", + List.of("id"), + null, + joined("placedBy", "party_id", "parties", "id"))); + + private OntologyShapeCheckFixtures() {} + + /** + * An order class that reaches {@code classes} other classes, each through a table of its own and + * each with an identity table of its own, so every relation can state a {@code class} part. + */ + static Shape targets(final String name, final int classes, final FilterSpec filter) { + final List tables = + new ArrayList<>(List.of(table(name + "_orders", List.of(integer("id"), text("channel"))))); + final List types = new ArrayList<>(List.of("Order")); + final List properties = new ArrayList<>(List.of(data("orderChannel", "Order"))); + final List bindings = + new ArrayList<>( + List.of( + identityTable( + "Order", + name + "_orders", + List.of("id"), + null, + bound("orderChannel", "channel")))); + for (int target = 0; target < classes; target++) { + tables.add(table(name + "_targets" + target, List.of(text("sku"), text("title")))); + tables.add(table(name + "_links" + target, List.of(integer("order_id"), text("sku")))); + types.add("Target" + target); + properties.add(data("title" + target, "Target" + target)); + properties.add(relation("reaches" + target, "Order", "Target" + target)); + bindings.add( + identityTable( + "Target" + target, + name + "_targets" + target, + List.of("sku"), + filter, + bound("title" + target, "title"))); + bindings.add( + contributing( + "Order", + name + "_links" + target, + List.of("order_id"), + joined("reaches" + target, "sku", name + "_targets" + target, "sku"))); + } + return mapping(name, tables, types, properties, bindings.toArray(BindingSpec[]::new)); + } + + static ColumnSpec integer(final String name) { + return new ColumnSpec(name, ColumnDataType.INT); + } + + static ColumnSpec text(final String name) { + return new ColumnSpec(name, ColumnDataType.VARCHAR); + } + + static ColumnSpec decimal(final String name) { + return new ColumnSpec(name, ColumnDataType.DECIMAL); + } + + @SafeVarargs + static TableSpec table( + final String name, final List columns, final List... rows) { + return new TableSpec(name, columns, List.of(rows)); + } + + /** A row that may hold nulls, which {@code List.of} refuses. */ + static List row(final Object... values) { + return Arrays.asList(values); + } + + static PropertySpec data(final String name, final String domain) { + return new PropertySpec(name, false, domain, null); + } + + static PropertySpec relation(final String name, final String domain, final String range) { + return new PropertySpec(name, false, domain, range); + } + + static ColumnBindingSpec bound(final String property, final String column) { + return new ColumnBindingSpec(property, column, null); + } + + /** A relation held in one column, with a confirmed join onto one column of the target. */ + static ColumnBindingSpec joined( + final String property, final String column, final String target, final String parent) { + return joined(property, target, List.of(column), List.of(parent)); + } + + /** A relation with a confirmed join of several columns. The binding names the first of them. */ + static ColumnBindingSpec joined( + final String property, + final String target, + final List child, + final List parent) { + return new ColumnBindingSpec( + property, + child.getFirst(), + new JoinSpec(target, OntologyJoinStatus.CONFIRMED, child, parent)); + } + + static BindingSpec identityTable( + final String type, + final String table, + final List key, + final FilterSpec filter, + final ColumnBindingSpec... columns) { + return new BindingSpec( + type, table, OntologyBindingRole.IDENTITY, key, filter, List.of(columns)); + } + + static BindingSpec contributing( + final String type, + final String table, + final List key, + final ColumnBindingSpec... columns) { + return new BindingSpec( + type, table, OntologyBindingRole.CONTRIBUTING, key, null, List.of(columns)); + } + + /** A mapping with no statement to ask of it. */ + static Shape mapping( + final String name, + final List tables, + final List classes, + final List properties, + final BindingSpec... bindings) { + return new Shape(name, tables, classes, properties, List.of(bindings), List.of()); + } + + /** A literal with no datatype, as a bound of a range or a member of a list. */ + static OntologyLiteral limit(final String value) { + return new OntologyLiteral().withValue(value); + } + + static List literals(final String... values) { + return Arrays.stream(values) + .map(value -> new OntologyShapeValue().withLiteral(limit(value))) + .toList(); + } + + /** A constraint on one property of the mapping, ready for the parts a test states. */ + static OntologyShapeConstraint on( + final OntologyShapeFixture fixture, final String id, final String property) { + return new OntologyShapeConstraint().withId(id).withPath(fixture.property(property).getIri()); + } + + /** Saves a shape that targets one class of the mapping in the working draft. */ + static OntologyShape declare( + final Ontology ontology, + final OntologyShapeFixture fixture, + final String name, + final String type, + final OntologyShapeConstraint... constraints) { + return admin() + .ontologyShapes() + .create( + new CreateOntologyShape() + .withName(name) + .withDisplayName(name) + .withDescription("What a record of " + type + " must satisfy") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(fixture.type(type).getIri()) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints(List.of(constraints))); + } + + /** The catalog declares a primary key of the table, and the columns that never hold a null. */ + static void declareKey( + final OntologyShapeFixture fixture, + final String tableName, + final List key, + final String... neverNull) { + final String id = fixture.table(tableName).getId().toString(); + final Table table = admin().tables().get(id, "tableConstraints"); + table.getColumns().stream() + .filter(column -> List.of(neverNull).contains(column.getName())) + .forEach(column -> column.setConstraint(ColumnConstraint.NOT_NULL)); + admin() + .tables() + .update( + id, + table.withTableConstraints( + List.of( + new TableConstraint() + .withConstraintType(TableConstraint.ConstraintType.PRIMARY_KEY) + .withColumns(key)))); + } + + /** Adds rows to a table that the fixture created in the database of the suite. */ + @SafeVarargs + static void addRows( + final OntologyShapeFixture fixture, final String tableName, final List... rows) { + final int width = fixture.shape().table(tableName).columns().size(); + final String insert = + "INSERT INTO " + + fixture.from(tableName) + + " VALUES (" + + String.join(", ", Collections.nCopies(width, "?")) + + ")"; + TestSuiteBootstrap.getJdbi() + .useHandle( + handle -> { + try (PreparedStatement row = handle.getConnection().prepareStatement(insert)) { + for (final List values : rows) { + for (int column = 0; column < width; column++) { + row.setObject(column + 1, values.get(column)); + } + row.executeUpdate(); + } + } catch (final SQLException failed) { + throw new IllegalStateException(insert, failed); + } + }); + } + + private static String path(final OntologyConcept type, final OntologyStatementVersion version) { + return "/v1/ontologyConcepts/" + + type.getId() + + "/shapeChecks" + + (version == null ? "" : "?version=" + version.value()); + } + + /** + * Asks how the shapes of a class are checked, as {@code client}. + * + * @param version the version to read, or null to name none + */ + static OntologyShapeChecks checks( + final OpenMetadataClient client, + final OntologyConcept type, + final OntologyStatementVersion version) { + return client + .getHttpClient() + .execute(HttpMethod.GET, path(type, version), null, OntologyShapeChecks.class); + } + + /** + * The body of an answer without the {@code proposal} of each check. A proposal follows the + * reconcile that an activation starts, and these answers are compared for what the compile says. + */ + static JsonNode withoutProposals(final String body) { + final JsonNode tree = JsonUtils.readTree(body); + tree.findParents("proposal").forEach(parent -> ((ObjectNode) parent).remove("proposal")); + return tree; + } + + static JsonNode withoutProposals(final Object answer) { + return withoutProposals(JsonUtils.pojoToJson(answer)); + } + + /** The body of the answer to {@link #checks}, as the server wrote it. */ + static String answer( + final OpenMetadataClient client, + final OntologyConcept type, + final OntologyStatementVersion version) { + return client.getHttpClient().executeForString(HttpMethod.GET, path(type, version), null); + } + + /** The entries of one part of the constraint with this id, in the first shape that holds it. */ + static List parts( + final OntologyShapeChecks checks, final String constraintId, final OntologyShapePart part) { + return checks.getShapes().stream() + .flatMap(shape -> shape.getConstraints().stream()) + .filter(constraint -> constraint.getId().equals(constraintId)) + .findFirst() + .map(OntologyCheckedConstraint::getParts) + .orElseThrow() + .stream() + .filter(entry -> entry.getPart() == part) + .toList(); + } + + /** The one entry of a part that every table answers alike. */ + static OntologyCheckedPart part( + final OntologyShapeChecks checks, final String constraintId, final OntologyShapePart part) { + final List entries = parts(checks, constraintId, part); + assertEquals(1, entries.size(), () -> constraintId + " " + part + " " + entries); + return entries.getFirst(); + } + + /** The one test of a part that one table checks. */ + static OntologyShapeCheck check( + final OntologyShapeChecks checks, final String constraintId, final OntologyShapePart part) { + final OntologyCheckedPart entry = part(checks, constraintId, part); + assertEquals(1, entry.getChecks() == null ? 0 : entry.getChecks().size(), entry::toString); + return entry.getChecks().getFirst(); + } + + static String parameter(final OntologyShapeCheck check, final String name) { + return check.getParameterValues().stream() + .filter(parameter -> parameter.getName().equals(name)) + .map(TestCaseParameterValue::getValue) + .findFirst() + .orElseThrow(); + } + + static TestCaseParameterValue parameter(final String name, final String value) { + return new TestCaseParameterValue().withName(name).withValue(value); + } + + /** The parameters of a generated test around its statement. */ + static List countParameters(final String sqlExpression) { + return List.of( + parameter("sqlExpression", sqlExpression), + parameter("strategy", "COUNT"), + parameter("operator", "<="), + parameter("threshold", "0")); + } + + /** + * The number a generated test returns on the rows the tables hold now. The runner hands the + * statement to a reader of {@code :name} parameters, which reads {@code \:} as a colon, so the + * database gets the statement with its colons back. + */ + static String violations(final OntologyShapeCheck check) { + final List> rows = + OntologyShapeFixture.run(parameter(check, "sqlExpression").replace("\\:", ":")); + assertEquals(1, rows.size(), rows::toString); + assertEquals(1, rows.getFirst().size(), rows::toString); + return rows.getFirst().getFirst(); + } + + /** The keys of the records in violation on the rows the tables hold now, in key order. */ + static List> keys(final OntologyShapeCheck check) { + return OntologyShapeFixture.run(check.getInspectionQuery()).stream() + .sorted(Comparator.comparing(List::toString)) + .toList(); + } + + /** The test counts this many records in violation, and its list of keys names exactly them. */ + static void assertCounts( + final String expected, + final List> expectedKeys, + final OntologyShapeCheck check) { + assertEquals(expected, violations(check), check::getInspectionQuery); + assertEquals(expectedKeys, keys(check), check::getInspectionQuery); + } + + static OntologyShapeCheckBinding read( + final OntologyShapeFixture fixture, + final String type, + final String tableName, + final long revision) { + return new OntologyShapeCheckBinding() + .withConceptId(fixture.type(type).getId()) + .withAssetId(fixture.table(tableName).getId()) + .withRevision(revision); + } + + /** + * The name of a check: the SHA-256 of what it checks, each part kept from the next by a + * character that none of them holds. + * + * @param holder the binding of the table the check belongs to + */ + static String identity( + final OntologyShape shape, + final String constraintId, + final OntologyShapePart part, + final OntologyShapeCheckBinding holder, + final List columnPath) { + return DigestUtils.sha256Hex( + String.join( + "\u001f", + shape.getId().toString(), + constraintId, + part.value(), + holder.getConceptId().toString(), + holder.getAssetId().toString(), + String.join("\u001e", columnPath))); + } + + /** The table as an answer names it. */ + static EntityReference reference(final OntologyShapeFixture fixture, final String tableName) { + return admin().tables().get(fixture.table(tableName).getId().toString()).getEntityReference(); + } + + /** + * The golden count statement of one part of a mapping shape of the service module, as the engine + * family of this database writes it, with the tables of this fixture in place of the tables of + * the golden schema. + * + * @param name the file name without its extension, as {@code linkTable-contains-class} + */ + static String goldenCount(final OntologyShapeFixture fixture, final String name) { + final String resource = String.format(GOLDEN_CHECKS, fixture.family(), name); + String text; + try (InputStream file = OntologyShapeCheckFixtures.class.getResourceAsStream(resource)) { + text = new String(file.readAllBytes(), StandardCharsets.UTF_8).stripTrailing(); + } catch (final IOException unread) { + throw new UncheckedIOException(resource, unread); + } + final List tables = + fixture.shape().tables().stream() + .map(TableSpec::name) + .sorted(Comparator.comparing(String::length).reversed()) + .toList(); + for (final String table : tables) { + text = text.replace(goldenName(fixture, table), fixture.from(table)); + } + return text; + } + + private static String goldenName(final OntologyShapeFixture fixture, final String table) { + return "mysql".equals(fixture.family()) ? "`shop`.`" + table + "`" : "shop." + table; + } + + /** The list of keys that a count statement counts: its inner statement, one level out. */ + static String keyList(final String count) { + final String inner = + count.substring(COUNT_OPENING.length(), count.length() - COUNT_CLOSING.length()); + return inner.lines().map(line -> line.substring(2)).reduce((a, b) -> a + "\n" + b).orElse(""); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckIT.java new file mode 100644 index 000000000000..c5ce99da5045 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckIT.java @@ -0,0 +1,464 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.CUSTOM_SQL; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.MEMBERS; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.PARTIES; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.addRows; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.assertCounts; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.check; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.contributing; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.countParameters; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.data; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identityTable; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.integer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.joined; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.mapping; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.parameter; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.read; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.relation; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.row; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.table; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.text; +import static org.openmetadata.schema.api.data.OntologyShapePart.CLASS; +import static org.openmetadata.schema.api.data.OntologyShapePart.IN; +import static org.openmetadata.schema.api.data.OntologyShapePart.MAX_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.MIN_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.RANGE; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; + +import java.math.BigDecimal; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * Runs the generated tests of {@code GET /v1/ontologyConcepts/{id}/shapeChecks} on the database + * this suite runs on. Each test runs twice: on rows that satisfy its constraint, where it must + * count no record, and on rows that break it, where it must count exactly the records the case + * names and list their keys. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckIT extends BaseOntologyApprovalIT { + private static final List> NO_KEYS = List.of(); + private static final String MYSQL = "mysql"; + + /** Web orders only, each with the products a link table gives it. */ + private static final Shape BASKETS = + mapping( + "baskets", + List.of( + table( + "orders", + List.of(integer("id"), text("channel")), + row(1, "web"), + row(2, "web"), + row(7, "internal")), + table( + "products", + List.of(text("sku"), text("title")), + row("A-1", "Anvil"), + row("B-2", "Bolt")), + table( + "order_items", + List.of(integer("order_id"), text("product_sku"), integer("quantity")), + row(1, "A-1", 2), + row(1, "A-1", 3), + row(2, "B-2", 1), + row(7, "ZZ-9", 0), + row(99, "ZZ-9", 0))), + List.of("Order", "Product"), + List.of( + data("orderChannel", "Order"), + data("productTitle", "Product"), + data("itemQuantity", "Order"), + relation("contains", "Order", "Product")), + identityTable( + "Order", + "orders", + List.of("id"), + new FilterSpec("channel", OntologyRowFilterOperator.EQUALS, "web"), + bound("orderChannel", "channel")), + identityTable( + "Product", "products", List.of("sku"), null, bound("productTitle", "title")), + contributing( + "Order", + "order_items", + List.of("order_id"), + bound("itemQuantity", "quantity"), + joined("contains", "product_sku", "products", "sku"))); + + /** A shipment names its account with two columns, the two-column key of the account table. */ + private static final Shape SHIPMENTS = + mapping( + "shipments", + List.of( + table( + "accounts", + List.of(text("tenant"), integer("account_no"), text("tier")), + row("eu", 1, "gold"), + row("us", 1, "silver")), + table( + "shipments", + List.of( + text("tenant"), + integer("shipment_no"), + text("account_tenant"), + integer("account_no")), + row("eu", 10, "eu", 1), + row("us", 11, "us", 1))), + List.of("Account", "Shipment"), + List.of(data("accountTier", "Account"), relation("shippedTo", "Shipment", "Account")), + identityTable( + "Account", + "accounts", + List.of("tenant", "account_no"), + null, + bound("accountTier", "tier")), + identityTable( + "Shipment", + "shipments", + List.of("tenant", "shipment_no"), + null, + joined( + "shippedTo", + "accounts", + List.of("account_tenant", "account_no"), + List.of("tenant", "account_no")))); + + @Test + void aNullIsNoValueAndARowWithoutAKeyIsNoRecord(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "members"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, MEMBERS).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "MemberShape", + "Member", + on(fixture, "email-required", "memberEmail").withMinCount(1), + on(fixture, "email-once", "memberEmail").withMaxCount(1), + on(fixture, "email-listed", "memberEmail") + .withIn(literals("ada@example.org", "grace@example.org")), + on(fixture, "age-range", "memberAge") + .withMinInclusive(limit("0")) + .withMaxInclusive(limit("120"))); + + final OntologyShapeChecks checks = checks(admin(), fixture.type("Member"), DRAFT); + final OntologyShapeCheck required = check(checks, "email-required", MIN_COUNT); + final OntologyShapeCheck once = check(checks, "email-once", MAX_COUNT); + final OntologyShapeCheck listed = check(checks, "email-listed", IN); + final OntologyShapeCheck range = check(checks, "age-range", RANGE); + + final String id = fixture.name("id"); + final String countOfListed = + String.join( + "\n", + "SELECT COUNT(*) AS violations", + "FROM (", + " SELECT DISTINCT t0." + id + " AS k0", + " FROM " + fixture.from("members") + " t0", + " WHERE t0." + id + " IS NOT NULL", + " AND t0." + + fixture.name("email") + + " NOT IN ('ada@example.org', 'grace@example.org')", + ") c"); + assertEquals(CUSTOM_SQL, listed.getTestDefinition()); + assertEquals( + "<#E::table::" + fixture.table("members").getFullyQualifiedName() + ">", + listed.getEntityLink()); + assertEquals(countParameters(countOfListed), listed.getParameterValues()); + assertEquals(List.of(List.of("email")), listed.getColumns()); + for (final OntologyShapeCheck check : List.of(required, once, listed, range)) { + assertCounts("0", NO_KEYS, check); + } + + // Member 3 has no email. Member 4 has one in its second row. The row with no id is no member. + addRows( + fixture, + "members", + row(3, null, null), + row(4, null, 50), + row(4, "ada@example.org", 50), + row(null, "nobody@example.org", 500), + row(5, "intruder@example.org", 200), + row(6, "ada@example.org", 1), + row(6, "grace@example.org", 1), + row(7, "ada@example.org", 2), + row(7, "ada@example.org", 2)); + + assertCounts("1", List.of(List.of("3")), required); + assertCounts("1", List.of(List.of("6")), once); + assertCounts("1", List.of(List.of("5")), listed); + assertCounts("1", List.of(List.of("5")), range); + } + } + + @Test + void aRelationReachesOnlyTheRecordsOfTheClassItNamesOnASharedTable(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "parties"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, PARTIES).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "OrderShape", + "Order", + on(fixture, "placed-by", "placedBy") + .withMinCount(1) + .withMaxCount(1) + .withClassIri(fixture.type("Person").getIri())); + declare( + ontology, + fixture, + "PersonShape", + "Person", + on(fixture, "name-listed", "personName").withIn(literals("Ada", "Grace"))); + + final OntologyShapeChecks orders = checks(admin(), fixture.type("Order"), DRAFT); + final OntologyShapeCheck placed = check(orders, "placed-by", MIN_COUNT); + final OntologyShapeCheck placedOnce = check(orders, "placed-by", MAX_COUNT); + final OntologyShapeCheck byPerson = check(orders, "placed-by", CLASS); + final OntologyShapeCheck named = + check(checks(admin(), fixture.type("Person"), DRAFT), "name-listed", IN); + + assertEquals( + List.of(read(fixture, "Order", "orders", 1L), read(fixture, "Person", "parties", 1L)), + byPerson.getReadBindings()); + assertEquals(fixture.table("orders").getId(), byPerson.getTable().getId()); + assertEquals(List.of(List.of("party_id")), byPerson.getColumns()); + // Ada placed two orders, and an order still has one person. Initech is no person. + for (final OntologyShapeCheck check : List.of(placed, placedOnce, byPerson, named)) { + assertCounts("0", NO_KEYS, check); + } + + // Order 103 names a party that no row holds, and order 104 an organization. + addRows( + fixture, + "orders", + row(103, 999, new BigDecimal("1.00")), + row(104, 10, new BigDecimal("1.00")), + row(105, null, new BigDecimal("1.00")), + row(106, 1, new BigDecimal("1.00")), + row(106, 2, new BigDecimal("1.00"))); + addRows(fixture, "parties", row(3, "person", "Mallory"), row(11, "org", "Globex")); + + assertCounts("1", List.of(List.of("105")), placed); + assertCounts("1", List.of(List.of("106")), placedOnce); + assertCounts("2", List.of(List.of("103"), List.of("104")), byPerson); + assertCounts("1", List.of(List.of("3")), named); + } + } + + @Test + void aLinkTableGivesARecordItsValuesAndAnOrphanRowGivesNone(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "baskets"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, BASKETS).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "OrderShape", + "Order", + on(fixture, "contains", "contains") + .withMinCount(1) + .withMaxCount(1) + .withClassIri(fixture.type("Product").getIri()), + on(fixture, "quantity", "itemQuantity").withMinInclusive(limit("1"))); + + final OntologyShapeChecks checks = checks(admin(), fixture.type("Order"), DRAFT); + final OntologyShapeCheck some = check(checks, "contains", MIN_COUNT); + final OntologyShapeCheck one = check(checks, "contains", MAX_COUNT); + final OntologyShapeCheck products = check(checks, "contains", CLASS); + final OntologyShapeCheck quantity = check(checks, "quantity", RANGE); + + assertEquals(fixture.table("order_items").getId(), products.getTable().getId()); + assertEquals( + List.of( + read(fixture, "Order", "orders", 2L), + read(fixture, "Order", "order_items", 2L), + read(fixture, "Product", "products", 1L)), + products.getReadBindings()); + // The same link twice is one value. The rows of orders 7 and 99 belong to no record. + for (final OntologyShapeCheck check : List.of(some, one, products, quantity)) { + assertCounts("0", NO_KEYS, check); + } + + // Order 3 has a row that names no product, and order 6 has no row at all. + addRows(fixture, "orders", row(3, "web"), row(4, "web"), row(5, "web"), row(6, "web")); + addRows( + fixture, + "order_items", + row(2, "A-1", 1), + row(3, null, 1), + row(4, "X-0", 5), + row(5, "B-2", 0)); + + assertCounts("2", List.of(List.of("3"), List.of("6")), some); + assertCounts("1", List.of(List.of("2")), one); + assertCounts("1", List.of(List.of("4")), products); + assertCounts("1", List.of(List.of("5")), quantity); + } + } + + @Test + void aTwoColumnKeyAndATwoColumnJoinAreComparedColumnByColumn(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "shipments"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, SHIPMENTS).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "ShipmentShape", + "Shipment", + on(fixture, "shipped-to", "shippedTo") + .withMinCount(1) + .withClassIri(fixture.type("Account").getIri())); + declare( + ontology, + fixture, + "AccountShape", + "Account", + on(fixture, "tier-listed", "accountTier").withIn(literals("gold", "silver"))); + + final OntologyShapeChecks shipments = checks(admin(), fixture.type("Shipment"), DRAFT); + final OntologyShapeCheck shipped = check(shipments, "shipped-to", MIN_COUNT); + final OntologyShapeCheck toAccount = check(shipments, "shipped-to", CLASS); + final OntologyShapeCheck tier = + check(checks(admin(), fixture.type("Account"), DRAFT), "tier-listed", IN); + + assertEquals( + List.of(List.of("account_tenant"), List.of("account_no")), toAccount.getColumns()); + for (final OntologyShapeCheck check : List.of(shipped, toAccount, tier)) { + assertCounts("0", NO_KEYS, check); + } + + // Shipment 12 names half an account, and shipment 13 an account of another tenant. + addRows( + fixture, + "shipments", + row("eu", 12, "eu", null), + row("eu", 13, "us", 2), + row(null, 14, "eu", 9)); + addRows(fixture, "accounts", row("eu", 2, "bronze"), row(null, 3, "bronze")); + + assertCounts("1", List.of(List.of("eu", "12")), shipped); + assertCounts("1", List.of(List.of("eu", "13")), toAccount); + assertCounts("1", List.of(List.of("eu", "2")), tier); + } + } + + @Test + void aListedValueWithAQuoteAndAColonComparesEqualToTheStoredValue(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "listed"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, MEMBERS).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "MemberShape", + "Member", + on(fixture, "email-listed", "memberEmail") + .withIn(literals("ada@example.org", "grace@example.org", "O'Brien", "mailto:a :b"))); + + final OntologyShapeCheck listed = + check(checks(admin(), fixture.type("Member"), DRAFT), "email-listed", IN); + assertTrue( + parameter(listed, "sqlExpression").contains("'O''Brien', 'mailto\\:a \\:b')"), + () -> parameter(listed, "sqlExpression")); + assertTrue( + listed.getInspectionQuery().contains("'O''Brien', 'mailto:a :b')"), + listed::getInspectionQuery); + assertCounts("0", NO_KEYS, listed); + + addRows( + fixture, + "members", + row(3, "O'Brien", 1), + row(4, "mailto:a :b", 1), + row(5, "O''Brien", 1)); + + assertCounts("1", List.of(List.of("5")), listed); + } + } + + @Test + void aListedValueIsEqualToAStoredOneWhenTheDatabaseSaysSo(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "collation"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, MEMBERS).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "MemberShape", + "Member", + on(fixture, "email-listed", "memberEmail") + .withIn(literals("ada@example.org", "grace@example.org"))); + final boolean mysql = MYSQL.equals(fixture.family()); + final OntologyShapeCheck listed = + check(checks(admin(), fixture.type("Member"), DRAFT), "email-listed", IN); + assertCounts("0", NO_KEYS, listed); + + addRows(fixture, "members", row(3, "ADA@EXAMPLE.ORG", 1)); + + // A Postgres text column tells the cases apart, and so does a MySQL column that compares + // bytes. The same statement on the same rows counts nothing once the column ignores case. + if (mysql) { + collate(fixture, "utf8mb4_bin"); + } + assertCounts("1", List.of(List.of("3")), listed); + if (mysql) { + collate(fixture, "utf8mb4_general_ci"); + assertCounts("0", NO_KEYS, listed); + } + } + } + + /** Gives the email column of the members table of a MySQL database another collation. */ + private static void collate(final OntologyShapeFixture fixture, final String collation) { + TestSuiteBootstrap.getJdbi() + .useHandle( + handle -> + handle.execute( + "ALTER TABLE " + + fixture.from("members") + + " MODIFY email VARCHAR(64) CHARACTER SET utf8mb4 COLLATE " + + collation)); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java new file mode 100644 index 000000000000..9c3d33a81466 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckPatternIT.java @@ -0,0 +1,383 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.CUSTOM_SQL; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.addRows; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.assertCounts; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.check; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.data; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identityTable; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.integer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.mapping; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.part; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.row; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.table; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.text; +import static org.openmetadata.schema.api.data.OntologyShapePart.PATTERN; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * Runs the pattern test of {@code GET /v1/ontologyConcepts/{id}/shapeChecks} on Postgres, on the + * values that show whether an engine reads a pattern as SHACL does: a line break inside a value + * and at its end, a letter of the other case, and a letter and a digit outside ASCII. On any + * other database the part has no test, and that is asserted there. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckPatternIT extends BaseOntologyApprovalIT { + private static final List> NO_KEYS = List.of(); + private static final String POSTGRES = "postgres"; + private static final List CONSTRAINTS = List.of("pair", "digits", "word", "mail"); + + /** One table with a text column for each pattern, and two rows that match every one. */ + private static final Shape CODES = + mapping( + "codes", + List.of( + table( + "codes", + List.of(integer("id"), text("pair"), text("digits"), text("word"), text("mail")), + row(1, "1x2", "123", "abc", "ada@example.org"), + row(2, "1 2", "7", "z", "grace@example.org"))), + List.of("Code"), + List.of( + data("codePair", "Code"), + data("codeDigits", "Code"), + data("codeWord", "Code"), + data("codeMail", "Code")), + identityTable( + "Code", + "codes", + List.of("id"), + null, + bound("codePair", "pair"), + bound("codeDigits", "digits"), + bound("codeWord", "word"), + bound("codeMail", "mail"))); + + /** Declares one pattern for each text column of the codes table and asks how they are checked. */ + private static OntologyShapeChecks patterns( + final Ontology ontology, final OntologyShapeFixture fixture) { + fixture.bindAll(); + declare( + ontology, + fixture, + "CodeShape", + "Code", + on(fixture, "pair", "codePair").withPattern("^1.2$"), + on(fixture, "digits", "codeDigits").withPattern("^[0-9]+$"), + on(fixture, "word", "codeWord").withPattern("^[a-z]+$"), + on(fixture, "mail", "codeMail").withPattern("^[a-z]+@[a-z]+\\.org$")); + return checks(admin(), fixture.type("Code"), DRAFT); + } + + private static void assertNoTestOffPostgres(final OntologyShapeChecks checks) { + assertNoTestOffPostgres(checks, CONSTRAINTS); + } + + private static void assertNoTestOffPostgres( + final OntologyShapeChecks checks, final List constraints) { + for (final String constraint : constraints) { + final OntologyCheckedPart pattern = part(checks, constraint, PATTERN); + assertEquals(OntologyShapeCheckOutcome.NOT_ENFORCEABLE, pattern.getOutcome(), constraint); + assertEquals(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED, pattern.getReason(), constraint); + assertNull(pattern.getChecks(), constraint); + } + } + + private static void execute(final String statement) { + TestSuiteBootstrap.getJdbi().useHandle(handle -> handle.execute(statement)); + } + + @Test + void aPatternCountsTheRecordsWithAValueThatItDoesNotMatch(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "codes"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, CODES).withRows()) { + final OntologyShapeChecks checks = patterns(ontology, fixture); + if (!POSTGRES.equals(fixture.family())) { + assertNoTestOffPostgres(checks); + return; + } + final OntologyShapeCheck pair = check(checks, "pair", PATTERN); + final OntologyShapeCheck digits = check(checks, "digits", PATTERN); + final OntologyShapeCheck word = check(checks, "word", PATTERN); + final OntologyShapeCheck mail = check(checks, "mail", PATTERN); + + assertEquals(CUSTOM_SQL, pair.getTestDefinition()); + for (final OntologyShapeCheck check : List.of(pair, digits, word, mail)) { + assertCounts("0", NO_KEYS, check); + } + + // Codes 3 and 4 hold a line feed or a carriage return, inside a value, after it and before + // it. Code 5 holds a letter and digits outside ASCII, and a capital. Code 6 holds no value, + // code 7 holds values that are too short or empty, and the row with no id is no code. + addRows( + fixture, + "codes", + row(3, "1\n2", "123\n", "aBc", "ada@exampleXorg"), + row(4, "1\r2", "\n123", "B", "ada@example.org\n"), + row(5, "1é2", "١٢٣", "é", "ADA@example.org"), + row(6, null, null, null, null), + row(7, "12", "", "", "a@b.org"), + row(null, "bad", "bad", "BAD", "bad")); + + assertCounts("3", List.of(List.of("3"), List.of("4"), List.of("7")), pair); + assertCounts("4", List.of(List.of("3"), List.of("4"), List.of("5"), List.of("7")), digits); + assertCounts("4", List.of(List.of("3"), List.of("4"), List.of("5"), List.of("7")), word); + assertCounts("3", List.of(List.of("3"), List.of("4"), List.of("5")), mail); + + // The text is read after the counts, so a statement that the engine reads in another way + // fails on the number it counts. + assertEquals( + String.join( + "\n", + "SELECT DISTINCT t0.id AS k0", + "FROM " + fixture.from("codes") + " t0", + "WHERE t0.id IS NOT NULL", + " AND NOT (CAST(t0.pair AS text) COLLATE \"C\" ~ E'^1[^\\\\n\\\\r]2$')"), + pair.getInspectionQuery()); + } + } + + /** The patterns of {@link #SPELLED} by the id of the constraint, and the column each is about. */ + private static final Map SPELLINGS = + Map.ofEntries( + Map.entry("brien", "^O'Brien$"), + Map.entry("colon", "^a:b$"), + Map.entry("lead", "^:name$"), + Map.entry("mail", "^[^@ ]+@[^@ ]+$"), + Map.entry("tab", "^a\\tb$"), + Map.entry("lines", "^[^\\n\\r]*$"), + Map.entry("drop", "^x'\\); DROP TABLE t; --$"), + Map.entry("or", "^x'\\) OR 1=1 --$"), + Map.entry("slash", "^a\\\\b$"), + Map.entry("dollar", "^\\$1$"), + Map.entry("dot", "^a.b$")); + + private static final List SPELLED = List.copyOf(SPELLINGS.keySet()); + + /** One text column for each pattern of {@link #SPELLINGS}, the column named as the pattern is. */ + private static Shape spelled() { + final List columns = new ArrayList<>(List.of(integer("id"))); + final List properties = new ArrayList<>(); + final List bound = new ArrayList<>(); + for (final String name : SPELLED) { + columns.add(text("col_" + name)); + properties.add(data("spelled" + name, "Spelled")); + bound.add(bound("spelled" + name, "col_" + name)); + } + return mapping( + "spelled", + List.of(table("spelled", columns)), + List.of("Spelled"), + properties, + identityTable( + "Spelled", "spelled", List.of("id"), null, bound.toArray(ColumnBindingSpec[]::new))); + } + + /** A value that matches the pattern of the column, for each column. */ + private static final Map MATCHING = + Map.ofEntries( + Map.entry("brien", "O'Brien"), + Map.entry("colon", "a:b"), + Map.entry("lead", ":name"), + Map.entry("mail", "ada@example.org"), + Map.entry("tab", "a\tb"), + Map.entry("lines", "plain"), + Map.entry("drop", "x'); DROP TABLE t; --"), + Map.entry("or", "x') OR 1=1 --"), + Map.entry("slash", "a\\b"), + Map.entry("dollar", "$1"), + Map.entry("dot", "axb")); + + /** A value that breaks the pattern of the column, for each column. */ + private static final Map BREAKING = + Map.ofEntries( + Map.entry("brien", "OBrien"), + Map.entry("colon", "a b"), + Map.entry("lead", "name"), + Map.entry("mail", "ada.example.org"), + Map.entry("tab", "a b"), + Map.entry("lines", "x\ny"), + Map.entry("drop", "x"), + Map.entry("or", "x"), + Map.entry("slash", "ab"), + Map.entry("dollar", "1"), + Map.entry("dot", "ab")); + + /** A row with this id and a value in each column that {@code byColumn} names, and null in the rest. */ + private static List spelledRow(final int id, final Map byColumn) { + final List values = new ArrayList<>(List.of(id)); + SPELLED.forEach(name -> values.add(byColumn.get(name))); + return row(values.toArray()); + } + + private static OntologyShapeChecks spellings( + final Ontology ontology, final OntologyShapeFixture fixture) { + fixture.bindAll(); + declare( + ontology, + fixture, + "SpelledShape", + "Spelled", + SPELLED.stream() + .map(name -> on(fixture, name, "spelled" + name).withPattern(SPELLINGS.get(name))) + .toArray(OntologyShapeConstraint[]::new)); + return checks(admin(), fixture.type("Spelled"), DRAFT); + } + + @Test + void aPatternWithPunctuationAnEscapeOrAnInjectionCountsTheValuesItDoesNotMatch( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "spelled"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, spelled()).withRows()) { + final OntologyShapeChecks checks = spellings(ontology, fixture); + if (!POSTGRES.equals(fixture.family())) { + assertNoTestOffPostgres(checks, SPELLED); + return; + } + final String spelled = fixture.from("spelled"); + + // Row 1 matches every pattern and row 2 breaks every one. Rows 3 and 4 hold a line feed and a + // carriage return in the one column that allows anything else, and rows 5 and 6 in the + // column whose dot stands for every character but those. Row 7 holds a backslash and a t + // where the tab pattern wants a tab. A column of null is no violation. + addRows( + fixture, + "spelled", + spelledRow(1, MATCHING), + spelledRow(2, BREAKING), + spelledRow(3, Map.of("lines", "a\nb")), + spelledRow(4, Map.of("lines", "a\rb")), + spelledRow(5, Map.of("dot", "a\nb")), + spelledRow(6, Map.of("dot", "a\rb")), + spelledRow(7, Map.of("tab", "a\\tb"))); + final String rows = "SELECT COUNT(*) FROM " + spelled; + assertEquals(List.of(List.of("7")), OntologyShapeFixture.run(rows)); + + final Map>> violating = + Map.of( + "tab", List.of(List.of("2"), List.of("7")), + "lines", List.of(List.of("2"), List.of("3"), List.of("4")), + "dot", List.of(List.of("2"), List.of("5"), List.of("6"))); + for (final String name : SPELLED) { + final List> keys = violating.getOrDefault(name, List.of(List.of("2"))); + assertCounts(String.valueOf(keys.size()), keys, check(checks, name, PATTERN)); + } + assertEquals(List.of(List.of("7")), OntologyShapeFixture.run(rows)); + } + } + + @Test + void anEscapeThatXPathRefusesIsNotEnforceableWithNoStatement(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "refused"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, CODES).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "RefusedShape", + "Code", + on(fixture, "quote", "codePair").withPattern("^O\\'Brien$"), + on(fixture, "colon", "codeDigits").withPattern("^a\\:b$"), + on(fixture, "at", "codeMail").withPattern("^\\@$")); + final OntologyShapeChecks checks = checks(admin(), fixture.type("Code"), DRAFT); + for (final String constraint : List.of("quote", "colon", "at")) { + final OntologyCheckedPart pattern = part(checks, constraint, PATTERN); + assertEquals(OntologyShapeCheckOutcome.NOT_ENFORCEABLE, pattern.getOutcome(), constraint); + assertEquals( + POSTGRES.equals(fixture.family()) + ? OntologyShapeCheckReason.PATTERN_NOT_PORTABLE + : OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED, + pattern.getReason(), + constraint); + assertNull(pattern.getChecks(), constraint); + } + } + } + + @Test + void aPatternReadsARangeByCodePointWhateverTheCollationOfItsColumn(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "collated"); + final String folding = "fold_" + UUID.randomUUID().toString().substring(0, 8); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, CODES).withRows()) { + final OntologyShapeChecks checks = patterns(ontology, fixture); + if (!POSTGRES.equals(fixture.family())) { + assertNoTestOffPostgres(checks); + return; + } + final String codes = fixture.from("codes"); + final OntologyShapeCheck word = check(checks, "word", PATTERN); + final OntologyShapeCheck mail = check(checks, "mail", PATTERN); + // The word column sorts B between a and z. The mail column calls ADA and ada equal, and + // Postgres refuses to match a regular expression under such a collation. + execute( + "CREATE COLLATION " + + folding + + " (provider = icu, locale = 'und-u-ks-level2', deterministic = false)"); + try { + execute( + "ALTER TABLE " + codes + " ALTER COLUMN word TYPE VARCHAR(64) COLLATE \"en-x-icu\""); + execute("ALTER TABLE " + codes + " ALTER COLUMN mail TYPE VARCHAR(64) COLLATE " + folding); + addRows( + fixture, + "codes", + row(3, "1x2", "1", "B", "ADA@example.org"), + row(4, "1x2", "1", "b", "ada@example.org")); + + assertEquals( + List.of(List.of("3", "inside", "same")), + OntologyShapeFixture.run( + "SELECT id, CASE WHEN word BETWEEN 'a' AND 'z' THEN 'inside' ELSE 'outside' END," + + " CASE WHEN mail = 'ada@example.org' THEN 'same' ELSE 'other' END FROM " + + codes + + " WHERE id = 3")); + assertCounts("1", List.of(List.of("3")), word); + assertCounts("1", List.of(List.of("3")), mail); + } finally { + execute("ALTER TABLE " + codes + " ALTER COLUMN mail TYPE VARCHAR(64) COLLATE \"C\""); + execute("DROP COLLATION " + folding); + } + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java new file mode 100644 index 000000000000..c7b7a5499b20 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckProposalIT.java @@ -0,0 +1,1178 @@ +/* + * 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; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.PARTIES; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.data; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declareKey; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identityTable; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.integer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.mapping; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.table; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.text; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.RELEASE; +import static org.openmetadata.schema.type.OntologyRowFilterOperator.NOT_EQUALS; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.ActivateOntologyRelease; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposalState; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.tasks.ResolveTask; +import org.openmetadata.schema.api.tests.CreateTestCaseResolutionStatus; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.tests.type.TestCaseResolutionStatusTypes; +import org.openmetadata.schema.type.TaskEntityStatus; +import org.openmetadata.schema.type.TaskResolutionType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyCheckReconcileAccess; +import org.openmetadata.service.ontology.OntologyCheckReconcileQueue; +import org.openmetadata.service.ontology.OntologyCheckReconciler.Outcome; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * A shape check reaches its table as a suggestion task that a person with the right accepts, and + * the tests and the open suggestions follow the active release (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckProposalIT extends BaseOntologyApprovalIT { + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + private static final long WAIT_SECONDS = 120; + + static final Shape ACCOUNTS = + mapping( + "accounts", + List.of(table("accounts", List.of(integer("id"), text("email"), integer("age")))), + List.of("Account"), + List.of( + data("accountNo", "Account"), + data("accountEmail", "Account"), + data("accountAge", "Account")), + identityTable( + "Account", + "accounts", + List.of("id"), + null, + bound("accountNo", "id"), + bound("accountEmail", "email"), + bound("accountAge", "age"))); + + static org.openmetadata.schema.type.OntologyShapeConstraint listed( + final OntologyShapeFixture fixture) { + return on(fixture, "email-listed", "accountEmail").withIn(literals("a", "b")); + } + + static org.openmetadata.schema.type.OntologyShapeConstraint ranged( + final OntologyShapeFixture fixture, final String upper) { + return on(fixture, "age-range", "accountAge") + .withDatatypeIri(URI.create(XSD + "integer")) + .withMinInclusive(limit("0")) + .withMaxInclusive(limit(upper)); + } + + static void settle() { + try { + assertTrue( + OntologyCheckReconcileQueue.instance().awaitIdle(WAIT_SECONDS, TimeUnit.SECONDS), + "the reconcile did not finish"); + } catch (final InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + /** Captures the working draft, approves the release and makes it the active one. */ + static OntologyRelease release(final TestNamespace ns, final Ontology ontology) { + final OntologyRelease release = capture(ontology); + final var task = submit(ns, Entity.ONTOLOGY_RELEASE, release.getFullyQualifiedName()); + SdkClients.user1Client() + .tasks() + .resolve(task.getId().toString(), decision(TaskResolutionType.Approved)); + activate(ontology, release); + return release; + } + + /** Makes an approved release the active one, an older one included, and waits for the reconcile. */ + static void activate(final Ontology ontology, final OntologyRelease release) { + final long revision = admin().ontologies().state(ontology.getId()).getActivationRevision(); + admin() + .ontologies() + .activate( + ontology.getId(), + new ActivateOntologyRelease() + .withReleaseId(release.getId()) + .withExpectedActivationRevision(revision)); + settle(); + } + + static List checks(final OntologyConcept account) { + return checks(admin(), account); + } + + static List checks( + final OpenMetadataClient reader, final OntologyConcept account) { + final List found = new ArrayList<>(); + for (final OntologyCheckedShape shape : answer(reader, account).getShapes()) { + for (final OntologyCheckedConstraint constraint : shape.getConstraints()) { + for (final OntologyCheckedPart part : constraint.getParts()) { + if (part.getChecks() != null) { + found.addAll(part.getChecks()); + } + } + } + } + return found; + } + + /** The first check of the constraint with this id, as the reader is shown it. */ + static OntologyShapeCheck checkOfConstraint( + final OpenMetadataClient reader, final OntologyConcept account, final String constraintId) { + return answer(reader, account).getShapes().stream() + .flatMap(shape -> shape.getConstraints().stream()) + .filter(constraint -> constraint.getId().equals(constraintId)) + .flatMap(constraint -> constraint.getParts().stream()) + .flatMap( + part -> java.util.Optional.ofNullable(part.getChecks()).stream().flatMap(List::stream)) + .findFirst() + .orElseThrow(); + } + + private static OntologyShapeChecks answer( + final OpenMetadataClient reader, final OntologyConcept account) { + return reader + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/ontologyConcepts/" + account.getId() + "/shapeChecks?version=" + RELEASE.value(), + null, + OntologyShapeChecks.class); + } + + static void cancel(final String taskId) { + OntologyCheckReconcileAccess.cancel(UUID.fromString(taskId)); + } + + static OntologyShapeCheck checkOf(final List checks, final String column) { + return checks.stream() + .filter(check -> check.getColumns().getFirst().getFirst().equals(column)) + .findFirst() + .orElseThrow(); + } + + static JsonNode testsOf(final String tableFqn) { + return testsOf(tableFqn, "non-deleted"); + } + + static JsonNode testsOf(final String tableFqn, final String include) { + return JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/dataQuality/testCases?entityLink=" + + java.net.URLEncoder.encode( + "<#E::table::" + tableFqn + ">", java.nio.charset.StandardCharsets.UTF_8) + + "&limit=100&include=" + + include + + "&fields=testSuite,testDefinition,inspectionQuery,generatedBy", + null)); + } + + static int generatedTests(final String tableFqn) { + return generated(tableFqn, "non-deleted").size(); + } + + /** The tests generated from a shape, with the deleted ones when {@code include} is {@code all}. */ + static List generated(final String tableFqn, final String include) { + final List found = new ArrayList<>(); + for (final JsonNode test : testsOf(tableFqn, include).path("data")) { + if (test.has("generatedBy")) { + found.add(test); + } + } + return found; + } + + static OntologyShapeCheckProposalState stateOf( + final OntologyConcept account, final String column) { + return checkOf(checks(account), column).getProposal().getState(); + } + + @Test + void activationProposes(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "proposals"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, fixture, "AccountShape", "Account", listed(fixture), ranged(fixture, "120")); + release(ns, ontology); + + final OntologyConcept account = fixture.type("Account"); + final List found = checks(account); + assertEquals(2, found.size()); + for (final OntologyShapeCheck check : found) { + assertEquals(OntologyShapeCheckProposalState.PROPOSED, check.getProposal().getState()); + final Task task = admin().tasks().get(check.getProposal().getTask().getId().toString()); + assertEquals(TaskEntityStatus.Open, task.getStatus()); + } + assertEquals(0, generatedTests(fixture.table("accounts").getFullyQualifiedName())); + } + } + + @Test + void acceptCreatesTest(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "accepted"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, fixture, "AccountShape", "Account", listed(fixture), ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + final OntologyShapeCheck proposed = checkOf(checks(account), "email"); + + admin() + .tasks() + .resolve( + proposed.getProposal().getTask().getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + + final OntologyShapeCheck accepted = checkOf(checks(account), "email"); + assertEquals(OntologyShapeCheckProposalState.ACCEPTED, accepted.getProposal().getState()); + assertEquals(1, generatedTests(tableFqn)); + final JsonNode test = testsOf(tableFqn).path("data").get(0); + assertEquals(proposed.getInspectionQuery(), test.path("inspectionQuery").asText()); + assertEquals("tableCustomSQLQuery", test.path("testDefinition").path("name").asText()); + assertEquals(4, test.path("parameterValues").size()); + assertEquals( + proposed.getParameterValues().getFirst().getValue(), + test.path("parameterValues").get(0).path("value").asText()); + assertEquals(proposed.getIdentity(), test.path("generatedBy").path("identity").asText()); + final String suiteId = test.path("testSuite").path("id").asText(); + final JsonNode suite = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/dataQuality/testSuites/" + suiteId + "?fields=pipelines", + null)); + assertEquals(1, suite.path("pipelines").size()); + final JsonNode pipeline = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/services/ingestionPipelines/" + + suite.path("pipelines").get(0).path("id").asText(), + null)); + assertEquals("0 0 * * *", pipeline.path("airflowConfig").path("scheduleInterval").asText()); + } + } + + @Test + void acceptNeedsRight(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "refused"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final OntologyShapeCheck proposed = checkOf(checks(account), "email"); + final String taskId = proposed.getProposal().getTask().getId().toString(); + + assertRefusedWithout( + () -> + SdkClients.dataConsumerClient() + .tasks() + .resolve( + taskId, new ResolveTask().withResolutionType(TaskResolutionType.Approved))); + + assertEquals(0, generatedTests(fixture.table("accounts").getFullyQualifiedName())); + assertEquals(TaskEntityStatus.Open, admin().tasks().get(taskId).getStatus()); + assertFalse(hasTestSuite(fixture.table("accounts").getId().toString())); + } + } + + static boolean hasTestSuite(final String tableId) { + return admin() + .getHttpClient() + .executeForString(HttpMethod.GET, "/v1/tables/" + tableId + "?fields=testSuite", null) + .contains("\"testSuite\""); + } + + @Test + void rejectedStays(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "rejected"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String taskId = + checkOf(checks(account), "email").getProposal().getTask().getId().toString(); + admin() + .tasks() + .resolve(taskId, new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + assertEquals(OntologyShapeCheckProposalState.REJECTED, stateOf(account, "email")); + final int before = taskCount(account); + + release(ns, ontology); + + assertEquals(OntologyShapeCheckProposalState.REJECTED, stateOf(account, "email")); + assertEquals(before, taskCount(account)); + assertEquals(0, generatedTests(fixture.table("accounts").getFullyQualifiedName())); + } + } + + private static void assertRefusedWithout(final Runnable resolve) { + final int status = + org.junit.jupiter.api.Assertions.assertThrows( + org.openmetadata.sdk.exceptions.OpenMetadataException.class, resolve::run) + .getStatusCode(); + assertTrue(status == 403 || status == 404, "status " + status); + } + + private static int taskCount(final OntologyConcept account) { + final JsonNode all = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString(HttpMethod.GET, "/v1/tasks?limit=1000&fields=payload", null)); + int count = 0; + for (final JsonNode task : all.path("data")) { + if ("TestCase".equals(task.path("payload").path("suggestionType").asText()) + && task.path("payload") + .path("suggestedValue") + .asText() + .contains(account.getId().toString())) { + count++; + } + } + return count; + } + + @Test + void boundChange(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "bound"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OntologyShape shape = + declare( + ontology, + fixture, + "AccountShape", + "Account", + listed(fixture), + ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + final OntologyShapeCheck listed = checkOf(checks(account), "email"); + final OntologyShapeCheck ranged = checkOf(checks(account), "age"); + admin() + .tasks() + .resolve( + ranged.getProposal().getTask().getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + final String testId = + checkOf(checks(account), "age").getProposal().getTestCase().getId().toString(); + final String openTask = listed.getProposal().getTask().getId().toString(); + + admin() + .ontologyShapes() + .update( + shape.getId(), + admin() + .ontologyShapes() + .get(shape.getId().toString()) + .withConstraints( + List.of( + on(fixture, "email-listed", "accountEmail") + .withIn(literals("a", "b", "c")), + ranged(fixture, "100")))); + release(ns, ontology); + + final OntologyShapeCheck after = checkOf(checks(account), "age"); + assertEquals(testId, after.getProposal().getTestCase().getId().toString()); + assertEquals(1, generatedTests(tableFqn)); + final JsonNode test = testsOf(tableFqn).path("data").get(0); + assertTrue(test.path("parameterValues").get(0).path("value").asText().contains("100")); + assertEquals( + after.getParameterValues().getFirst().getValue(), + test.path("parameterValues").get(0).path("value").asText()); + final OntologyShapeCheck replaced = checkOf(checks(account), "email"); + assertEquals(openTask, replaced.getProposal().getTask().getId().toString()); + assertEquals( + "governance-bot", + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString(HttpMethod.GET, "/v1/tasks/" + openTask, null)) + .path("updatedBy") + .asText()); + final JsonNode value = + JsonUtils.readTree( + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, "/v1/tasks/" + openTask + "?fields=payload", null)) + .path("payload") + .path("suggestedValue") + .asText()); + assertTrue( + value + .path("testCase") + .path("parameterValues") + .get(0) + .path("value") + .asText() + .contains("'c'")); + } + } + + @Test + void constraintGone(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "removed"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OntologyShape shape = + declare( + ontology, + fixture, + "AccountShape", + "Account", + listed(fixture), + ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + admin() + .tasks() + .resolve( + checkOf(checks(account), "age").getProposal().getTask().getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + final String open = + checkOf(checks(account), "email").getProposal().getTask().getId().toString(); + assertEquals(1, generatedTests(tableFqn)); + + admin() + .ontologyShapes() + .update( + shape.getId(), + admin().ontologyShapes().get(shape.getId().toString()).withConstraints(List.of())); + release(ns, ontology); + + assertEquals(0, generatedTests(tableFqn)); + assertEquals(TaskEntityStatus.Cancelled, admin().tasks().get(open).getStatus()); + assertEquals(0, checks(account).size()); + } + } + + @Test + void readOnly(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "readonly"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("pro")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + final OpenMetadataClient owner = + OntologyBindingFixtures.client(access.userToken("owner", List.of())); + fixture.ownedBy(owner, "accounts"); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + approve(checkOf(checks(account), "email").getProposal().getTask().getId().toString()); + final String testId = + checkOf(checks(account), "email").getProposal().getTestCase().getId().toString(); + final String path = "/v1/dataQuality/testCases/" + testId; + + assertRepositoryRefusesAPutOfAChangedThreshold(testId); + assertCsvImportRefusesWhatTheShapeFreezes( + fixture.table("accounts").getFullyQualifiedName(), testId); + + final java.util.Map callers = new java.util.LinkedHashMap<>(); + callers.put("admin", admin()); + callers.put("owner", owner); + for (final var caller : callers.entrySet()) { + final OpenMetadataClient who = caller.getValue(); + assertShapeRefusal( + () -> + who.getHttpClient() + .execute( + HttpMethod.PATCH, + path, + JsonUtils.readTree( + "[{\"op\":\"replace\",\"path\":\"/parameterValues/0/value\"," + + "\"value\":\"SELECT 0\"}]"), + org.openmetadata.schema.tests.TestCase.class)); + assertShapeRefusal(() -> replaceDefinition(who, path)); + assertShapeRefusal(() -> put(who, testId, "threshold", "5")); + assertShapeRefusal(() -> putDefinition(who, testId, "tableRowCountToEqual")); + final String words = "looked at by " + caller.getKey(); + assertEquals(words, put(who, testId, null, words).getDescription()); + assertEquals(words, getTest(testId).getDescription()); + assertEquals("0", parameter(getTest(testId), "threshold")); + assertEquals( + "patched by " + words, + who.getHttpClient() + .execute( + HttpMethod.PATCH, + path, + JsonUtils.readTree( + "[{\"op\":\"add\",\"path\":\"/description\",\"value\":\"patched by " + + words + + "\"}]"), + org.openmetadata.schema.tests.TestCase.class) + .getDescription()); + } + } + } + + /** A CSV dry run refuses the row that the real import refuses, and neither changes the test. */ + private static void assertCsvImportRefusesWhatTheShapeFreezes( + final String tableFqn, final String testId) { + final String exported = admin().testCases().exportCsv(tableFqn); + final String threshold = exported.replaceFirst("(name\\W+threshold\\W+value\\W+)0", "$15"); + final String definition = exported.replace(",tableCustomSQLQuery,", ",tableRowCountToEqual,"); + assertNotEquals(exported, threshold); + assertNotEquals(exported, definition); + for (final String changed : List.of(threshold, definition)) { + for (final boolean dryRun : new boolean[] {true, false}) { + final JsonNode result = + JsonUtils.readTree(admin().testCases().importCsv(tableFqn, changed, dryRun, "table")); + assertEquals("failure", result.path("status").asText(), "dryRun=" + dryRun); + assertEquals(1, result.path("numberOfRowsProcessed").asInt(), "dryRun=" + dryRun); + assertEquals(0, result.path("numberOfRowsPassed").asInt(), "dryRun=" + dryRun); + assertEquals(1, result.path("numberOfRowsFailed").asInt(), "dryRun=" + dryRun); + assertTrue( + result.path("importResultsCsv").asText().contains(FROM_A_SHAPE), + result.path("importResultsCsv").asText()); + assertEquals("0", parameter(getTest(testId), "threshold")); + assertEquals("tableCustomSQLQuery", getTest(testId).getTestDefinition().getName()); + } + } + } + + /** A write that reaches the repository without the resource's checks is refused as well. */ + private static void assertRepositoryRefusesAPutOfAChangedThreshold(final String testId) { + final org.openmetadata.schema.tests.TestCase body = + JsonUtils.deepCopy(getTest(testId), org.openmetadata.schema.tests.TestCase.class); + body.setGeneratedBy(null); + body.getParameterValues().stream() + .filter(value -> "threshold".equals(value.getName())) + .forEach(value -> value.setValue("5")); + final org.openmetadata.service.exception.BadRequestException refused = + assertThrows( + org.openmetadata.service.exception.BadRequestException.class, + () -> + ((org.openmetadata.service.jdbi3.TestCaseRepository) + Entity.getEntityRepository(Entity.TEST_CASE)) + .createOrUpdate(null, body, "admin")); + assertEquals(FROM_A_SHAPE, refused.getMessage()); + assertEquals("0", parameter(getTest(testId), "threshold")); + } + + static final String FROM_A_SHAPE = + "This test comes from a shape: its test definition, entity link and parameter values change" + + " only when the shape or the table bindings change. Its description, owners and tags" + + " can be edited, and it can be deleted"; + + /** The request is a 400 that says the test comes from a shape. */ + private static void assertShapeRefusal(final Runnable request) { + final OpenMetadataException refused = assertThrows(OpenMetadataException.class, request::run); + assertEquals(400, refused.getStatusCode()); + assertTrue(refused.getMessage().contains(FROM_A_SHAPE), refused.getMessage()); + } + + private static void replaceDefinition(final OpenMetadataClient who, final String path) { + final String other = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/dataQuality/testDefinitions/name/tableRowCountToEqual", + null)) + .path("id") + .asText(); + who.getHttpClient() + .execute( + HttpMethod.PATCH, + path, + JsonUtils.readTree( + "[{\"op\":\"replace\",\"path\":\"/testDefinition\",\"value\":{\"id\":\"" + + other + + "\",\"type\":\"testDefinition\"}}]"), + org.openmetadata.schema.tests.TestCase.class); + } + + private static org.openmetadata.schema.tests.TestCase getTest(final String id) { + return admin() + .getHttpClient() + .execute( + HttpMethod.GET, + "/v1/dataQuality/testCases/" + id + "?fields=*", + null, + org.openmetadata.schema.tests.TestCase.class); + } + + private static String parameter( + final org.openmetadata.schema.tests.TestCase test, final String name) { + return test.getParameterValues().stream() + .filter(value -> name.equals(value.getName())) + .findFirst() + .orElseThrow() + .getValue(); + } + + /** + * A PUT of the test as a person would send it: the stored name, link, definition and + * parameters, with {@code changed} given another value, or the description when it is null. + */ + private static org.openmetadata.schema.tests.TestCase put( + final OpenMetadataClient who, final String id, final String changed, final String value) { + return put(who, id, changed, value, null); + } + + /** A PUT that names another test definition and sends the stored parameters. */ + private static org.openmetadata.schema.tests.TestCase putDefinition( + final OpenMetadataClient who, final String id, final String definition) { + return put(who, id, null, "same words", definition); + } + + private static org.openmetadata.schema.tests.TestCase put( + final OpenMetadataClient who, + final String id, + final String changed, + final String value, + final String definition) { + final org.openmetadata.schema.tests.TestCase stored = getTest(id); + final List> parameters = new ArrayList<>(); + for (final var parameter : stored.getParameterValues()) { + parameters.add( + java.util.Map.of( + "name", + parameter.getName(), + "value", + parameter.getName().equals(changed) ? value : parameter.getValue())); + } + final java.util.Map body = new java.util.LinkedHashMap<>(); + body.put("name", stored.getName()); + body.put("entityLink", stored.getEntityLink()); + body.put( + "testDefinition", + definition == null ? stored.getTestDefinition().getFullyQualifiedName() : definition); + body.put("parameterValues", parameters); + body.put("description", changed == null ? value : stored.getDescription()); + return who.getHttpClient() + .execute( + HttpMethod.PUT, + "/v1/dataQuality/testCases", + body, + org.openmetadata.schema.tests.TestCase.class); + } + + static void approve(final String taskId) { + admin() + .tasks() + .resolve(taskId, new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + } + + @Test + void secondRunIdle(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "idempotent"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, fixture, "AccountShape", "Account", listed(fixture), ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + admin() + .tasks() + .resolve( + checkOf(checks(account), "age").getProposal().getTask().getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + final OntologyCheckReconcileQueue queue = OntologyCheckReconcileQueue.instance(); + queue.afterActivation(ontology.getId(), "admin"); + settle(); + final int written = queue.writesMade(ontology.getId()); + final String before = JsonUtils.pojoToJson(checks(account)); + + queue.afterActivation(ontology.getId(), "admin"); + settle(); + + assertEquals(written, queue.writesMade(ontology.getId())); + assertEquals(before, JsonUtils.pojoToJson(checks(account))); + assertNotNull(checkOf(checks(account), "age").getProposal().getTestCase()); + assertNull(checkOf(checks(account), "age").getProposal().getTask()); + assertEquals(OntologyShapeCheckProposalState.PROPOSED, stateOf(account, "email")); + } + } + + @Test + void filterChange(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "filter"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + admin() + .tasks() + .resolve( + checkOf(checks(account), "email").getProposal().getTask().getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + final OntologyShapeCheck before = checkOf(checks(account), "email"); + + final BindingSpec spec = fixture.shape().bindings().getFirst(); + fixture.bind( + new BindingSpec( + spec.type(), + spec.table(), + spec.role(), + spec.key(), + new FilterSpec("email", NOT_EQUALS, "zz"), + spec.columns())); + settle(); + + final OntologyShapeCheck after = checkOf(checks(account), "email"); + assertEquals( + before.getProposal().getTestCase().getId(), after.getProposal().getTestCase().getId()); + assertNotEquals( + before.getParameterValues().getFirst().getValue(), + after.getParameterValues().getFirst().getValue()); + final JsonNode test = + testsOf(fixture.table("accounts").getFullyQualifiedName()).path("data").get(0); + assertEquals( + after.getParameterValues().getFirst().getValue(), + test.path("parameterValues").get(0).path("value").asText()); + } + } + + static final String NO_PROPOSAL = "{\"state\":\"none\"}"; + + /** The open tasks that propose a check of the class. */ + static List openTasks(final OntologyConcept account) { + final JsonNode all = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, "/v1/tasks?limit=1000&fields=payload,assignees", null)); + final List open = new ArrayList<>(); + for (final JsonNode task : all.path("data")) { + final String status = task.path("status").asText(); + if (("Open".equals(status) || "InProgress".equals(status) || "Pending".equals(status)) + && "TestCase".equals(task.path("payload").path("suggestionType").asText()) + && task.path("payload") + .path("suggestedValue") + .asText() + .contains(account.getId().toString())) { + open.add(task); + } + } + return open; + } + + private static String proposalOf(final OntologyConcept account, final String column) { + return JsonUtils.pojoToJson(checkOf(checks(account), column).getProposal()); + } + + private static void setConstraints( + final OntologyShape shape, + final List constraints) { + admin() + .ontologyShapes() + .update( + shape.getId(), + admin().ontologyShapes().get(shape.getId().toString()).withConstraints(constraints)); + } + + private static void deleteTest(final String id, final String query) { + admin() + .getHttpClient() + .executeForString(HttpMethod.DELETE, "/v1/dataQuality/testCases/" + id + query, null); + } + + /** The incidents of a test as "stateId type", one for each incident, at their latest state. */ + private static List incidents(final String testFqn) { + final JsonNode data = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/dataQuality/testCases/testCaseIncidentStatus?testCaseFQN=" + + java.net.URLEncoder.encode( + testFqn, java.nio.charset.StandardCharsets.UTF_8) + + "&latest=true&limit=10", + null)); + final List found = new ArrayList<>(); + data.path("data") + .forEach( + one -> + found.add( + one.path("stateId").asText() + + " " + + one.path("testCaseResolutionStatusType").asText())); + return found; + } + + @Test + void olderComesBack(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "older"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OntologyShape shape = + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + final OntologyRelease first = release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + approve(checkOf(checks(account), "email").getProposal().getTask().getId().toString()); + final OntologyShapeCheck accepted = checkOf(checks(account), "email"); + final String testId = accepted.getProposal().getTestCase().getId().toString(); + admin() + .getHttpClient() + .executeForString( + HttpMethod.POST, + "/v1/dataQuality/testCases/testCaseResults/" + + java.net.URLEncoder.encode( + accepted.getProposal().getTestCase().getFullyQualifiedName(), + java.nio.charset.StandardCharsets.UTF_8), + java.util.Map.of( + "timestamp", + System.currentTimeMillis(), + "testCaseStatus", + "Failed", + "result", + "3 violations")); + final String testFqn = accepted.getProposal().getTestCase().getFullyQualifiedName(); + await().atMost(30, TimeUnit.SECONDS).until(() -> incidents(testFqn).size() == 1); + admin() + .testCaseResolutionStatuses() + .create( + new CreateTestCaseResolutionStatus() + .withTestCaseResolutionStatusType(TestCaseResolutionStatusTypes.Ack) + .withTestCaseReference(testFqn)); + final List incidentBefore = incidents(testFqn); + assertEquals(1, incidentBefore.size()); + assertTrue(incidentBefore.getFirst().endsWith(" Ack"), incidentBefore.toString()); + setConstraints(shape, List.of()); + final OntologyRelease second = release(ns, ontology); + assertEquals(0, generatedTests(tableFqn)); + assertEquals(1, generated(tableFqn, "all").size()); + assertEquals( + "governance-bot", generated(tableFqn, "all").getFirst().path("updatedBy").asText()); + + activate(ontology, first); + + final List live = generated(tableFqn, "non-deleted"); + assertEquals(1, live.size()); + assertEquals(testId, live.getFirst().path("id").asText()); + assertEquals(0, openTasks(account).size()); + final OntologyShapeCheck back = checkOf(checks(account), "email"); + assertEquals(OntologyShapeCheckProposalState.ACCEPTED, back.getProposal().getState()); + assertEquals(testId, back.getProposal().getTestCase().getId().toString()); + assertEquals( + org.openmetadata.schema.tests.type.TestCaseStatus.Failed, + back.getProposal().getLatestResultStatus()); + assertEquals(incidentBefore, incidents(testFqn)); + final Outcome restored = + OntologyCheckReconcileQueue.instance().outcomeSoFar(ontology.getId()); + assertEquals(1, restored.deleted()); + assertEquals(1, restored.restored()); + assertEquals(0, restored.updated()); + assertEquals(0, restored.refused()); + + deleteTest(testId, "?recursive=true"); + assertEquals(0, generatedTests(tableFqn)); + assertEquals("admin", generated(tableFqn, "all").getFirst().path("updatedBy").asText()); + activate(ontology, second); + activate(ontology, first); + + assertEquals(NO_PROPOSAL, proposalOf(account, "email")); + assertEquals(0, openTasks(account).size()); + assertEquals(0, generatedTests(tableFqn)); + assertEquals(1, generated(tableFqn, "all").size()); + } + } + + @Test + void hardDeleted(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "harddelete"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OntologyShape shape = + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + approve(checkOf(checks(account), "email").getProposal().getTask().getId().toString()); + final String testId = + checkOf(checks(account), "email").getProposal().getTestCase().getId().toString(); + + deleteTest(testId, "?hardDelete=true"); + OntologyCheckReconcileQueue.instance().afterActivation(ontology.getId(), "admin"); + settle(); + + assertEquals(0, openTasks(account).size()); + assertEquals(0, generated(tableFqn, "all").size()); + assertEquals(NO_PROPOSAL, proposalOf(account, "email")); + + setConstraints( + shape, + List.of(on(fixture, "email-listed", "accountEmail").withIn(literals("a", "b", "c")))); + release(ns, ontology); + + assertEquals(1, openTasks(account).size()); + assertEquals(OntologyShapeCheckProposalState.PROPOSED, stateOf(account, "email")); + } + } + + @Test + void twoServers(final TestNamespace ns) throws Exception { + final Ontology ontology = createOntology(ns, "twoservers"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OntologyShape shape = + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + + for (int attempt = 0; attempt < 8 && openTasks(account).size() < 2; attempt++) { + openTasks(account) + .forEach( + task -> + OntologyCheckReconcileAccess.cancel(UUID.fromString(task.path("id").asText()))); + runTwoServersAtOnce(ontology.getId()); + } + final List open = openTasks(account); + assertEquals(2, open.size()); + for (final JsonNode task : open) { + approve(task.path("id").asText()); + } + assertEquals(2, generatedTests(tableFqn)); + final String lowest = + generated(tableFqn, "non-deleted").stream() + .map(test -> test.path("id").asText()) + .sorted() + .findFirst() + .orElseThrow(); + + OntologyCheckReconcileQueue.instance().afterActivation(ontology.getId(), "admin"); + settle(); + + final List kept = generated(tableFqn, "non-deleted"); + assertEquals(1, kept.size()); + assertEquals(lowest, kept.getFirst().path("id").asText()); + assertEquals(2, generated(tableFqn, "all").size()); + + setConstraints( + shape, + List.of(on(fixture, "email-listed", "accountEmail").withIn(literals("a", "b", "c")))); + release(ns, ontology); + + final List after = generated(tableFqn, "non-deleted"); + assertEquals(1, after.size()); + assertEquals(lowest, after.getFirst().path("id").asText()); + assertTrue( + after.getFirst().path("parameterValues").get(0).path("value").asText().contains("'c'")); + } + } + + private static void runTwoServersAtOnce(final UUID ontologyId) throws InterruptedException { + final CyclicBarrier together = new CyclicBarrier(2); + final List failures = java.util.Collections.synchronizedList(new ArrayList<>()); + final Runnable server = + () -> { + try { + together.await(60, TimeUnit.SECONDS); + OntologyCheckReconcileAccess.runAsAnotherServer(ontologyId); + } catch (final Exception failed) { + failures.add(failed); + } + }; + final Thread one = new Thread(server); + final Thread other = new Thread(server); + one.start(); + other.start(); + one.join(); + other.join(); + assertEquals(List.of(), failures); + } + + @Test + void otherClass(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "otherclass"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, PARTIES).withRows()) { + fixture.bindAll(); + declare( + ontology, + fixture, + "OrderShape", + "Order", + on(fixture, "placed-by", "placedBy").withClassIri(fixture.type("Person").getIri())); + release(ns, ontology); + final OntologyConcept orders = fixture.type("Order"); + final String tableFqn = fixture.table("orders").getFullyQualifiedName(); + approve(checkOf(checks(orders), "party_id").getProposal().getTask().getId().toString()); + final String before = + generated(tableFqn, "non-deleted") + .getFirst() + .path("parameterValues") + .get(0) + .path("value") + .asText(); + final String testId = generated(tableFqn, "non-deleted").getFirst().path("id").asText(); + + final BindingSpec person = + fixture.shape().bindings().stream() + .filter(spec -> spec.type().equals("Person")) + .findFirst() + .orElseThrow(); + fixture.bind( + new BindingSpec( + person.type(), + person.table(), + person.role(), + person.key(), + new FilterSpec( + "kind", org.openmetadata.schema.type.OntologyRowFilterOperator.EQUALS, "human"), + person.columns())); + settle(); + + final List after = generated(tableFqn, "non-deleted"); + assertEquals(1, after.size()); + assertEquals(testId, after.getFirst().path("id").asText()); + final String now = after.getFirst().path("parameterValues").get(0).path("value").asText(); + assertNotEquals(before, now); + assertTrue(now.contains("human"), now); + assertEquals( + checkOf(checks(orders), "party_id").getParameterValues().getFirst().getValue(), now); + } + } + + @Test + void inARow(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "inarow"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, fixture, "AccountShape", "Account", listed(fixture), ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + approve(checkOf(checks(account), "email").getProposal().getTask().getId().toString()); + final OntologyCheckReconcileQueue queue = OntologyCheckReconcileQueue.instance(); + + queue.afterActivation(ontology.getId(), "admin"); + queue.afterActivation(ontology.getId(), "admin"); + final BindingSpec spec = fixture.shape().bindings().getFirst(); + fixture.bind( + new BindingSpec( + spec.type(), + spec.table(), + spec.role(), + spec.key(), + new FilterSpec("email", NOT_EQUALS, "zz"), + spec.columns())); + settle(); + + final OntologyShapeCheck email = checkOf(checks(account), "email"); + final List tests = generated(tableFqn, "non-deleted"); + assertEquals(1, tests.size()); + assertEquals( + email.getParameterValues().getFirst().getValue(), + tests.getFirst().path("parameterValues").get(0).path("value").asText()); + assertTrue(email.getParameterValues().getFirst().getValue().contains("'zz'")); + assertEquals(OntologyShapeCheckProposalState.ACCEPTED, email.getProposal().getState()); + final OntologyShapeCheck age = checkOf(checks(account), "age"); + assertEquals(OntologyShapeCheckProposalState.PROPOSED, age.getProposal().getState()); + assertEquals(1, openTasks(account).size()); + final int written = queue.writesMade(ontology.getId()); + queue.afterActivation(ontology.getId(), "admin"); + settle(); + assertEquals(written, queue.writesMade(ontology.getId())); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java new file mode 100644 index 000000000000..3f9d492ed286 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckReadsIT.java @@ -0,0 +1,1115 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.bound; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.contributing; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.data; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declareKey; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identityTable; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.integer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.joined; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.mapping; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.part; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.relation; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.table; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.targets; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.text; +import static org.openmetadata.schema.api.data.OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.RELEASE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiConsumer; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.util.SqlQueryCounter; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyAxiom; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.type.OntologyAxiomType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyExpression; +import org.openmetadata.schema.type.OntologyExpressionKind; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.RelationProvenance; +import org.openmetadata.service.Entity; +import org.openmetadata.service.monitoring.RequestLatencyContext; +import org.openmetadata.service.ontology.OntologyCheckReconcileQueue; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyMappingShapes.TableSpec; + +/** + * How many statements {@code GET /v1/ontologyConcepts/{id}/shapeChecks} runs. Each kind of input is + * read once for the answer, and the caller's right to view is checked once for the shapes, once + * for the properties and once for the tables. So a class with eighty constraints is read in the + * statements of a class with one, and a class of twelve tables in the statements of one of three. + * No statement of a request locks the rows it reads. + */ +@Isolated("Counts the SQL statements that serve one request") +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckReadsIT extends BaseOntologyApprovalIT { + private static final String SELECT = "select"; + private static final String SHAPES = "from ontology_shape_entity"; + private static final String PROPERTIES = "from ontology_property_entity"; + private static final String BINDING_ROWS = "from ontology_concept_binding"; + private static final String RELEASE_MEMBERS = "from ontology_release_member"; + private static final String SETTINGS = "from openmetadata_settings"; + + /** What a read that locks its rows ends with, on MySQL and on Postgres. */ + private static final List LOCKS = + List.of( + " for update", + " for share", + " for no key update", + " for key share", + " lock in share mode"); + + /** Every statement of one read of the draft, as an administrator, and of the active release. */ + private static final int DRAFT_STATEMENTS = 53; + + private static final int RELEASE_STATEMENTS = 62; + + /** + * The same reads when the identity binding of every class a part names has a row filter. The + * filter costs one statement that reads the binding rows of all those tables, and the count does + * not depend on how many classes are named. + */ + private static final int FILTERED_DRAFT_STATEMENTS = DRAFT_STATEMENTS + 1; + + private static final int FILTERED_RELEASE_STATEMENTS = RELEASE_STATEMENTS + 1; + + /** + * A draft that finds classes sharing a filtered table reads those classes once and then walks the + * subclass steps above them, one statement for each level of the hierarchy and one more that finds + * nothing above the top. A release reads no more, because it is read through its cache. + */ + private static final int SHARED_AT_DEPTH_ONE_DRAFT_STATEMENTS = FILTERED_DRAFT_STATEMENTS + 3; + + private static final int SHARED_AT_DEPTH_THREE_DRAFT_STATEMENTS = FILTERED_DRAFT_STATEMENTS + 5; + + /** + * A walk asks for the axioms of a class once. A class that two chains reach is in the frontier of + * the shorter chain's level, so the longer chain finds it read and the walk stops one level + * sooner than a single chain of the same depth: the read of the sharing classes and three levels. + */ + private static final int SHARED_BY_CHAINS_THAT_MEET_DRAFT_STATEMENTS = + FILTERED_DRAFT_STATEMENTS + 4; + + /** + * A class that another ontology binds on the table is no candidate. The draft reads the classes + * that share the table and finds nothing to walk from. + */ + private static final int SHARED_ONLY_BY_ANOTHER_ONTOLOGY_DRAFT_STATEMENTS = + FILTERED_DRAFT_STATEMENTS + 1; + + private static final FilterSpec NOT_X = + new FilterSpec("title", OntologyRowFilterOperator.NOT_EQUALS, "x"); + + /** A shape holds at most this many of the constraints that a test declares. */ + private static final int CONSTRAINTS_OF_A_SHAPE = 5; + + /** + * An order class that binds its identity table, a link table, and one more table for each note + * property. Its relation arrives at one more table, so the mapping has {@code notes + 3} tables. + */ + private static Shape orders(final String name, final int notes) { + final List tables = + new ArrayList<>( + List.of( + table("orders", List.of(integer("id"), text("channel"))), + table( + "order_items", + List.of(integer("order_id"), text("product_sku"), integer("quantity"))), + table("products", List.of(text("sku"), text("title"))))); + final List properties = + new ArrayList<>( + List.of( + data("orderChannel", "Order"), + data("itemQuantity", "Order"), + data("productTitle", "Product"), + relation("contains", "Order", "Product"))); + final List bindings = + new ArrayList<>( + List.of( + identityTable( + "Order", "orders", List.of("id"), null, bound("orderChannel", "channel")), + identityTable( + "Product", "products", List.of("sku"), null, bound("productTitle", "title")), + contributing( + "Order", + "order_items", + List.of("order_id"), + bound("itemQuantity", "quantity"), + joined("contains", "product_sku", "products", "sku")))); + for (int note = 0; note < notes; note++) { + tables.add(table("order_notes" + note, List.of(integer("order_id"), text("note")))); + properties.add(data("orderNote" + note, "Order")); + bindings.add( + contributing( + "Order", + "order_notes" + note, + List.of("order_id"), + bound("orderNote" + note, "note"))); + } + return mapping( + name, + tables, + List.of("Order", "Product"), + properties, + bindings.toArray(BindingSpec[]::new)); + } + + /** Constraints that a shape on {@link #targets} holds, as many as the targets are asked to name. */ + private static final int CONSTRAINTS_ON_TARGETS = 8; + + /** + * One shape of the order class with eight {@code class} constraints, which name {@code named} + * distinct classes among them. + */ + private static void declareClassParts( + final Ontology ontology, final OntologyShapeFixture fixture, final int named) { + declare( + ontology, + fixture, + "Targets", + "Order", + IntStream.range(0, CONSTRAINTS_ON_TARGETS) + .mapToObj( + constraint -> + on(fixture, "class" + constraint, "reaches" + constraint % named) + .withClassIri(fixture.type("Target" + constraint % named).getIri())) + .toArray(OntologyShapeConstraint[]::new)); + } + + /** The statements of one request, as the server rendered them. */ + private record Reads(OntologyShapeChecks answer, List statements) { + long of(final String fragment) { + return statements.stream().filter(statement -> statement.contains(fragment)).count(); + } + + int constraints() { + return answer.getShapes().stream().mapToInt(shape -> shape.getConstraints().size()).sum(); + } + + /** The tables that the tests of the answer read, the table a relation arrives at included. */ + Set tables() { + return answer.getShapes().stream() + .flatMap(shape -> shape.getConstraints().stream()) + .flatMap(constraint -> constraint.getParts().stream()) + .filter(part -> part.getChecks() != null) + .flatMap(part -> part.getChecks().stream()) + .flatMap(check -> check.getReadBindings().stream()) + .map(OntologyShapeCheckBinding::getAssetId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + } + + String listed() { + return String.join("\n", statements); + } + } + + /** A statement and the request that issued it. */ + private record Issued(RequestLatencyContext.RequestContext request, String statement) {} + + /** Asks once to fill what the server caches between requests, then records the next request. */ + private static Reads reads( + final OntologyShapeFixture fixture, final OntologyStatementVersion version) { + settleReconcile(); + checks(admin(), fixture.type("Order"), version); + final List issued = Collections.synchronizedList(new ArrayList<>()); + try (var ignored = + SqlQueryCounter.forRequests( + Entity.getJdbi(), + SELECT, + statement -> + issued.add( + new Issued( + RequestLatencyContext.getContext(), plain(statement.getRenderedSql()))))) { + final OntologyShapeChecks answer = checks(admin(), fixture.type("Order"), version); + return new Reads(answer, ofTheRequestThatReadTheBindings(List.copyOf(issued))); + } + } + + /** + * The statements of the request that read the binding rows. Work that an earlier request left + * running keeps the context of that request, and it reads no binding. A server setting is cached + * for every request, and the request that finds the cached value lapsed reads it again, so a read + * of a setting is not a read for the answer. + */ + private static List ofTheRequestThatReadTheBindings(final List issued) { + return ofTheAnsweringRequest(issued).stream() + .takeWhile(statement -> !readsProposals(statement)) + .toList(); + } + + private static List ofTheAnsweringRequest(final List issued) { + final RequestLatencyContext.RequestContext answering = + issued.stream() + .filter(read -> read.statement().contains(BINDING_ROWS)) + .map(Issued::request) + .findFirst() + .orElseThrow(); + return issued.stream() + .filter(read -> read.request() == answering) + .map(Issued::statement) + .filter(statement -> statement.startsWith(SELECT) && !statement.contains(SETTINGS)) + .toList(); + } + + /** + * The statements the answering request runs from the lookup of the tests and the suggestions of + * the checks on, which is what it reads for the proposal state of each check. + */ + private static int statementsAfterTheLookup(final OntologyConcept account) { + settleReconcile(); + checks(admin(), account, RELEASE); + final List issued = Collections.synchronizedList(new ArrayList<>()); + try (var ignored = + SqlQueryCounter.forRequests( + Entity.getJdbi(), + SELECT, + statement -> + issued.add( + new Issued( + RequestLatencyContext.getContext(), plain(statement.getRenderedSql()))))) { + checks(admin(), account, RELEASE); + } + return (int) + ofTheAnsweringRequest(List.copyOf(issued)).stream() + .dropWhile(statement -> !readsProposals(statement)) + .count(); + } + + /** + * One class with {@code constraints} checks on a table with no row, each proposed, or each + * accepted. The statements after the lookup are the same for any number of checks. + */ + private static int proposalReads( + final TestNamespace ns, final int constraints, final boolean accepted) { + final String size = "proposalReads" + constraints + (accepted ? "a" : "p"); + ns.setMethodId(size); + final Ontology ontology = createOntology(ns, size); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, OntologyShapeCheckProposalIT.ACCOUNTS).withRows()) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, + fixture, + "AccountShape", + "Account", + IntStream.range(0, constraints) + .mapToObj( + constraint -> + on(fixture, "c" + constraint, "accountEmail") + .withIn(literals("v" + constraint))) + .toArray(OntologyShapeConstraint[]::new)); + OntologyShapeCheckProposalIT.release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + assertEquals(constraints, OntologyShapeCheckProposalIT.openTasks(account).size()); + if (accepted) { + OntologyShapeCheckProposalIT.openTasks(account) + .forEach(task -> OntologyShapeCheckProposalIT.approve(task.path("id").asText())); + } + return statementsAfterTheLookup(account); + } + } + + @Test + void theProposalsOfOneCheckAndOfFortyAreReadInTheSameStatementsWhetherProposedOrAccepted( + final TestNamespace ns) { + final List counts = + List.of( + proposalReads(ns, 1, false), + proposalReads(ns, 40, false), + proposalReads(ns, 1, true), + proposalReads(ns, 40, true)); + + assertEquals(counts.getFirst(), counts.get(1), counts.toString()); + assertEquals(counts.get(2), counts.get(3), counts.toString()); + assertEquals(List.of(5, 5, 33, 33), counts); + } + + /** + * The first statement of the lookup of the tests and the suggestions of the checks. It comes + * after the compile and is what the rest of the request reads for each proposal it finds. + */ + private static boolean readsProposals(final String statement) { + return statement.contains(" from test_case ") || statement.contains(" from task_entity "); + } + + /** The reconcile that an activation starts reads the same rows, so a count waits for it. */ + private static void settleReconcile() { + try { + assertTrue( + OntologyCheckReconcileQueue.instance() + .awaitIdle(120, java.util.concurrent.TimeUnit.SECONDS)); + } catch (final InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + /** A statement in lower case, without the comment that names its method and on one line. */ + private static String plain(final String rendered) { + return rendered + .replaceAll("/\\*.*?\\*/", " ") + .replaceAll("\\s+", " ") + .trim() + .toLowerCase(Locale.ROOT); + } + + /** + * Every constraint that a shape of a test can hold: seven on the three tables that every mapping + * has, and two on each note table. Between them they rest on every table of the mapping. + */ + private static List stated( + final OntologyShapeFixture fixture, final int notes) { + final List stated = + new ArrayList<>( + List.of( + on(fixture, "product", "contains").withClassIri(fixture.type("Product").getIri()), + on(fixture, "channel", "orderChannel").withIn(literals("web", "store")), + on(fixture, "quantity", "itemQuantity").withMinInclusive(limit("1")), + on(fixture, "some", "contains").withMinCount(1), + on(fixture, "one", "contains").withMaxCount(1), + on(fixture, "channelOnce", "orderChannel").withMaxCount(1), + on(fixture, "quantityRequired", "itemQuantity").withMinCount(1))); + for (int note = 0; note < notes; note++) { + stated.add(on(fixture, "note" + note, "orderNote" + note).withMinCount(1)); + stated.add( + on(fixture, "noteListed" + note, "orderNote" + note).withIn(literals("new", "gift"))); + } + return stated; + } + + /** + * Declares shapes of the order class until it has {@code upTo} constraints, given that it has + * {@code already}. Constraint {@code n} of the class is constraint {@code n} of {@link #stated}, + * which starts again when it runs out. + */ + private static void declareUpTo( + final Ontology ontology, + final OntologyShapeFixture fixture, + final int notes, + final int already, + final int upTo) { + final List stated = stated(fixture, notes); + for (int first = already; first < upTo; first += CONSTRAINTS_OF_A_SHAPE) { + final OntologyShapeConstraint[] held = + IntStream.range(first, Math.min(first + CONSTRAINTS_OF_A_SHAPE, upTo)) + .mapToObj(constraint -> stated.get(constraint % stated.size())) + .toArray(OntologyShapeConstraint[]::new); + declare(ontology, fixture, "Shape" + first, "Order", held); + } + } + + private static List sizes(final Reads reads) { + return List.of(reads.answer().getShapes().size(), reads.constraints(), reads.tables().size()); + } + + @Test + void aDraftOfSixTablesIsReadInTheSameStatementsForOneFortyAndEightyConstraints( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "shapeReads"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, orders("sixTables", 3))) { + fixture.bindAll(); + declareUpTo(ontology, fixture, 3, 0, 1); + final Reads one = reads(fixture, DRAFT); + declareUpTo(ontology, fixture, 3, 1, 40); + final Reads forty = reads(fixture, DRAFT); + declareUpTo(ontology, fixture, 3, 40, 80); + final Reads eighty = reads(fixture, DRAFT); + + assertEquals(List.of(1, 1, 3), sizes(one)); + assertEquals(List.of(9, 40, 6), sizes(forty)); + assertEquals(List.of(17, 80, 6), sizes(eighty)); + assertEquals( + List.of(DRAFT_STATEMENTS, DRAFT_STATEMENTS, DRAFT_STATEMENTS), + List.of(one.statements().size(), forty.statements().size(), eighty.statements().size()), + eighty::listed); + assertDraftReads(one); + assertDraftReads(eighty); + } + } + + @Test + void aDraftOfThreeTablesWithFortyConstraintsIsReadInTheStatementsOfAnyDraft( + final TestNamespace ns) { + final Reads three = drafted(ns, "threeTables", 0, 40); + + assertEquals(List.of(8, 40, 3), sizes(three)); + assertEquals(DRAFT_STATEMENTS, three.statements().size(), three::listed); + assertDraftReads(three); + } + + @Test + void aDraftOfTwelveTablesWithFortyConstraintsIsReadInTheStatementsOfAnyDraft( + final TestNamespace ns) { + final Reads twelve = drafted(ns, "twelveTables", 9, 40); + + assertEquals(List.of(8, 40, 12), sizes(twelve)); + assertEquals(DRAFT_STATEMENTS, twelve.statements().size(), twelve::listed); + assertDraftReads(twelve); + } + + @Test + void aReleaseOfSixTablesWithOneConstraintIsReadInTheStatementsOfAnyRelease( + final TestNamespace ns) { + final Reads one = released(ns, "sixTables", 3, 1); + + assertEquals(List.of(1, 1, 3), sizes(one)); + assertReleaseReads(one); + } + + @Test + void aReleaseOfSixTablesWithFortyConstraintsIsReadInTheStatementsOfAnyRelease( + final TestNamespace ns) { + final Reads forty = released(ns, "sixTables", 3, 40); + + assertEquals(List.of(8, 40, 6), sizes(forty)); + assertReleaseReads(forty); + } + + @Test + void aReleaseOfSixTablesWithEightyConstraintsIsReadInTheStatementsOfAnyRelease( + final TestNamespace ns) { + final Reads eighty = released(ns, "sixTables", 3, 80); + + assertEquals(List.of(16, 80, 6), sizes(eighty)); + assertReleaseReads(eighty); + } + + @Test + void aReleaseOfThreeTablesWithFortyConstraintsIsReadInTheStatementsOfAnyRelease( + final TestNamespace ns) { + final Reads three = released(ns, "threeTables", 0, 40); + + assertEquals(List.of(8, 40, 3), sizes(three)); + assertReleaseReads(three); + } + + @Test + void aReleaseOfTwelveTablesWithFortyConstraintsIsReadInTheStatementsOfAnyRelease( + final TestNamespace ns) { + final Reads twelve = released(ns, "twelveTables", 9, 40); + + assertEquals(List.of(8, 40, 12), sizes(twelve)); + assertReleaseReads(twelve); + } + + @Test + void aDraftWhoseClassPartsNameOneClassIsReadInTheStatementsOfEight(final TestNamespace ns) { + final Reads one = classParts(ns, "oneTarget", 1, DRAFT); + + assertEquals(List.of(1, 8, 3), sizes(one)); + assertEquals(DRAFT_STATEMENTS, one.statements().size(), one::listed); + assertDraftReads(one); + } + + @Test + void aDraftWhoseClassPartsNameEightClassesIsReadInTheStatementsOfOne(final TestNamespace ns) { + final Reads eight = classParts(ns, "eightTargets", 8, DRAFT); + + assertEquals(List.of(1, 8, 17), sizes(eight)); + assertEquals(DRAFT_STATEMENTS, eight.statements().size(), eight::listed); + assertDraftReads(eight); + } + + @Test + void aReleaseWhoseClassPartsNameOneClassIsReadInTheStatementsOfEight(final TestNamespace ns) { + final Reads one = classParts(ns, "oneTarget", 1, RELEASE); + + assertEquals(List.of(1, 8, 3), sizes(one)); + assertReleaseReads(one, RELEASE_STATEMENTS); + } + + @Test + void aReleaseWhoseClassPartsNameEightClassesIsReadInTheStatementsOfOne(final TestNamespace ns) { + final Reads eight = classParts(ns, "eightTargets", 8, RELEASE); + + assertEquals(List.of(1, 8, 17), sizes(eight)); + assertReleaseReads(eight, RELEASE_STATEMENTS); + } + + @Test + void aDraftWhoseFilteredClassPartsNameOneClassIsReadInTheStatementsOfEight( + final TestNamespace ns) { + final Reads one = classParts(ns, "oneFiltered", 1, DRAFT, NOT_X); + + assertEquals(List.of(1, 8, 3), sizes(one)); + assertEquals(FILTERED_DRAFT_STATEMENTS, one.statements().size(), one::listed); + assertDraftReads(one, 3); + } + + @Test + void aDraftWhoseFilteredClassPartsNameEightClassesIsReadInTheStatementsOfOne( + final TestNamespace ns) { + final Reads eight = classParts(ns, "eightFiltered", 8, DRAFT, NOT_X); + + assertEquals(List.of(1, 8, 17), sizes(eight)); + assertEquals(FILTERED_DRAFT_STATEMENTS, eight.statements().size(), eight::listed); + assertDraftReads(eight, 3); + } + + @Test + void aReleaseWhoseFilteredClassPartsNameOneClassIsReadInTheStatementsOfEight( + final TestNamespace ns) { + final Reads one = classParts(ns, "oneFiltered", 1, RELEASE, NOT_X); + + assertEquals(List.of(1, 8, 3), sizes(one)); + assertReleaseReads(one, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aReleaseWhoseFilteredClassPartsNameEightClassesIsReadInTheStatementsOfOne( + final TestNamespace ns) { + final Reads eight = classParts(ns, "eightFiltered", 8, RELEASE, NOT_X); + + assertEquals(List.of(1, 8, 17), sizes(eight)); + assertReleaseReads(eight, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aDraftWithNoClassOnTheFilteredTableReadsNoSubclassStep(final TestNamespace ns) { + final Reads none = sharing(ns, "none", 0, 1, true, DRAFT); + + assertEquals(FILTERED_DRAFT_STATEMENTS, none.statements().size(), none::listed); + assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(none).getOutcome()); + assertDraftReads(none, 3); + } + + @Test + void aDraftWithOneSharingClassOneStepBelowTheNamedClassWalksOneLevelAndASecond( + final TestNamespace ns) { + final Reads one = sharing(ns, "oneBelow", 1, 1, true, DRAFT); + + assertEquals(SHARED_AT_DEPTH_ONE_DRAFT_STATEMENTS, one.statements().size(), one::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(one).getReason()); + assertDraftReads(one, 3); + } + + @Test + void aDraftWithOneSharingClassThreeStepsBelowTheNamedClassWalksThreeLevelsAndASecond( + final TestNamespace ns) { + final Reads one = sharing(ns, "oneDeep", 1, 3, true, DRAFT); + + assertEquals(SHARED_AT_DEPTH_THREE_DRAFT_STATEMENTS, one.statements().size(), one::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(one).getReason()); + assertDraftReads(one, 3); + } + + @Test + void aDraftWithEightSharingClassesOneStepDeepIsReadInTheStatementsOfOne(final TestNamespace ns) { + final Reads eight = sharing(ns, "eightBelow", 8, 1, true, DRAFT); + + assertEquals(SHARED_AT_DEPTH_ONE_DRAFT_STATEMENTS, eight.statements().size(), eight::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(eight).getReason()); + assertDraftReads(eight, 3); + } + + @Test + void aDraftWithEightSharingClassesThreeStepsDeepIsReadInTheStatementsOfOne( + final TestNamespace ns) { + final Reads eight = sharing(ns, "eightDeep", 8, 3, true, DRAFT); + + assertEquals(SHARED_AT_DEPTH_THREE_DRAFT_STATEMENTS, eight.statements().size(), eight::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(eight).getReason()); + assertDraftReads(eight, 3); + } + + @Test + void aDraftWhoseSharingClassesReachAnotherClassStillWalksThemInOneStatementPerLevel( + final TestNamespace ns) { + final Reads eight = sharing(ns, "eightElsewhere", 8, 3, false, DRAFT); + + assertEquals(SHARED_AT_DEPTH_THREE_DRAFT_STATEMENTS, eight.statements().size(), eight::listed); + assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(eight).getOutcome()); + assertDraftReads(eight, 3); + } + + @Test + void aDraftWithOneSharingClassThatReachesAnotherClassAnswersWithATest(final TestNamespace ns) { + final Reads one = sharing(ns, "oneElsewhere", 1, 1, false, DRAFT); + + assertEquals(SHARED_AT_DEPTH_ONE_DRAFT_STATEMENTS, one.statements().size(), one::listed); + assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(one).getOutcome()); + } + + /** + * The sharing class is a subclass of Product directly and also through two more classes. The + * class that both chains reach is asked for once, so the walk reads three levels. + */ + @Test + void aDraftWhoseSharingClassReachesTheNamedClassDirectlyAndThroughALongerChainReadsEachClassOnce( + final TestNamespace ns) { + final Reads meeting = + sharedBy( + ns, + "directAndLonger", + DRAFT, + (ontology, fixture) -> { + final OntologyConcept sharer = sharesTable(fixture, "Sharer", "products"); + subclassOf(ontology, sharer, fixture.type("Product")); + subclassOf(ontology, sharer, fixture.type("LongerOne")); + subclassOf(ontology, fixture.type("LongerOne"), fixture.type("LongerTwo")); + subclassOf(ontology, fixture.type("LongerTwo"), fixture.type("Product")); + }); + + assertEquals( + SHARED_BY_CHAINS_THAT_MEET_DRAFT_STATEMENTS, meeting.statements().size(), meeting::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(meeting).getReason()); + assertDraftReads(meeting, 3); + } + + /** + * The sharing class has two named parents. The one that the walk reads first leads away from the + * named class, and only the second leads to it. The axioms are read by name, so the first is the + * one whose name sorts first. + */ + @Test + void aDraftWhoseSharingClassReachesTheNamedClassOnlyThroughItsSecondParentWalksBothParents( + final TestNamespace ns) { + final Reads second = + sharedBy( + ns, + "secondParent", + DRAFT, + (ontology, fixture) -> { + final OntologyConcept sharer = sharesTable(fixture, "Sharer", "products"); + subclassOf(ontology, sharer, fixture.type("FirstParent")); + subclassOf(ontology, sharer, fixture.type("SecondParent")); + subclassOf(ontology, fixture.type("FirstParent"), fixture.type("Elsewhere")); + subclassOf(ontology, fixture.type("SecondParent"), fixture.type("Product")); + }); + + assertEquals( + SHARED_BY_CHAINS_THAT_MEET_DRAFT_STATEMENTS, second.statements().size(), second::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(second).getReason()); + assertDraftReads(second, 3); + } + + /** + * The same two parents with the order reversed: the parent that leads to the named class has the + * axiom whose name sorts first, so it is read first and the dead end second. The answer and the + * statements are those of the case above, whichever parent is read first. + */ + @Test + void aDraftWhoseSharingClassReachesTheNamedClassThroughItsFirstParentAlsoWalksBothParents( + final TestNamespace ns) { + final Reads first = + sharedBy( + ns, + "firstParent", + DRAFT, + (ontology, fixture) -> { + final OntologyConcept sharer = sharesTable(fixture, "Sharer", "products"); + subclassOf(ontology, sharer, fixture.type("AParent")); + subclassOf(ontology, sharer, fixture.type("BParent")); + subclassOf(ontology, fixture.type("AParent"), fixture.type("Product")); + subclassOf(ontology, fixture.type("BParent"), fixture.type("Elsewhere")); + }); + + assertEquals( + SHARED_BY_CHAINS_THAT_MEET_DRAFT_STATEMENTS, first.statements().size(), first::listed); + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(first).getReason()); + assertDraftReads(first, 3); + } + + /** + * A class of another ontology has the IRI of a subclass of Product and binds the filtered table. + * It is no candidate, so the class part is checked. + */ + @Test + void aDraftWhoseFilteredTableIsSharedOnlyByAClassOfAnotherOntologyChecksTheClassPart( + final TestNamespace ns) { + final Reads foreign = + sharedBy( + ns, + "foreign", + DRAFT, + (ontology, fixture) -> { + final OntologyConcept near = fixture.type("Near"); + subclassOf(ontology, near, fixture.type("Product")); + final OntologyConcept stranger = + declareClass(createOntology(ns, "otherDraft"), "Stranger", near.getIri()); + put( + admin(), + stranger, + binding(fixture.table("products"), OntologyBindingRole.IDENTITY, "sku"), + bindings(admin(), stranger).getRevision()); + }); + + assertEquals( + SHARED_ONLY_BY_ANOTHER_ONTOLOGY_DRAFT_STATEMENTS, + foreign.statements().size(), + foreign::listed); + assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(foreign).getOutcome()); + assertDraftReads(foreign, 3); + } + + @Test + void aReleaseWithNoClassOnTheFilteredTableIsReadInTheStatementsOfAnyFilteredRelease( + final TestNamespace ns) { + final Reads none = sharing(ns, "none", 0, 1, true, RELEASE); + + assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(none).getOutcome()); + assertReleaseReads(none, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aReleaseWithOneSharingClassOneStepBelowIsReadInTheStatementsOfAnyFilteredRelease( + final TestNamespace ns) { + final Reads one = sharing(ns, "oneBelow", 1, 1, true, RELEASE); + + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(one).getReason()); + assertReleaseReads(one, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aReleaseWithOneSharingClassThreeStepsBelowIsReadInTheStatementsOfAnyFilteredRelease( + final TestNamespace ns) { + final Reads one = sharing(ns, "oneDeep", 1, 3, true, RELEASE); + + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(one).getReason()); + assertReleaseReads(one, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aReleaseWithEightSharingClassesOneStepBelowIsReadInTheStatementsOfAnyFilteredRelease( + final TestNamespace ns) { + final Reads eight = sharing(ns, "eightBelow", 8, 1, true, RELEASE); + + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(eight).getReason()); + assertReleaseReads(eight, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aReleaseWithEightSharingClassesThreeStepsBelowIsReadInTheStatementsOfAnyFilteredRelease( + final TestNamespace ns) { + final Reads eight = sharing(ns, "eightDeep", 8, 3, true, RELEASE); + + assertEquals(SUBCLASS_ON_JOIN_TABLE, classPart(eight).getReason()); + assertReleaseReads(eight, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aReleaseWhoseSharingClassesReachAnotherClassIsReadInTheStatementsOfAnyFilteredRelease( + final TestNamespace ns) { + final Reads eight = sharing(ns, "eightElsewhere", 8, 3, false, RELEASE); + + assertEquals(OntologyShapeCheckOutcome.CHECK, classPart(eight).getOutcome()); + assertReleaseReads(eight, FILTERED_RELEASE_STATEMENTS, 3); + } + + @Test + void aDraftNamingEightFilteredClassesWithOneSharingClassEachCostsWhatOneNamedClassCosts( + final TestNamespace ns) { + final Reads eight = namedWithSharers(ns, "eightNamed", DRAFT); + + assertEquals(List.of(1, 8, 0), sizes(eight)); + assertEquals(SHARED_AT_DEPTH_ONE_DRAFT_STATEMENTS, eight.statements().size(), eight::listed); + assertEveryClassPartIsNotEnforceable(eight); + assertDraftReads(eight, 3); + } + + @Test + void aReleaseNamingEightFilteredClassesWithOneSharingClassEachCostsWhatOneNamedClassCosts( + final TestNamespace ns) { + final Reads eight = namedWithSharers(ns, "eightNamed", RELEASE); + + assertEquals(List.of(1, 8, 0), sizes(eight)); + assertEveryClassPartIsNotEnforceable(eight); + assertReleaseReads(eight, FILTERED_RELEASE_STATEMENTS, 3); + } + + private static void assertEveryClassPartIsNotEnforceable(final Reads reads) { + final List classParts = + reads.answer().getShapes().stream() + .flatMap(shape -> shape.getConstraints().stream()) + .flatMap(constraint -> constraint.getParts().stream()) + .filter(part -> part.getPart() == OntologyShapePart.CLASS) + .toList(); + assertEquals(CONSTRAINTS_ON_TARGETS, classParts.size()); + classParts.forEach( + part -> { + assertEquals(OntologyShapeCheckOutcome.NOT_ENFORCEABLE, part.getOutcome()); + assertEquals(SUBCLASS_ON_JOIN_TABLE, part.getReason()); + }); + } + + private static OntologyCheckedPart classPart(final Reads reads) { + return part(reads.answer(), "onProducts", OntologyShapePart.CLASS); + } + + /** + * Product's identity binding has a row filter and {@code sharers} classes bind the same table as + * their identity table, each below a chain of {@code depth} subclass steps. With {@code + * subclasses} the even ones are chained up to Product and the odd ones up to another class. With + * it false every one is chained up to the other class. + */ + private static Reads sharing( + final TestNamespace ns, + final String name, + final int sharers, + final int depth, + final boolean subclasses, + final OntologyStatementVersion version) { + return sharedBy( + ns, + name, + version, + (ontology, fixture) -> { + final OntologyConcept product = fixture.type("Product"); + final OntologyConcept elsewhere = fixture.type("Elsewhere"); + for (int sharer = 0; sharer < sharers; sharer++) { + final String sharerName = "Sharer" + sharer; + sharesTable(fixture, sharerName, "products"); + chain( + ontology, + fixture, + fixture.type(sharerName), + subclasses && sharer % 2 == 0 ? product : elsewhere, + depth); + } + }); + } + + /** + * Product's identity binding has a row filter, one class part of the order shape names Product, + * and {@code declareSharers} adds the classes that share its table and their subclass axioms. + */ + private static Reads sharedBy( + final TestNamespace ns, + final String name, + final OntologyStatementVersion version, + final BiConsumer declareSharers) { + final Ontology ontology = createOntology(ns, name + version.value()); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE)) { + fixture.bindAll(); + fixture.bind( + new BindingSpec( + "Product", + "products", + OntologyBindingRole.IDENTITY, + List.of("sku"), + NOT_X, + List.of(bound("productTitle", "title")))); + final OntologyConcept product = fixture.type("Product"); + fixture.type("Elsewhere"); + declareSharers.accept(ontology, fixture); + declare( + ontology, + fixture, + "OrderShape", + "Order", + on(fixture, "onProducts", "contains").withClassIri(product.getIri())); + if (version == RELEASE) { + activate(ns, ontology); + } + return reads(fixture, version); + } + } + + /** + * Eight filtered classes, each on a table of its own, with one class below it that binds the same + * table as its identity table. + */ + private static Reads namedWithSharers( + final TestNamespace ns, final String name, final OntologyStatementVersion version) { + final Ontology ontology = createOntology(ns, name + version.value()); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, targets(name, CONSTRAINTS_ON_TARGETS, NOT_X))) { + fixture.bindAll(); + for (int target = 0; target < CONSTRAINTS_ON_TARGETS; target++) { + final String sharerName = "Sharer" + target; + sharesTable(fixture, sharerName, name + "_targets" + target); + chain(ontology, fixture, fixture.type(sharerName), fixture.type("Target" + target), 1); + } + declareClassParts(ontology, fixture, CONSTRAINTS_ON_TARGETS); + if (version == RELEASE) { + activate(ns, ontology); + } + return reads(fixture, version); + } + } + + private static OntologyConcept sharesTable( + final OntologyShapeFixture fixture, final String type, final String table) { + fixture.bind( + new BindingSpec( + type, table, OntologyBindingRole.IDENTITY, List.of("sku"), null, List.of())); + return fixture.type(type); + } + + /** Declares {@code depth} subclass steps from {@code bottom} up to {@code top}. */ + private static void chain( + final Ontology ontology, + final OntologyShapeFixture fixture, + final OntologyConcept bottom, + final OntologyConcept top, + final int depth) { + OntologyConcept child = bottom; + for (int step = 1; step < depth; step++) { + final OntologyConcept middle = fixture.type(bottom.getName() + "Mid" + step); + subclassOf(ontology, child, middle); + child = middle; + } + subclassOf(ontology, child, top); + } + + private static void subclassOf( + final Ontology ontology, final OntologyConcept child, final OntologyConcept parent) { + admin() + .ontologyAxioms() + .create( + new CreateOntologyAxiom() + .withName(child.getName() + "Is" + parent.getName()) + .withDisplayName(child.getName() + "Is" + parent.getName()) + .withDescription("A subclass step of the hierarchy a test walks") + .withOntology(ontology.getFullyQualifiedName()) + .withAxiomType(OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(child.getIri()) + .withProvenance(RelationProvenance.MANUAL) + .withExpressions( + List.of( + new OntologyExpression() + .withKind(OntologyExpressionKind.NAMED_CLASS) + .withClassIri(parent.getIri())))); + } + + private static Reads classParts( + final TestNamespace ns, + final String name, + final int named, + final OntologyStatementVersion version) { + return classParts(ns, name, named, version, null); + } + + /** The statements of a read of an order class whose class parts name {@code named} classes. */ + private static Reads classParts( + final TestNamespace ns, + final String name, + final int named, + final OntologyStatementVersion version, + final FilterSpec filter) { + final Ontology ontology = createOntology(ns, name + version.value()); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, targets(name, 8, filter))) { + fixture.bindAll(); + declareClassParts(ontology, fixture, named); + if (version == RELEASE) { + activate(ns, ontology); + } + return reads(fixture, version); + } + } + + /** The statements of a read of the draft of an order class with this many constraints. */ + private static Reads drafted( + final TestNamespace ns, final String name, final int notes, final int constraints) { + final Ontology ontology = createOntology(ns, name); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, orders(name, notes))) { + fixture.bindAll(); + declareUpTo(ontology, fixture, notes, 0, constraints); + return reads(fixture, DRAFT); + } + } + + /** The statements of a read of the active release of an order class with this many constraints. */ + private static Reads released( + final TestNamespace ns, final String name, final int notes, final int constraints) { + final Ontology ontology = createOntology(ns, name); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, orders(name, notes))) { + fixture.bindAll(); + declareUpTo(ontology, fixture, notes, 0, constraints); + activate(ns, ontology); + return reads(fixture, RELEASE); + } + } + + /** A draft reads the shapes and the properties once, and authorizes the rows it read. */ + private static void assertDraftReads(final Reads reads) { + assertDraftReads(reads, 2); + } + + private static void assertDraftReads(final Reads reads, final int bindingReads) { + assertEquals(1, reads.of(SHAPES), reads::listed); + assertEquals(1, reads.of(PROPERTIES), reads::listed); + assertEquals(bindingReads, reads.of(BINDING_ROWS), reads::listed); + assertEquals(0, reads.of(RELEASE_MEMBERS), reads::listed); + assertNoLock(reads); + } + + private static void assertReleaseReads(final Reads reads) { + assertReleaseReads(reads, RELEASE_STATEMENTS); + } + + private static void assertReleaseReads(final Reads reads, final int statements) { + assertReleaseReads(reads, statements, 2); + } + + private static void assertReleaseReads( + final Reads reads, final int statements, final int bindingReads) { + assertEquals(statements, reads.statements().size(), reads::listed); + assertEquals(0, reads.of(SHAPES), reads::listed); + assertEquals(1, reads.of(PROPERTIES), reads::listed); + assertEquals(bindingReads, reads.of(BINDING_ROWS), reads::listed); + assertEquals(4, reads.of(RELEASE_MEMBERS), reads::listed); + assertNoLock(reads); + } + + /** A request only reads, so none of its statements may lock the rows it read. */ + private static void assertNoLock(final Reads reads) { + LOCKS.forEach(lock -> assertEquals(0, reads.of(lock), reads::listed)); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java new file mode 100644 index 000000000000..ec6b964961e6 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeCheckRightsIT.java @@ -0,0 +1,371 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; +import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.CUSTOM_SQL; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.answer; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.countParameters; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.goldenCount; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.identity; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.keyList; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.limit; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.read; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.reference; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.CHECK; +import static org.openmetadata.schema.api.data.OntologyShapeCheckOutcome.HIDDEN; +import static org.openmetadata.schema.api.data.OntologyShapePart.CLASS; +import static org.openmetadata.schema.api.data.OntologyShapePart.IN; +import static org.openmetadata.schema.api.data.OntologyShapePart.MAX_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.MIN_COUNT; +import static org.openmetadata.schema.api.data.OntologyShapePart.RANGE; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.RELEASE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposal; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposalState; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.policies.Policy; +import org.openmetadata.schema.entity.teams.Role; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.service.Entity; + +/** + * Who gets an answer from {@code GET /v1/ontologyConcepts/{id}/shapeChecks}, and what a reader who + * may not view a table reads in it. The mapping is the link table shape, whose order class has an + * identity table, a link table that holds a relation, and a table the relation arrives at. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeCheckRightsIT extends BaseOntologyApprovalIT { + private static final List TABLES = List.of("orders", "order_items", "products"); + + /** One shape of the order class with a constraint on each of its three properties. */ + private static OntologyShape orderShape( + final Ontology ontology, final OntologyShapeFixture fixture) { + return declare( + ontology, + fixture, + "OrderShape", + "Order", + on(fixture, "channel", "orderChannel").withIn(literals("web", "store")), + on(fixture, "contains", "contains") + .withMinCount(1) + .withMaxCount(1) + .withClassIri(fixture.type("Product").getIri()), + on(fixture, "quantity", "itemQuantity").withMinInclusive(limit("1"))); + } + + /** What an answer is about, and what the release it reads holds. */ + private record Scene(OntologyShapeFixture fixture, OntologyShape shape, OntologyRelease release) { + OntologyShapeCheckBinding orders() { + return read(fixture, "Order", "orders", 2L); + } + + OntologyShapeCheckBinding items() { + return read(fixture, "Order", "order_items", 2L); + } + + OntologyShapeCheckBinding products() { + return read(fixture, "Product", "products", 1L); + } + + /** The reader owns the named tables and no other table of the mapping, so views only them. */ + void show(final OpenMetadataClient reader, final Set visible) { + final EntityReference owner = readerReference(reader); + for (final String name : TABLES) { + final String id = fixture.table(name).getId().toString(); + final Table table = admin().tables().get(id, "owners"); + admin() + .tables() + .update(id, table.withOwners(visible.contains(name) ? List.of(owner) : List.of())); + } + } + + /** The whole answer for the order class, with these parts for its three constraints. */ + OntologyShapeChecks answer( + final List channel, + final List contains, + final List quantity) { + return new OntologyShapeChecks() + .withConceptId(fixture.type("Order").getId()) + .withClassIri(fixture.type("Order").getIri()) + .withVersion( + new OntologyStatementVersionRead() + .withKind(OntologyStatementVersion.RELEASE) + .withReleaseId(release.getId()) + .withReleaseRevision(release.getReleaseRevision()) + .withSemanticVersion(release.getSemanticVersion())) + .withShapes( + List.of( + new OntologyCheckedShape() + .withId(shape.getId()) + .withName("OrderShape") + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints( + List.of( + constraint("channel", "orderChannel", channel), + constraint("contains", "contains", contains), + constraint("quantity", "itemQuantity", quantity))))); + } + + private OntologyCheckedConstraint constraint( + final String id, final String property, final List parts) { + return new OntologyCheckedConstraint() + .withId(id) + .withPath(fixture.property(property).getIri()) + .withParts(parts); + } + + /** + * A part that one generated test checks, with the golden statement of the link table shape. + * + * @param column the bound column of the property on {@code tableName} + * @param read every binding the test read, the binding of {@code tableName} among them + */ + OntologyCheckedPart checked( + final String constraint, + final OntologyShapePart part, + final String golden, + final String tableName, + final String column, + final List read) { + final String count = goldenCount(fixture, golden); + final OntologyShapeCheckBinding holder = + read.stream() + .filter(binding -> binding.getAssetId().equals(fixture.table(tableName).getId())) + .findFirst() + .orElseThrow(); + return new OntologyCheckedPart() + .withPart(part) + .withOutcome(CHECK) + .withChecks( + List.of( + new OntologyShapeCheck() + .withIdentity(identity(shape, constraint, part, holder, List.of(column))) + .withTable(reference(fixture, tableName)) + .withColumns(List.of(List.of(column))) + .withTestDefinition(CUSTOM_SQL) + .withEntityLink( + "<#E::table::" + fixture.table(tableName).getFullyQualifiedName() + ">") + .withParameterValues(countParameters(count)) + .withInspectionQuery(keyList(count)) + .withReadBindings(read) + .withProposal( + new OntologyShapeCheckProposal() + .withState(OntologyShapeCheckProposalState.NONE)))); + } + + List channelChecked() { + return List.of( + checked( + "channel", IN, "linkTable-orderChannel-in", "orders", "channel", List.of(orders()))); + } + + List quantityChecked() { + return List.of( + checked( + "quantity", + RANGE, + "linkTable-itemQuantity-range", + "order_items", + "quantity", + List.of(orders(), items()))); + } + + List containsChecked() { + final List toProducts = List.of(orders(), items(), products()); + return List.of( + checked( + "contains", + MIN_COUNT, + "linkTable-contains-minCount", + "order_items", + "product_sku", + List.of(orders(), items())), + checked( + "contains", + MAX_COUNT, + "linkTable-contains-maxCount", + "order_items", + "product_sku", + List.of(orders(), items())), + checked( + "contains", + CLASS, + "linkTable-contains-class", + "order_items", + "product_sku", + toProducts)); + } + } + + private static List hidden(final OntologyShapePart... parts) { + final List entries = new ArrayList<>(); + for (final OntologyShapePart part : parts) { + entries.add(new OntologyCheckedPart().withPart(part).withOutcome(HIDDEN)); + } + return entries; + } + + /** The body is exactly the expected answer, and it names nothing of the hidden table. */ + private static void assertAnswer( + final OntologyShapeChecks expected, final String body, final Table... hidden) { + assertEquals( + OntologyShapeCheckFixtures.withoutProposals(expected), + OntologyShapeCheckFixtures.withoutProposals(body)); + for (final Table table : hidden) { + assertFalse(body.contains(table.getName()), body); + assertFalse(body.contains(table.getId().toString()), body); + } + } + + @Test + void aReaderWhoMayNotViewATableReadsHiddenForEveryConstraintThatRestsOnIt( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "hiddenTables"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("checkTables" + ns.shortPrefix())) { + fixture.bindAll(); + final OntologyShape shape = orderShape(ontology, fixture); + final Scene scene = new Scene(fixture, shape, current(activate(ns, ontology))); + final OpenMetadataClient reader = ownerReader(access, Entity.TABLE); + final var order = fixture.type("Order"); + + assertAnswer( + scene.answer(scene.channelChecked(), scene.containsChecked(), scene.quantityChecked()), + answer(admin(), order, null)); + + scene.show(reader, Set.of("order_items", "products")); + assertAnswer( + scene.answer(hidden(IN), hidden(MIN_COUNT, MAX_COUNT, CLASS), hidden(RANGE)), + answer(reader, order, null), + fixture.table("orders"), + fixture.table("order_items"), + fixture.table("products")); + + scene.show(reader, Set.of("orders", "products")); + assertAnswer( + scene.answer(scene.channelChecked(), hidden(MIN_COUNT, MAX_COUNT, CLASS), hidden(RANGE)), + answer(reader, order, null), + fixture.table("order_items"), + fixture.table("products")); + + scene.show(reader, Set.of("orders", "order_items")); + assertAnswer( + scene.answer( + scene.channelChecked(), hidden(MIN_COUNT, MAX_COUNT, CLASS), scene.quantityChecked()), + answer(reader, order, null), + fixture.table("products")); + + scene.show(reader, Set.of("orders", "order_items", "products")); + assertAnswer( + scene.answer(scene.channelChecked(), scene.containsChecked(), scene.quantityChecked()), + answer(reader, order, null)); + } + } + + @Test + void aDraftReadTakesEditRightsAndAReleaseReadTakesAnActiveRelease(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "checkVersionRights"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("checkDraft" + ns.shortPrefix())) { + fixture.bindAll(); + final OntologyShape shape = orderShape(ontology, fixture); + final OpenMetadataClient consumer = client(access.userToken("consumer", List.of())); + final String name = readerReference(consumer).getName(); + final var order = fixture.type("Order"); + + assertRefused( + 404, + "Ontology " + ontology.getFullyQualifiedName() + " has no active release", + () -> checks(consumer, order, null)); + assertRefused( + 403, + "Principal: CatalogPrincipal{name='" + name + "'} operations [EditAll] not allowed", + () -> checks(consumer, order, DRAFT)); + final Scene scene = new Scene(fixture, shape, current(activate(ns, ontology))); + + assertAnswer( + scene.answer(scene.channelChecked(), scene.containsChecked(), scene.quantityChecked()), + answer(consumer, order, RELEASE)); + assertRefused( + 403, + "Principal: CatalogPrincipal{name='" + name + "'} operations [EditAll] not allowed", + () -> checks(consumer, order, DRAFT)); + assertEquals(DRAFT, checks(admin(), order, DRAFT).getVersion().getKind()); + } + } + + @Test + void aReaderWhoMayNotViewTheClassIsRefusedOnEitherVersion(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "checkHiddenClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("checkClass" + ns.shortPrefix())) { + fixture.bindAll(); + orderShape(ontology, fixture); + activate(ns, ontology); + final Role denied = access.denyRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CONCEPT); + final Policy policy = + admin().policies().get(denied.getPolicies().getFirst().getId().toString(), "rules"); + final OpenMetadataClient reader = client(access.userToken("reader", List.of(denied.getId()))); + final String refusal = + "Principal: CatalogPrincipal{name='" + + readerReference(reader).getName() + + "'} operation ViewBasic denied by role " + + denied.getName() + + ", policy " + + policy.getName() + + ", rule " + + policy.getRules().getFirst().getName(); + + for (final OntologyStatementVersion version : List.of(RELEASE, DRAFT)) { + assertRefused(403, refusal, () -> checks(reader, fixture.type("Order"), version)); + } + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java new file mode 100644 index 000000000000..d0dbe89b4c57 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeFixture.java @@ -0,0 +1,421 @@ +/* + * 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; + +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.jdbi.v3.core.Handle; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.factories.DatabaseSchemaTestFactory; +import org.openmetadata.it.factories.DatabaseTestFactory; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.OntologyAggregateStatementRequest; +import org.openmetadata.schema.api.data.OntologyConceptQueryDialect; +import org.openmetadata.schema.api.data.OntologyExpandStatementRequest; +import org.openmetadata.schema.api.data.OntologyFindStatementRequest; +import org.openmetadata.schema.api.data.OntologyOpenStatementRequest; +import org.openmetadata.schema.api.data.OntologyStatementBindingRevision; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.api.services.CreateDatabaseService; +import org.openmetadata.schema.api.services.CreateDatabaseService.DatabaseServiceType; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.services.DatabaseService; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyAssetBinding; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyConceptBindingsResponse; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.ontology.OntologyMappingShapes; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyMappingShapes.TableSpec; + +/** + * One mapping shape of {@link OntologyMappingShapes} made through the API over the database this + * suite runs on: a database service of the type of that database, and a table entry for each table + * of the shape. A class or a property is created the first time a binding names it, so a test + * decides what a release of the ontology holds by what it binds before it activates one. + * + *

{@link #withRows} also creates the tables in the database with the rows of the shape, so a + * generated statement can run. Every shape names its tables as a shop would and the suite has one + * database, so each fixture gives its tables a prefix of its own. + */ +final class OntologyShapeFixture implements AutoCloseable { + private static final URI XSD_STRING = URI.create("http://www.w3.org/2001/XMLSchema#string"); + private static final Pattern GOLDEN_TABLE = + Pattern.compile("(?:FROM|JOIN) `?" + OntologyMappingShapes.GOLDEN_SCHEMA + "`?\\.`?(\\w+)"); + private static final Map COLUMN_TYPES = + Map.of( + ColumnDataType.INT, "INT", + ColumnDataType.VARCHAR, "VARCHAR(64)", + ColumnDataType.DECIMAL, "DECIMAL(10,2)", + ColumnDataType.JSON, "JSON"); + + private final Shape shape; + private final Ontology ontology; + private final boolean mysql = TestSuiteBootstrap.getConnectionType() == ConnectionType.MYSQL; + private final String prefix = "s" + UUID.randomUUID().toString().substring(0, 8) + "_"; + private final String schemaName; + private final DatabaseService service; + private final Map tables = new HashMap<>(); + private final Map classes = new HashMap<>(); + private final Map properties = new HashMap<>(); + private final List created = new ArrayList<>(); + + OntologyShapeFixture(final TestNamespace ns, final Ontology ontology, final Shape shape) { + this.shape = shape; + this.ontology = ontology; + this.schemaName = + TestSuiteBootstrap.getJdbi() + .withHandle( + handle -> + handle + .createQuery(mysql ? "SELECT DATABASE()" : "SELECT current_schema()") + .mapTo(String.class) + .one()); + this.service = + ns.trackRoot( + Entity.DATABASE_SERVICE, + admin() + .databaseServices() + .create( + new CreateDatabaseService() + .withName(ns.prefix("shapes")) + .withServiceType( + mysql ? DatabaseServiceType.Mysql : DatabaseServiceType.Postgres))); + final DatabaseSchema schema = + DatabaseSchemaTestFactory.create( + DatabaseTestFactory.create(ns, service.getFullyQualifiedName()).getFullyQualifiedName(), + schemaName); + for (final TableSpec spec : shape.tables()) { + tables.put( + spec.name(), + OntologyMappingFixtures.table( + schema, + prefix + spec.name(), + spec.columns().stream() + .map(column -> OntologyMappingFixtures.column(column.name(), column.type())) + .toArray(Column[]::new))); + } + } + + /** Creates the tables in the database of the suite and fills them with the rows of the shape. */ + OntologyShapeFixture withRows() { + TestSuiteBootstrap.getJdbi() + .useTransaction(handle -> shape.tables().forEach(spec -> create(handle, spec))); + return this; + } + + private void create(final Handle handle, final TableSpec spec) { + final String name = prefix + spec.name(); + handle.execute( + "CREATE TABLE " + + name + + " (" + + spec.columns().stream() + .map(column -> column.name() + " " + COLUMN_TYPES.get(column.type())) + .collect(Collectors.joining(", ")) + + ")"); + created.add(name); + final String marks = + spec.columns().stream() + .map(column -> column.type() == ColumnDataType.JSON ? "CAST(? AS JSON)" : "?") + .collect(Collectors.joining(", ")); + final String insert = "INSERT INTO " + name + " VALUES (" + marks + ")"; + try (PreparedStatement row = handle.getConnection().prepareStatement(insert)) { + for (final List values : spec.rows()) { + for (int column = 0; column < values.size(); column++) { + row.setObject(column + 1, values.get(column)); + } + row.executeUpdate(); + } + } catch (final SQLException failed) { + throw new IllegalStateException(insert, failed); + } + } + + Shape shape() { + return shape; + } + + DatabaseService service() { + return service; + } + + /** The engine family of the database of the suite, as a plan and a golden directory name it. */ + String family() { + return mysql ? "mysql" : "postgres"; + } + + OntologyConceptQueryDialect dialect() { + return mysql ? OntologyConceptQueryDialect.MYSQL : OntologyConceptQueryDialect.ANSI; + } + + /** A column or a table name as a statement for this database writes it. */ + String name(final String plain) { + return mysql ? "`" + plain + "`" : plain; + } + + /** A table of the shape as a statement names it after {@code FROM} or {@code JOIN}. */ + String from(final String tableName) { + return name(schemaName) + "." + name(prefix + tableName); + } + + Table table(final String name) { + return tables.get(name); + } + + /** The class of the shape with this name, declared in the working draft on first use. */ + OntologyConcept type(final String name) { + return classes.computeIfAbsent( + name, term -> BaseOntologyApprovalIT.declareClass(ontology, term, shape.iri(term))); + } + + /** The property of the shape with this name, declared in the working draft on first use. */ + OntologyProperty property(final String name) { + final OntologyProperty declared = properties.get(name); + if (declared != null) { + return declared; + } + final PropertySpec spec = shape.property(name); + final CreateOntologyProperty request = + new CreateOntologyProperty() + .withName(name) + .withIri(shape.iri(name)) + .withOntology(ontology.getFullyQualifiedName()) + .withKind(spec.kind()) + .withDomain(List.of(type(spec.domain()).getIri())) + .withRange(List.of(spec.range() == null ? XSD_STRING : type(spec.range()).getIri())); + final OntologyProperty created = + admin() + .ontologyProperties() + .create(spec.displayName() ? request.withIsDisplayName(true) : request); + properties.put(name, created); + return created; + } + + /** Writes every binding of the shape, in the order the shape lists them. */ + OntologyShapeFixture bindAll() { + return bindAll(admin()); + } + + /** Writes every binding of the shape as {@code writer}. */ + OntologyShapeFixture bindAll(final OpenMetadataClient writer) { + shape.bindings().forEach(spec -> bind(writer, spec)); + return this; + } + + /** Writes one binding of the shape, or a changed copy of one, over what the class binds now. */ + OntologyConceptBindingsResponse bind(final BindingSpec spec) { + return bind(admin(), spec); + } + + private OntologyConceptBindingsResponse bind( + final OpenMetadataClient writer, final BindingSpec spec) { + final OntologyConcept type = type(spec.type()); + final Table table = tables.get(spec.table()); + final OntologyAssetBinding asset = + spec.role() == null + ? binding(table) + : binding(table, spec.role(), spec.key().toArray(String[]::new)); + asset.withColumns(spec.columns().stream().map(this::column).toList()); + if (spec.filter() != null) { + asset.withRowFilter( + filter(spec.filter().column(), spec.filter().operator(), spec.filter().value())); + } + return put(writer, type, asset, bindings(writer, type).getRevision()); + } + + private OntologyColumnBinding column(final ColumnBindingSpec spec) { + final OntologyColumnBinding bound = + OntologyMappingFixtures.column(property(spec.property()), spec.column()); + return spec.join() == null ? bound : bound.withJoin(join(spec.join())); + } + + private OntologyColumnJoin join(final JoinSpec spec) { + return new OntologyColumnJoin() + .withTargetAssetId(tables.get(spec.target()).getId()) + .withStatus(spec.status()) + .withOn( + IntStream.range(0, spec.child().size()) + .mapToObj( + pair -> + new OntologyJoinColumnPair() + .withChild(List.of(spec.child().get(pair))) + .withParent(List.of(spec.parent().get(pair)))) + .toList()); + } + + /** Makes {@code reader} the owner of the named tables, which a rule on ownership then shows. */ + void ownedBy(final OpenMetadataClient reader, final String... names) { + final EntityReference owner = OntologyBindingFixtures.readerReference(reader); + for (final String name : names) { + final String id = tables.get(name).getId().toString(); + admin().tables().update(id, admin().tables().get(id, "owners").withOwners(List.of(owner))); + } + } + + /** What a plan says about the bindings of one class: its id, its IRI and its revision now. */ + OntologyStatementBindingRevision revisionOf(final String typeName) { + return revision(typeName, bindings(admin(), type(typeName)).getRevision()); + } + + OntologyStatementBindingRevision revision(final String typeName, final long revision) { + final OntologyConcept type = type(typeName); + return new OntologyStatementBindingRevision() + .withConceptId(type.getId()) + .withClassIri(type.getIri()) + .withRevision(revision); + } + + /** + * Asks the endpoint of one statement, as {@code client}. + * + * @param version the version to read, or null to name none + */ + OntologyStatementPlan ask( + final OpenMetadataClient client, final Ask ask, final OntologyStatementVersion version) { + return client + .getHttpClient() + .execute(HttpMethod.POST, path(ask), request(ask, version), OntologyStatementPlan.class); + } + + /** The body of the answer to {@link #ask}, as the server wrote it. */ + String answer( + final OpenMetadataClient client, final Ask ask, final OntologyStatementVersion version) { + return client + .getHttpClient() + .executeForString(HttpMethod.POST, path(ask), request(ask, version)); + } + + private String path(final Ask ask) { + return "/v1/ontologyConcepts/" + type(ask.type()).getId() + "/statements/" + ask.kind(); + } + + private Object request(final Ask ask, final OntologyStatementVersion version) { + final UUID relation = ask.relation() == null ? null : property(ask.relation()).getId(); + return switch (ask.kind()) { + case FIND -> new OntologyFindStatementRequest() + .withVersion(version) + .withMatchText(ask.matchText()); + case OPEN -> new OntologyOpenStatementRequest().withVersion(version).withKey(ask.key()); + case EXPAND -> new OntologyExpandStatementRequest() + .withVersion(version) + .withKey(ask.key()) + .withAfter(ask.after()) + .withRelation(relation) + .withDirection(ask.direction()); + case AGGREGATE -> new OntologyAggregateStatementRequest() + .withVersion(version) + .withRelation(relation) + .withDirection(ask.direction()) + .withMeasure(ask.measure()); + }; + } + + /** + * The golden text of a statement of the shape, as the engine family of this database writes it, + * with the tables of this fixture in place of the tables of the golden schema. + */ + String golden(final Ask ask) { + final String shop = OntologyMappingShapes.GOLDEN_SCHEMA; + return mysql + ? goldenText(ask).replace("`" + shop + "`.`", "`" + schemaName + "`.`" + prefix) + : goldenText(ask).replace(shop + ".", schemaName + "." + prefix); + } + + /** The tables that the golden text of a statement reads, in join order, by full name. */ + List tablesOf(final Ask ask) { + return GOLDEN_TABLE + .matcher(goldenText(ask)) + .results() + .map(named -> tables.get(named.group(1)).getFullyQualifiedName()) + .toList(); + } + + private String goldenText(final Ask ask) { + final String resource = "/" + shape.golden(family(), ask); + try (InputStream file = OntologyShapeFixture.class.getResourceAsStream(resource)) { + return new String(file.readAllBytes(), StandardCharsets.UTF_8); + } catch (final IOException unread) { + throw new UncheckedIOException(resource, unread); + } + } + + /** Runs a statement as a driver sends it and returns its rows, each value as text. */ + static List> run(final String sql) { + try (Handle handle = TestSuiteBootstrap.getJdbi().open(); + Statement statement = handle.getConnection().createStatement()) { + statement.setEscapeProcessing(false); + try (ResultSet rows = statement.executeQuery(sql)) { + final int width = rows.getMetaData().getColumnCount(); + final List> read = new ArrayList<>(); + while (rows.next()) { + final List row = new ArrayList<>(); + for (int column = 1; column <= width; column++) { + row.add(rows.getString(column)); + } + read.add(row); + } + return read; + } + } catch (final SQLException failed) { + throw new IllegalStateException(sql, failed); + } + } + + @Override + public void close() { + TestSuiteBootstrap.getJdbi() + .useHandle(handle -> created.forEach(name -> handle.execute("DROP TABLE " + name))); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapePolicyMigrationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapePolicyMigrationIT.java new file mode 100644 index 000000000000..c3d83aa716a3 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapePolicyMigrationIT.java @@ -0,0 +1,223 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.auth.JwtAuthProvider; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.migration.utils.v220.OntologyShapePolicyRules; +import org.openmetadata.service.security.policyevaluator.SubjectCache; + +/** + * Exercises the 2.2.0 step that adds the shape resource to the seeded author and reviewer + * policies, against the real database. A policy created by an earlier release keeps its old rule, + * because seeding creates a policy only when it is missing. + */ +@Isolated("rewrites seeded policies that every user of the shared server is evaluated against") +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapePolicyMigrationIT extends BaseOntologyApprovalIT { + private static final HttpClient HTTP = HttpClient.newHttpClient(); + private static final String RESOURCE = "ontologyShape"; + private static final String AUTHOR_POLICY = "OntologyAuthorPolicy"; + private static final String AUTHOR_RULE = "OntologyAuthorPolicy-AuthorRule"; + private static final String REVIEWER_POLICY = "OntologyReviewerPolicy"; + private static final String REVIEWER_RULE = "OntologyReviewerPolicy-ViewRule"; + + @Test + void upgradeGivesAuthorsTheShapeRightOnceAndLeavesTheOtherRulesAlone(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final User author = createAuthor(ns); + final String body = JsonUtils.pojoToJson(shape(ontology, "UpgradedAuthorShape")); + removeResource(AUTHOR_POLICY, AUTHOR_RULE); + removeResource(REVIEWER_POLICY, REVIEWER_RULE); + final List releaseRuleBefore = + resources(AUTHOR_POLICY, "OntologyAuthorPolicy-ReleaseRule"); + assertEquals(403, createShape(author, body), "an upgraded install starts without the right"); + + try { + step(); + step(); + + assertEquals( + 1, resources(AUTHOR_POLICY, AUTHOR_RULE).stream().filter(RESOURCE::equals).count()); + assertEquals( + 1, resources(REVIEWER_POLICY, REVIEWER_RULE).stream().filter(RESOURCE::equals).count()); + assertEquals( + List.of( + "ontology", + "ontologyAxiom", + "ontologyChangeSet", + "ontologyConcept", + "ontologyProperty", + RESOURCE), + resources(AUTHOR_POLICY, AUTHOR_RULE).stream().sorted().toList()); + assertEquals(releaseRuleBefore, resources(AUTHOR_POLICY, "OntologyAuthorPolicy-ReleaseRule")); + assertEquals(201, createShape(author, body)); + } finally { + step(); + } + } + + private static void step() { + final ConnectionType engine = + "mysql".equalsIgnoreCase(System.getProperty("databaseType", "postgres")) + ? ConnectionType.MYSQL + : ConnectionType.POSTGRES; + TestSuiteBootstrap.getJdbi() + .useHandle(handle -> OntologyShapePolicyRules.addShapeResource(handle, engine)); + evictPolicies(); + } + + /** Writes the rule as a release before this resource existed listed it. */ + private static void removeResource(final String policy, final String rule) { + final JsonNode stored = readPolicy(policy); + final ArrayNode resources = (ArrayNode) ruleOf(stored, rule).get("resources"); + for (int index = resources.size() - 1; index >= 0; index--) { + if (RESOURCE.equals(resources.get(index).asText())) { + resources.remove(index); + } + } + final String json = stored.toString(); + final String cast = + "mysql".equalsIgnoreCase(System.getProperty("databaseType", "postgres")) + ? ":json" + : "CAST(:json AS jsonb)"; + TestSuiteBootstrap.getJdbi() + .useHandle( + handle -> + handle + .createUpdate("UPDATE policy_entity SET json = " + cast + " WHERE name = :name") + .bind("json", json) + .bind("name", policy) + .execute()); + evictPolicies(); + } + + private static List resources(final String policy, final String rule) { + final List names = new ArrayList<>(); + ruleOf(readPolicy(policy), rule).get("resources").forEach(node -> names.add(node.asText())); + return names; + } + + private static JsonNode ruleOf(final JsonNode policy, final String rule) { + for (final JsonNode candidate : policy.get("rules")) { + if (rule.equals(candidate.get("name").asText())) { + return candidate; + } + } + throw new IllegalStateException("No rule " + rule); + } + + private static JsonNode readPolicy(final String policy) { + return JsonUtils.readTree( + TestSuiteBootstrap.getJdbi() + .withHandle( + handle -> + handle + .createQuery("SELECT json FROM policy_entity WHERE name = :name") + .bind("name", policy) + .mapTo(String.class) + .one())); + } + + /** A restart reads the rows again; this server keeps the policies it already loaded. */ + private static void evictPolicies() { + for (final String name : List.of(AUTHOR_POLICY, REVIEWER_POLICY)) { + final var policy = SdkClients.adminClient().policies().getByName(name); + EntityRepository.invalidateCacheForEntity( + Entity.POLICY, policy.getId(), policy.getFullyQualifiedName()); + } + SubjectCache.invalidateAll(); + } + + private static CreateOntologyShape shape(final Ontology ontology, final String name) { + return new CreateOntologyShape() + .withName(name) + .withDisplayName(name) + .withDescription("A shape created by an author of an upgraded install") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(URI.create("https://example.org/model/Person")) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints( + List.of( + new OntologyShapeConstraint() + .withId("name-count") + .withPath(URI.create("https://example.org/model/name")) + .withMinCount(1))); + } + + private static User createAuthor(final TestNamespace ns) { + final String name = ns.shortPrefix("upgradedAuthor"); + return ns.trackRoot( + Entity.USER, + SdkClients.adminClient() + .users() + .create( + new CreateUser() + .withName(name) + .withEmail(name + "@test.om.org") + .withDescription("author of an upgraded install") + .withRoles( + List.of( + SdkClients.adminClient() + .roles() + .getByName("OntologyAuthor") + .getId())))); + } + + private static int createShape(final User user, final String body) { + final String token = + JwtAuthProvider.tokenFor(user.getEmail(), user.getEmail(), new String[] {}, 600); + try { + return HTTP.send( + HttpRequest.newBuilder() + .uri(URI.create(SdkClients.getServerUrl() + "/v1/ontologyShapes")) + .header("Authorization", "Bearer " + token) + .header("Content-Type", "application/json") + .timeout(Duration.ofSeconds(60)) + .POST(HttpRequest.BodyPublishers.ofString(body)) + .build(), + HttpResponse.BodyHandlers.ofString()) + .statusCode(); + } catch (java.io.IOException | InterruptedException e) { + throw new IllegalStateException("POST /v1/ontologyShapes", e); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java new file mode 100644 index 000000000000..37a41af64da5 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeProposalAskIT.java @@ -0,0 +1,595 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declare; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.declareKey; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.literals; +import static org.openmetadata.it.tests.OntologyShapeCheckFixtures.on; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.ACCOUNTS; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.approve; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.checkOf; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.checkOfConstraint; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.checks; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.generated; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.hasTestSuite; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.listed; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.openTasks; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.ranged; +import static org.openmetadata.it.tests.OntologyShapeCheckProposalIT.release; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.ActivateOntologyRelease; +import org.openmetadata.schema.api.tasks.ResolveTask; +import org.openmetadata.schema.api.teams.CreateTeam; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.teams.Role; +import org.openmetadata.schema.entity.teams.Team; +import org.openmetadata.schema.tests.type.TestCaseStatus; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.TaskEntityStatus; +import org.openmetadata.schema.type.TaskResolutionType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyCheckReconcileQueue; + +/** + * Who is asked to accept a proposed test, who may, and what a reader who may not view the task or + * the test is shown (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyShapeProposalAskIT extends BaseOntologyApprovalIT { + private static final String DENIED = "operation CreateTests denied by role"; + + private static List assignees(final JsonNode task) { + final List names = new ArrayList<>(); + task.path("assignees").forEach(assignee -> names.add(assignee.path("name").asText())); + return names; + } + + private static void ownedBy(final String path, final String type, final EntityReference owner) { + admin() + .getHttpClient() + .executeForString( + HttpMethod.PATCH, + path, + JsonUtils.readTree( + "[{\"op\":\"add\",\"path\":\"/owners\",\"value\":[{\"id\":\"" + + owner.getId() + + "\",\"type\":\"" + + type + + "\"}]}]")); + } + + private static Ontology ontologyWith(final TestNamespace ns, final String name) { + return createOntology(ns, name); + } + + private static JsonNode onlyTask(final OntologyConcept account) { + final List open = openTasks(account); + assertEquals(1, open.size()); + assertEquals("Ingestion", open.getFirst().path("payload").path("source").asText()); + return open.getFirst(); + } + + private static OpenMetadataException refused(final OpenMetadataClient who, final String taskId) { + return assertThrows( + OpenMetadataException.class, + () -> + who.tasks() + .resolve( + taskId, new ResolveTask().withResolutionType(TaskResolutionType.Approved))); + } + + private static Role mayCreate(final RdfAccessFixtures access) { + return access.allowRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + } + + @Test + void teamMembers(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "assignteam"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("pra")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final Role deny = access.denyRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + final OpenMetadataClient ok = + OntologyBindingFixtures.client(access.userToken("mok", List.of())); + final OpenMetadataClient denied = + OntologyBindingFixtures.client(access.userToken("mdeny", List.of(deny.getId()))); + final EntityReference okUser = OntologyBindingFixtures.readerReference(ok); + final EntityReference deniedUser = OntologyBindingFixtures.readerReference(denied); + final Team team = + admin() + .teams() + .create( + new CreateTeam() + .withName("team" + access.suffix()) + .withTeamType(CreateTeam.TeamType.GROUP) + .withUsers(List.of(okUser.getId(), deniedUser.getId()))); + try { + final String tableId = fixture.table("accounts").getId().toString(); + ownedBy("/v1/tables/" + tableId, "team", team.getEntityReference()); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final JsonNode task = onlyTask(account); + assertEquals(List.of(okUser.getName()), assignees(task)); + + final String taskId = task.path("id").asText(); + final OpenMetadataException refusal = refused(denied, taskId); + assertEquals(403, refusal.getStatusCode()); + assertTrue(refusal.getMessage().contains(DENIED), refusal.getMessage()); + assertEquals(0, generated(fixture.table("accounts").getFullyQualifiedName(), "all").size()); + assertFalse(hasTestSuite(tableId)); + + ok.tasks() + .resolve(taskId, new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + + final List tests = + generated(fixture.table("accounts").getFullyQualifiedName(), "all"); + assertEquals(1, tests.size()); + assertEquals(okUser.getName(), tests.getFirst().path("updatedBy").asText()); + final String suiteId = tests.getFirst().path("testSuite").path("id").asText(); + final JsonNode suite = + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/dataQuality/testSuites/" + suiteId + "?fields=pipelines", + null)); + assertEquals(1, suite.path("pipelines").size()); + } finally { + admin().teams().delete(team.getId().toString()); + } + } + } + + @Test + void deniedOwner(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "assigndenied"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("prb")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final Role deny = access.denyRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + final EntityReference deniedOwner = + OntologyBindingFixtures.readerReference( + OntologyBindingFixtures.client(access.userToken("odeny", List.of(deny.getId())))); + final EntityReference ontologyOwner = + OntologyBindingFixtures.readerReference( + OntologyBindingFixtures.client( + access.userToken("oont", List.of(mayCreate(access).getId())))); + ownedBy("/v1/tables/" + fixture.table("accounts").getId(), "user", deniedOwner); + ownedBy("/v1/ontologies/" + ontology.getId(), "user", ontologyOwner); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + + release(ns, ontology); + + assertEquals(List.of(ontologyOwner.getName()), assignees(onlyTask(fixture.type("Account")))); + } + } + + @Test + void noTableOwner(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "assignontology"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("prc")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, fixture, "AccountShape", "Account", listed(fixture), ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + for (final JsonNode task : openTasks(account)) { + assertEquals(List.of("admin"), assignees(task)); + } + + final EntityReference ontologyOwner = + OntologyBindingFixtures.readerReference( + OntologyBindingFixtures.client( + access.userToken("oont", List.of(mayCreate(access).getId())))); + ownedBy("/v1/ontologies/" + ontology.getId(), "user", ontologyOwner); + final String emailTask = + checkOf(checks(account), "email").getProposal().getTask().getId().toString(); + OntologyShapeCheckProposalIT.cancel(emailTask); + OntologyShapeCheckProposalIT.cancel( + checkOf(checks(account), "age").getProposal().getTask().getId().toString()); + OntologyCheckReconcileQueue.instance().afterActivation(ontology.getId(), "admin"); + OntologyShapeCheckProposalIT.settle(); + + final List asked = openTasks(account); + assertEquals(2, asked.size()); + for (final JsonNode task : asked) { + assertEquals(List.of(ontologyOwner.getName()), assignees(task)); + } + } + } + + @Test + void noOneMay(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "assignnone"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("prg")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final Role deny = access.denyRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + final OpenMetadataClient tableOwner = + OntologyBindingFixtures.client(access.userToken("tdeny", List.of(deny.getId()))); + final EntityReference tableOwnerUser = OntologyBindingFixtures.readerReference(tableOwner); + final EntityReference ontologyOwnerUser = + OntologyBindingFixtures.readerReference( + OntologyBindingFixtures.client(access.userToken("odeny", List.of(deny.getId())))); + final String tableId = fixture.table("accounts").getId().toString(); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + ownedBy("/v1/tables/" + tableId, "user", tableOwnerUser); + ownedBy("/v1/ontologies/" + ontology.getId(), "user", ontologyOwnerUser); + declare( + ontology, fixture, "AccountShape", "Account", listed(fixture), ranged(fixture, "120")); + + release(ns, ontology); + + final OntologyConcept account = fixture.type("Account"); + final List filed = openTasks(account); + assertEquals(2, filed.size()); + for (final JsonNode task : filed) { + assertEquals(List.of(tableOwnerUser.getName()), assignees(task)); + } + final String emailTask = taskOf(account, "email-listed"); + final String ageTask = taskOf(account, "age-range"); + + final OpenMetadataException refusal = refused(tableOwner, emailTask); + assertEquals(403, refusal.getStatusCode()); + assertTrue(refusal.getMessage().contains(DENIED), refusal.getMessage()); + assertEquals(TaskEntityStatus.Open, admin().tasks().get(emailTask).getStatus()); + assertEquals(0, generated(tableFqn, "all").size()); + assertFalse(hasTestSuite(tableId)); + + approve(ageTask); + assertEquals(1, generated(tableFqn, "all").size()); + assertTrue(hasTestSuite(tableId)); + } + } + + @Test + void deniedOwnerMayNotReject(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "assignreject"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("prh")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final Role deny = access.denyRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + final OpenMetadataClient tableOwner = + OntologyBindingFixtures.client(access.userToken("rdeny", List.of(deny.getId()))); + final String tableId = fixture.table("accounts").getId().toString(); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + final EntityReference ownerUser = OntologyBindingFixtures.readerReference(tableOwner); + ownedBy("/v1/tables/" + tableId, "user", ownerUser); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + final String taskId = taskOf(account, "email-listed"); + + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> + tableOwner + .tasks() + .resolve( + taskId, + new ResolveTask().withResolutionType(TaskResolutionType.Rejected))); + + assertEquals(403, refusal.getStatusCode()); + assertEquals( + "Principal: CatalogPrincipal{name='" + + ownerUser.getName() + + "'} operation CreateTests denied by role " + + deny.getName() + + ", policy " + + deny.getName().replace("Role", "Policy") + + ", rule prhdeny", + refusal.getMessage()); + assertEquals(TaskEntityStatus.Open, admin().tasks().get(taskId).getStatus()); + + admin() + .tasks() + .resolve(taskId, new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + + assertEquals(TaskEntityStatus.Rejected, admin().tasks().get(taskId).getStatus()); + assertEquals(0, generated(tableFqn, "all").size()); + assertFalse(hasTestSuite(tableId)); + } + } + + @Test + void lostTheRight(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "assignlost"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("prd")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final Role allow = access.allowRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + final Role deny = access.denyRole(MetadataOperation.CREATE_TESTS, Entity.TABLE); + final OpenMetadataClient assignee = + OntologyBindingFixtures.client(access.userToken("assignee", List.of(allow.getId()))); + final EntityReference user = OntologyBindingFixtures.readerReference(assignee); + final String tableId = fixture.table("accounts").getId().toString(); + ownedBy("/v1/tables/" + tableId, "user", user); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + final JsonNode task = onlyTask(fixture.type("Account")); + assertEquals(List.of(user.getName()), assignees(task)); + + admin() + .getHttpClient() + .executeForString( + HttpMethod.PATCH, + "/v1/users/" + user.getId(), + JsonUtils.readTree( + "[{\"op\":\"add\",\"path\":\"/roles/-\",\"value\":{\"id\":\"" + + deny.getId() + + "\",\"type\":\"role\"}}]")); + final String taskId = task.path("id").asText(); + final OpenMetadataException refusal = refused(assignee, taskId); + + assertEquals(403, refusal.getStatusCode()); + assertTrue(refusal.getMessage().contains(DENIED), refusal.getMessage()); + assertEquals(TaskEntityStatus.Open, admin().tasks().get(taskId).getStatus()); + assertEquals(0, generated(fixture.table("accounts").getFullyQualifiedName(), "all").size()); + assertFalse(hasTestSuite(tableId)); + } + } + + private static JsonNode taskWithFiler(final String taskId) { + return JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, "/v1/tasks/" + taskId + "?fields=assignees,createdBy", null)); + } + + private static void activateAs( + final OpenMetadataClient activator, final TestNamespace ns, final Ontology ontology) { + final OntologyRelease release = capture(ontology); + final var review = submit(ns, Entity.ONTOLOGY_RELEASE, release.getFullyQualifiedName()); + SdkClients.user1Client() + .tasks() + .resolve(review.getId().toString(), decision(TaskResolutionType.Approved)); + activator + .ontologies() + .activate( + ontology.getId(), + new ActivateOntologyRelease() + .withReleaseId(release.getId()) + .withExpectedActivationRevision( + admin().ontologies().state(ontology.getId()).getActivationRevision())); + OntologyShapeCheckProposalIT.settle(); + } + + @Test + void theOwnerWhoActivatesMayApprove(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "filerapprove"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("pri")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + final OpenMetadataClient owner = + OntologyBindingFixtures.client(access.userToken("filer", List.of())); + final EntityReference ownerUser = OntologyBindingFixtures.readerReference(owner); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + ownedBy("/v1/tables/" + fixture.table("accounts").getId(), "user", ownerUser); + ownedBy("/v1/ontologies/" + ontology.getId(), "user", ownerUser); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + + activateAs(owner, ns, ontology); + + final JsonNode filed = onlyTask(fixture.type("Account")); + final JsonNode task = taskWithFiler(filed.path("id").asText()); + assertEquals("governance-bot", task.path("createdBy").path("name").asText()); + assertEquals("governance-bot", task.path("updatedBy").asText()); + assertEquals(List.of(ownerUser.getName()), assignees(task)); + assertEquals(0, generated(tableFqn, "all").size()); + final String taskId = filed.path("id").asText(); + assertFalse( + owner.tasks().listCreated(null, null, null, null, 1000).getData().stream() + .anyMatch(listed -> listed.getId().toString().equals(taskId))); + assertTrue( + owner.tasks().listAssigned(null, null, null, null, 1000).getData().stream() + .anyMatch(listed -> listed.getId().toString().equals(taskId))); + + owner + .tasks() + .resolve( + filed.path("id").asText(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + + assertEquals(1, generated(tableFqn, "all").size()); + + admin().users().delete(ownerUser.getId()); + assertEquals( + "governance-bot", + JsonUtils.readTree( + admin() + .getHttpClient() + .executeForString( + HttpMethod.GET, "/v1/tasks/" + taskId + "?fields=createdBy", null)) + .path("createdBy") + .path("name") + .asText()); + } + } + + @Test + void theOwnerWhoWritesABindingMayReject(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "filerreject"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures access = new RdfAccessFixtures("prj")) { + declareKey(fixture, "accounts", List.of("id"), "email"); + final OpenMetadataClient owner = + OntologyBindingFixtures.client(access.userToken("binder", List.of())); + final EntityReference ownerUser = OntologyBindingFixtures.readerReference(owner); + final String tableFqn = fixture.table("accounts").getFullyQualifiedName(); + ownedBy("/v1/tables/" + fixture.table("accounts").getId(), "user", ownerUser); + ownedBy("/v1/ontologies/" + ontology.getId(), "user", ownerUser); + declare(ontology, fixture, "AccountShape", "Account", listed(fixture)); + release(ns, ontology); + assertEquals(0, openTasks(fixture.type("Account")).size()); + + fixture.bindAll(owner); + OntologyShapeCheckProposalIT.settle(); + + final JsonNode filed = onlyTask(fixture.type("Account")); + final JsonNode task = taskWithFiler(filed.path("id").asText()); + assertEquals("governance-bot", task.path("createdBy").path("name").asText()); + assertEquals(List.of(ownerUser.getName()), assignees(task)); + + owner + .tasks() + .resolve( + filed.path("id").asText(), + new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + + assertEquals( + TaskEntityStatus.Rejected, admin().tasks().get(filed.path("id").asText()).getStatus()); + assertEquals(0, generated(tableFqn, "all").size()); + } + } + + @Test + void blindReaders(final TestNamespace ns) { + final Ontology ontology = ontologyWith(ns, "readers"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, ACCOUNTS).withRows(); + RdfAccessFixtures noTask = new RdfAccessFixtures("pre"); + RdfAccessFixtures noTest = new RdfAccessFixtures("prf")) { + fixture.bindAll(); + declareKey(fixture, "accounts", List.of("id"), "email"); + declare( + ontology, + fixture, + "AccountShape", + "Account", + on(fixture, "l1", "accountEmail").withIn(literals("a")), + on(fixture, "l2", "accountEmail").withIn(literals("b")), + on(fixture, "l3", "accountEmail").withIn(literals("c")), + ranged(fixture, "120")); + release(ns, ontology); + final OntologyConcept account = fixture.type("Account"); + approve(taskOf(account, "l1")); + approve(taskOf(account, "age-range")); + admin() + .tasks() + .resolve( + taskOf(account, "l3"), + new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + final String ageTest = + proposalOf(admin(), account, "age-range").getTestCase().getFullyQualifiedName(); + admin() + .getHttpClient() + .executeForString( + HttpMethod.POST, + "/v1/dataQuality/testCases/testCaseResults/" + + java.net.URLEncoder.encode(ageTest, java.nio.charset.StandardCharsets.UTF_8), + Map.of( + "timestamp", 1_700_000_000_000L, "testCaseStatus", "Failed", "result", "3 hits")); + final OpenMetadataClient taskBlind = + OntologyBindingFixtures.client( + noTask.userToken( + "notask", List.of(noTask.denyRole(MetadataOperation.ALL, Entity.TASK).getId()))); + final OpenMetadataClient testBlind = + OntologyBindingFixtures.client( + noTest.userToken( + "notest", + List.of(noTest.denyRole(MetadataOperation.ALL, Entity.TEST_CASE).getId()))); + + assertEquals( + "{\"state\":\"accepted\",\"testCase\":{\"id\":\"" + + proposalOf(admin(), account, "l1").getTestCase().getId() + + "\",\"type\":\"testCase\",\"name\":\"" + + proposalOf(admin(), account, "l1").getTestCase().getName() + + "\",\"fullyQualifiedName\":\"" + + proposalOf(admin(), account, "l1").getTestCase().getFullyQualifiedName() + + "\",\"description\":" + + JsonUtils.pojoToJson( + proposalOf(admin(), account, "l1").getTestCase().getDescription()) + + ",\"displayName\":\"" + + proposalOf(admin(), account, "l1").getTestCase().getDisplayName() + + "\",\"deleted\":false}}", + json(proposalOf(admin(), account, "l1")).replaceAll(",\"href\":\"[^\"]*\"", "")); + assertEquals( + TestCaseStatus.Failed, proposalOf(admin(), account, "age-range").getLatestResultStatus()); + assertEquals( + 1_700_000_000_000L, proposalOf(admin(), account, "age-range").getLatestResultTimestamp()); + + assertEquals("{\"state\":\"proposed\"}", json(proposalOf(taskBlind, account, "l2"))); + assertEquals("{\"state\":\"rejected\"}", json(proposalOf(taskBlind, account, "l3"))); + assertNotNull(proposalOf(taskBlind, account, "l1").getTestCase()); + assertEquals( + TestCaseStatus.Failed, + proposalOf(taskBlind, account, "age-range").getLatestResultStatus()); + + assertEquals("{\"state\":\"accepted\"}", json(proposalOf(testBlind, account, "l1"))); + assertEquals("{\"state\":\"accepted\"}", json(proposalOf(testBlind, account, "age-range"))); + assertNull(proposalOf(testBlind, account, "age-range").getLatestResultStatus()); + assertNull(proposalOf(testBlind, account, "age-range").getLatestResultTimestamp()); + assertNotNull(proposalOf(testBlind, account, "l2").getTask()); + assertNotNull(proposalOf(testBlind, account, "l3").getTask()); + } + } + + private static String json(final Object proposal) { + return JsonUtils.pojoToJson(proposal); + } + + private static String taskOf(final OntologyConcept account, final String constraintId) { + return proposalOf(admin(), account, constraintId).getTask().getId().toString(); + } + + private static org.openmetadata.schema.api.data.OntologyShapeCheckProposal proposalOf( + final OpenMetadataClient reader, final OntologyConcept account, final String constraintId) { + return checkOfConstraint(reader, account, constraintId).getProposal(); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeResourceIT.java new file mode 100644 index 000000000000..bebdcd5907f2 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyShapeResourceIT.java @@ -0,0 +1,557 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.openmetadata.it.auth.JwtAuthProvider; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.data.ImportOntologyShapes; +import org.openmetadata.schema.api.data.OntologyShapeImportAction; +import org.openmetadata.schema.api.data.OntologyShapeImportResult; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.models.ListParams; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.OntologyRepository; +import org.openmetadata.service.jdbi3.OntologyShapeRepository; +import org.openmetadata.service.resources.ontology.OntologyShapeMapper; + +/** Persistence, SHACL exchange and authorization of ontology shapes in a working draft. */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +public class OntologyShapeResourceIT extends BaseOntologyApprovalIT { + private static final HttpClient HTTP = HttpClient.newHttpClient(); + private static final String MODEL = "https://example.org/model/"; + private static final URI PERSON = URI.create(MODEL + "Person"); + private static final URI NAME = URI.create(MODEL + "name"); + private static final URI AGE = URI.create(MODEL + "age"); + private static final URI XSD_INTEGER = URI.create("http://www.w3.org/2001/XMLSchema#integer"); + + @Test + void aShapeIsCreatedReadUpdatedAndDeletedWithItsConstraintsIntact(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + final CreateOntologyShape request = shapeRequest(ontology, "PersonShape"); + + final OntologyShape created = client.ontologyShapes().create(request); + final OntologyShape stored = client.ontologyShapes().get(created.getId().toString()); + + assertEquals(PERSON, stored.getTargetConcept()); + assertEquals(OntologyShapeSeverity.VIOLATION, stored.getSeverity()); + assertEquals( + List.of("name-count", "age-range", "name-values"), + stored.getConstraints().stream().map(OntologyShapeConstraint::getId).toList()); + assertEquals( + JsonUtils.pojoToJson(request.getConstraints()), + JsonUtils.pojoToJson(stored.getConstraints())); + assertEquals(ontology.getFullyQualifiedName() + ".PersonShape", stored.getFullyQualifiedName()); + + request.setSeverity(OntologyShapeSeverity.WARNING); + request.getConstraints().getFirst().setMaxCount(2); + final OntologyShape updated = client.ontologyShapes().upsert(request); + + assertEquals(created.getId(), updated.getId()); + assertEquals(OntologyShapeSeverity.WARNING, updated.getSeverity()); + assertEquals("name-count", updated.getConstraints().getFirst().getId()); + assertEquals(Integer.valueOf(2), updated.getConstraints().getFirst().getMaxCount()); + + client.ontologyShapes().delete(created.getId().toString()); + assertTrue(client.ontologyShapes().get(created.getId().toString(), null, "all").getDeleted()); + } + + @Test + void aShapeThatCanNeverBeSatisfiedIsRefusedWhenItIsSaved(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + + final var cardinality = shapeRequest(ontology, "Cardinality"); + cardinality.getConstraints().getFirst().withMinCount(3).withMaxCount(2); + final var emptyList = shapeRequest(ontology, "EmptyList"); + emptyList.getConstraints().get(2).setIn(List.of()); + final var repeatedId = shapeRequest(ontology, "RepeatedId"); + repeatedId.getConstraints().get(1).setId("name-count"); + final var relative = shapeRequest(ontology, "Relative"); + relative.getConstraints().getFirst().setPath(URI.create("name")); + + assertRefused(client, cardinality, "minCount 3 is above maxCount 2"); + assertRefused(client, emptyList, "An in list names at least one value"); + assertRefused(client, repeatedId, "A constraint id is unique within its shape: name-count"); + assertRefused(client, relative, "An IRI must be absolute: name"); + assertEquals( + 0, + client + .ontologyShapes() + .list(new ListParams().addFilter("ontologyId", ontology.getId().toString())) + .getData() + .size()); + } + + @Test + void exportedShaclImportsIntoAFreshOntologyWithEveryShapeAndConstraintId(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology source = createOntology(ns, "shapeSource"); + final Ontology target = createOntology(ns, "shapeTarget"); + final var first = client.ontologyShapes().create(shapeRequest(source, "PersonShape")); + final var second = + client + .ontologyShapes() + .create( + new CreateOntologyShape() + .withName("EmptyShape") + .withDisplayName("EmptyShape") + .withDescription("No constraints yet") + .withOntology(source.getFullyQualifiedName()) + .withTargetConcept(URI.create(MODEL + "Other")) + .withSeverity(OntologyShapeSeverity.INFO)); + + final String shacl = exportDraft(source); + final OntologyShapeImportResult imported = + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(target.getFullyQualifiedName()) + .withContent(shacl)); + + assertEquals(List.of(), imported.getUnsupported()); + assertEquals( + List.of("EmptyShape", "PersonShape"), + imported.getShapes().stream().map(shape -> shape.getName()).toList()); + assertTrue( + imported.getShapes().stream() + .allMatch(s -> s.getAction() == OntologyShapeImportAction.CREATED)); + final OntologyShape copy = + client.ontologyShapes().getByName(target.getFullyQualifiedName() + ".PersonShape"); + assertEquals( + JsonUtils.pojoToJson(first.getConstraints()), JsonUtils.pojoToJson(copy.getConstraints())); + assertEquals(first.getTargetConcept(), copy.getTargetConcept()); + assertEquals(first.getSeverity(), copy.getSeverity()); + final OntologyShape copyOfSecond = + client.ontologyShapes().getByName(target.getFullyQualifiedName() + ".EmptyShape"); + assertEquals(second.getTargetConcept(), copyOfSecond.getTargetConcept()); + assertEquals(OntologyShapeSeverity.INFO, copyOfSecond.getSeverity()); + + final OntologyShapeImportResult again = + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(target.getFullyQualifiedName()) + .withContent(shacl)); + assertTrue( + again.getShapes().stream() + .allMatch(s -> s.getAction() == OntologyShapeImportAction.UPDATED), + "importing the same file again updates by name"); + } + + @Test + void aFileWithUnsupportedConstructsImportsItsSupportedPartsAndNamesTheRest( + final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + final String file = + """ + @prefix sh: . + @prefix ex: . + + ex:PersonShape a sh:NodeShape ; + sh:targetClass ex:Person ; + sh:closed true ; + sh:property [ sh:path ex:name ; sh:minCount 1 ; sh:maxCount 1 ; sh:minLength 2 ] ; + sh:property [ sh:path [ sh:inversePath ex:knows ] ; sh:minCount 1 ] ; + sh:or ( [ sh:class ex:A ] [ sh:class ex:B ] ) . + """; + + final OntologyShapeImportResult result = + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent(file)); + + assertEquals( + List.of("sh:closed", "sh:minLength", "sh:or", "sh:path"), + result.getUnsupported().stream() + .map(item -> item.getConstruct()) + .distinct() + .sorted() + .toList()); + final OntologyShape stored = + client.ontologyShapes().getByName(ontology.getFullyQualifiedName() + ".PersonShape"); + assertEquals(1, stored.getConstraints().size()); + assertEquals(NAME, stored.getConstraints().getFirst().getPath()); + assertEquals(Integer.valueOf(1), stored.getConstraints().getFirst().getMinCount()); + assertEquals(Integer.valueOf(1), stored.getConstraints().getFirst().getMaxCount()); + assertEquals(List.of("c1"), result.getShapes().getFirst().getConstraintIds()); + } + + @Test + void aDryRunImportWritesNothingAndAnUnsatisfiableFileWritesNothing(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + final String valid = + """ + @prefix sh: . + @prefix ex: . + ex:A a sh:NodeShape ; sh:targetClass ex:Person ; sh:property [ sh:path ex:name ; sh:minCount 1 ] . + """; + final String refused = + """ + @prefix sh: . + @prefix ex: . + ex:A a sh:NodeShape ; sh:targetClass ex:Person ; sh:property [ sh:path ex:name ; sh:minCount 1 ] . + ex:B a sh:NodeShape ; sh:targetClass ex:Person ; sh:property [ sh:path ex:name ; sh:minCount 3 ; sh:maxCount 2 ] . + """; + + final var dry = + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent(valid) + .withDryRun(true)); + final OpenMetadataException failure = + assertThrows( + OpenMetadataException.class, + () -> + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent(refused))); + + assertTrue(dry.getDryRun()); + assertEquals( + List.of("A:CREATED"), + dry.getShapes().stream().map(s -> s.getName() + ":" + s.getAction()).toList()); + assertEquals(400, failure.getStatusCode()); + assertTrue(failure.getMessage().contains("minCount 3 is above maxCount 2")); + assertEquals( + 0, + client + .ontologyShapes() + .list(new ListParams().addFilter("ontologyId", ontology.getId().toString())) + .getData() + .size()); + } + + @Test + void aFileWithAShapeNameTheNameRulesRefuseWritesNothing(final TestNamespace ns) { + final OpenMetadataClient client = SdkClients.adminClient(); + final Ontology ontology = createOntology(ns); + final String fine = + "ex:Fine a sh:NodeShape ; sh:targetClass ex:Person ; sh:property [ sh:path ex:name ; sh:minCount 1 ] .\n"; + final String prefixes = + "@prefix sh: .\n@prefix ex: .\n"; + final String tooLong = + prefixes + + fine + + "ex:Long a sh:NodeShape ; sh:name \"" + + "n".repeat(300) + + "\" ; sh:targetClass ex:Person ; sh:property [ sh:path ex:name ; sh:minCount 1 ] .\n"; + final String invalid = + prefixes + + fine + + "ex:Bad a sh:NodeShape ; sh:name \"bad\\\"quote>\" ; sh:targetClass ex:Person ; sh:property [ sh:path ex:name ; sh:minCount 1 ] .\n"; + + for (final String file : List.of(tooLong, invalid)) { + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + client + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent(file))); + assertEquals(400, refused.getStatusCode(), refused.getMessage()); + assertTrue(refused.getMessage().contains("cannot be imported"), refused.getMessage()); + } + assertEquals(0, shapeCount(ontology)); + } + + @Test + void aFileOverTheShapeCapWritesNothing(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final StringBuilder file = + new StringBuilder( + "@prefix sh: .\n@prefix ex: .\n"); + for (int shape = 0; shape <= 1000; shape++) { + file.append("ex:S").append(shape).append(" a sh:NodeShape ; sh:targetClass ex:Person .\n"); + } + + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent(file.toString()))); + + assertEquals(400, refused.getStatusCode()); + assertTrue(refused.getMessage().contains("at most 1000 shapes"), refused.getMessage()); + assertEquals(0, shapeCount(ontology)); + } + + @Test + void writesMadeUnderTheDraftLockAreKeptOrDroppedTogether(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyRepository ontologies = + (OntologyRepository) Entity.getEntityRepository(Entity.ONTOLOGY); + final OntologyShapeRepository shapes = + (OntologyShapeRepository) Entity.getEntityRepository(Entity.ONTOLOGY_SHAPE); + final OntologyShape first = + new OntologyShapeMapper().createToEntity(shapeRequest(ontology, "First"), "admin"); + final OntologyShape second = + new OntologyShapeMapper().createToEntity(shapeRequest(ontology, "Second"), "admin"); + + shapes.prepareInternal(first, false); + shapes.prepareInternal(second, false); + + assertThrows( + IllegalStateException.class, + () -> + ontologies.writeWorkingDraft( + ontology.getId(), + () -> { + shapes.createOrUpdate(null, first, "admin"); + shapes.createOrUpdate(null, second, "admin"); + throw new IllegalStateException("the import fails after both writes"); + })); + assertEquals(0, shapeCount(ontology)); + + ontologies.writeWorkingDraft( + ontology.getId(), + () -> { + shapes.createOrUpdate(null, first, "admin"); + return shapes.createOrUpdate(null, second, "admin"); + }); + assertEquals(2, shapeCount(ontology)); + } + + private static int shapeCount(final Ontology ontology) { + return SdkClients.adminClient() + .ontologyShapes() + .list(new ListParams().addFilter("ontologyId", ontology.getId().toString())) + .getData() + .size(); + } + + @Test + void textThatIsNotTurtleIsRefused(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + + final OpenMetadataException failure = + assertThrows( + OpenMetadataException.class, + () -> + SdkClients.adminClient() + .ontologyShapes() + .importShapes( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent("this is { not turtle"))); + + assertEquals(400, failure.getStatusCode()); + } + + @Test + void aConsumerCannotWriteOrReadTheWorkingDraftShapesAndAnAuthorCan(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyShape shape = + SdkClients.adminClient().ontologyShapes().create(shapeRequest(ontology, "PersonShape")); + final User consumer = createUser(ns, "shapeConsumer", "DataConsumer"); + final User author = createUser(ns, "shapeAuthor", "OntologyAuthor"); + final String id = ontology.getId().toString(); + final String body = JsonUtils.pojoToJson(shapeRequest(ontology, "ByCaller")); + final String importBody = + JsonUtils.pojoToJson( + new ImportOntologyShapes() + .withOntology(ontology.getFullyQualifiedName()) + .withContent( + "@prefix sh: . " + + " a sh:NodeShape ; sh:targetClass ; " + + "sh:property [ sh:path ; sh:minCount 1 ] .")); + + assertEquals(403, status(consumer, "GET", "/v1/ontologyShapes?ontologyId=" + id, null)); + assertEquals(403, status(consumer, "GET", "/v1/ontologyShapes", null)); + assertEquals( + 403, status(consumer, "GET", "/v1/ontologies/" + id + "/export?format=shacl", null)); + assertEquals(403, status(consumer, "POST", "/v1/ontologyShapes", body)); + assertEquals(403, status(consumer, "PUT", "/v1/ontologyShapes", body)); + assertEquals(403, status(consumer, "POST", "/v1/ontologyShapes/import", importBody)); + assertEquals( + 403, + status( + consumer, + "PATCH", + "/v1/ontologyShapes/" + shape.getId(), + "[{\"op\":\"replace\",\"path\":\"/description\",\"value\":\"changed\"}]")); + assertEquals(403, status(consumer, "DELETE", "/v1/ontologyShapes/" + shape.getId(), null)); + + assertEquals(200, status(author, "GET", "/v1/ontologyShapes?ontologyId=" + id, null)); + assertEquals(200, status(author, "GET", "/v1/ontologies/" + id + "/export?format=shacl", null)); + assertEquals(201, status(author, "POST", "/v1/ontologyShapes", body)); + assertEquals(200, status(author, "POST", "/v1/ontologyShapes/import", importBody)); + assertEquals( + 200, + status(SdkClients.getAdminToken(), "GET", "/v1/ontologyShapes?ontologyId=" + id, null)); + + SdkClients.adminClient().ontologyShapes().delete(shape.getId().toString()); + final String restore = "{\"id\":\"" + shape.getId() + "\"}"; + assertEquals(403, status(consumer, "PUT", "/v1/ontologyShapes/restore", restore)); + assertEquals(200, status(author, "PUT", "/v1/ontologyShapes/restore", restore)); + assertEquals(403, status(consumer, "PUT", "/v1/ontologyShapes/restore", restore)); + SdkClients.adminClient().ontologyShapes().delete(shape.getId().toString()); + assertEquals( + 200, status(SdkClients.getAdminToken(), "PUT", "/v1/ontologyShapes/restore", restore)); + } + + private static void assertRefused( + final OpenMetadataClient client, final CreateOntologyShape request, final String message) { + final OpenMetadataException failure = + assertThrows(OpenMetadataException.class, () -> client.ontologyShapes().create(request)); + assertEquals(400, failure.getStatusCode(), failure.getMessage()); + assertTrue(failure.getMessage().contains(message), failure.getMessage()); + assertFalse(failure.getMessage().isBlank()); + } + + private static CreateOntologyShape shapeRequest(final Ontology ontology, final String name) { + return new CreateOntologyShape() + .withName(name) + .withDisplayName(name) + .withDescription("A person has one name and a sensible age") + .withOntology(ontology.getFullyQualifiedName()) + .withTargetConcept(PERSON) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints( + new java.util.ArrayList<>( + List.of( + new OntologyShapeConstraint() + .withId("name-count") + .withPath(NAME) + .withMinCount(1) + .withMaxCount(1), + new OntologyShapeConstraint() + .withId("age-range") + .withPath(AGE) + .withDatatypeIri(XSD_INTEGER) + .withMinInclusive( + new OntologyLiteral().withValue("0").withDatatypeIri(XSD_INTEGER)) + .withMaxInclusive( + new OntologyLiteral().withValue("150").withDatatypeIri(XSD_INTEGER)), + new OntologyShapeConstraint() + .withId("name-values") + .withPath(NAME) + .withPattern("^[A-Z]") + .withIn( + List.of( + new OntologyShapeValue() + .withLiteral(new OntologyLiteral().withValue("Alice")), + new OntologyShapeValue() + .withLiteral(new OntologyLiteral().withValue("Bob"))))))); + } + + private static String exportDraft(final Ontology ontology) { + return SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/ontologies/" + ontology.getId() + "/export?format=shacl", + null, + RequestOptions.builder().header("Accept", "*/*").build()); + } + + private static User createUser(final TestNamespace ns, final String base, final String role) { + final String name = ns.shortPrefix(base); + return ns.trackRoot( + Entity.USER, + SdkClients.adminClient() + .users() + .create( + new CreateUser() + .withName(name) + .withEmail(name + "@test.om.org") + .withDescription("v7 user") + .withRoles(List.of(SdkClients.adminClient().roles().getByName(role).getId())))); + } + + private static int status( + final User user, final String method, final String path, final String body) { + return status( + JwtAuthProvider.tokenFor(user.getEmail(), user.getEmail(), new String[] {}, 600), + method, + path, + body); + } + + private static int status( + final String token, final String method, final String path, final String body) { + final String contentType = + "PATCH".equals(method) ? "application/json-patch+json" : "application/json"; + try { + return HTTP.send( + HttpRequest.newBuilder() + .uri(URI.create(SdkClients.getServerUrl() + path)) + .header("Authorization", "Bearer " + token) + .header("Content-Type", contentType) + .timeout(Duration.ofSeconds(60)) + .method( + method, + body == null + ? HttpRequest.BodyPublishers.noBody() + : HttpRequest.BodyPublishers.ofString(body)) + .build(), + HttpResponse.BodyHandlers.ofString()) + .statusCode(); + } catch (java.io.IOException | InterruptedException e) { + throw new IllegalStateException(method + " " + path, e); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologySqlLiteralIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologySqlLiteralIT.java new file mode 100644 index 000000000000..1bb3a1c1734f --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologySqlLiteralIT.java @@ -0,0 +1,263 @@ +/* + * 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; + +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 static org.junit.jupiter.api.Assumptions.assumeTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.function.Consumer; +import java.util.stream.Stream; +import org.jdbi.v3.core.Handle; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.ontology.sql.TypedStatement; +import org.openmetadata.service.ontology.sql.TypedValues; + +/** + * Sends the strings of {@code ontology/sql-value-cases.json} to the database this suite runs on, + * written as the engine family of that database writes them, and reads back what the engine made + * of each one. A string that comes back changed, or a statement that fails, means that the engine + * read part of a value as SQL. + */ +class OntologySqlLiteralIT { + private static final String CHARACTER_TYPE = "VARCHAR"; + private static final Column TEXT = column(ColumnDataType.VARCHAR); + private static final String SERVER_MODE = "SET SESSION sql_mode = DEFAULT"; + private static final String NO_BACKSLASH_ESCAPES = + "SET SESSION sql_mode = 'NO_BACKSLASH_ESCAPES'"; + + private static SqlEngineFamily family() { + return TestSuiteBootstrap.getConnectionType() == ConnectionType.MYSQL + ? SqlEngineFamily.MYSQL + : SqlEngineFamily.POSTGRES; + } + + /** + * The session settings under which the family promises the same characters back. Postgres reads a + * backslash in an ordinary string as an escape only when {@code standard_conforming_strings} is + * off, and the family writes one text for both settings. + */ + private static List sessionsThatReadTheSameCharacters() { + return family() == SqlEngineFamily.MYSQL + ? List.of(SERVER_MODE) + : List.of("SET standard_conforming_strings = on", "SET standard_conforming_strings = off"); + } + + /** Every string that a case gives as a row filter value, a member of a list or a part of a key. */ + static Stream strings() { + return writtenForThisFamily().stream() + .filter(json -> List.of("rowFilterValue", "keyValue").contains(json.get("path").asText())) + .flatMap(OntologySqlLiteralIT::stringsOf); + } + + static Stream searches() { + return writtenForThisFamily().stream() + .filter(json -> "searchText".equals(json.get("path").asText())) + .map(json -> Arguments.of(json.get("id").asText(), json.get("input").asText())); + } + + private static List writtenForThisFamily() { + final String family = family().name().toLowerCase(Locale.ROOT); + return OntologySqlValueCases.withOutcome("rendered").stream() + .filter(json -> family.equals(json.get("engineFamily").asText())) + .toList(); + } + + /** + * A case gives one data type for a value or for a list, and one data type per part for a key. + * Only a string for a character column is written as a string. + */ + private static Stream stringsOf(final JsonNode json) { + final JsonNode input = json.get("input"); + final String[] types = json.get("columnType").asText().split(","); + final List strings = new ArrayList<>(); + for (int member = 0; member < Math.max(1, input.size()); member++) { + final JsonNode value = input.isArray() ? input.get(member) : input; + final String type = types[Math.min(member, types.length - 1)]; + if (value.isTextual() && CHARACTER_TYPE.equals(type)) { + strings.add(Arguments.of(json.get("id").asText(), value.asText())); + } + } + return strings.stream(); + } + + @Test + void theCasesGiveThisDatabaseItsStringsAndItsSearches() { + assertEquals(31, strings().count()); + assertEquals(9, searches().count()); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("strings") + void theEngineReadsBackEachStringAsItArrived(final String caseId, final String text) + throws SQLException { + final String select = sent(sql -> sql.sql("SELECT ").value(TypedValues.value(TEXT, text))); + + try (Handle handle = TestSuiteBootstrap.getJdbi().open(); + Statement statement = unescaped(handle)) { + for (final String session : sessionsThatReadTheSameCharacters()) { + statement.execute(session); + + assertEquals(List.of(text), onlyRow(statement, select), session); + } + } + } + + /** + * MySQL with {@code NO_BACKSLASH_ESCAPES} reads the doubled backslash that the family writes as + * two backslashes. The value that comes back is then another value, and it is still one value: + * no part of it ended the string. + */ + @ParameterizedTest(name = "{0} {1}") + @MethodSource("strings") + void mysqlWithoutBackslashEscapesKeepsEachStringInsideItsQuotes( + final String caseId, final String text) throws SQLException { + assumeTrue(family() == SqlEngineFamily.MYSQL, "Only MySQL has this mode"); + final String select = sent(sql -> sql.sql("SELECT ").value(TypedValues.value(TEXT, text))); + + try (Handle handle = TestSuiteBootstrap.getJdbi().open(); + Statement statement = unescaped(handle)) { + statement.execute(NO_BACKSLASH_ESCAPES); + + assertEquals(List.of(text.replace("\\", "\\\\")), onlyRow(statement, select)); + } + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("searches") + void aSearchFindsItsOwnTextAndNoTextThatOnlyAWildcardWouldMatch( + final String caseId, final String text) throws SQLException { + final String withPlainCharacters = text.replace('%', 'a').replace('_', 'b'); + final String itself = like(text, text); + final String another = like(withPlainCharacters, text); + + try (Handle handle = TestSuiteBootstrap.getJdbi().open(); + Statement statement = unescaped(handle)) { + for (final String session : sessionsThatReadTheSameCharacters()) { + statement.execute(session); + + assertTrue(matches(statement, itself), session); + if (!withPlainCharacters.equals(text)) { + assertFalse(matches(statement, another), session); + } + } + } + } + + /** + * The pattern of a search is a string too. With {@code NO_BACKSLASH_ESCAPES} it comes back with + * each backslash doubled, and it is still one string. + */ + @ParameterizedTest(name = "{0} {1}") + @MethodSource("searches") + void mysqlWithoutBackslashEscapesKeepsEachPatternInsideItsQuotes( + final String caseId, final String text) throws SQLException { + assumeTrue(family() == SqlEngineFamily.MYSQL, "Only MySQL has this mode"); + final String select = + sent(sql -> sql.sql("SELECT ").contains(TypedValues.searchText(TEXT, text))); + + try (Handle handle = TestSuiteBootstrap.getJdbi().open(); + Statement statement = unescaped(handle)) { + statement.execute(SERVER_MODE); + final String pattern = onlyRow(statement, select).getFirst(); + statement.execute(NO_BACKSLASH_ESCAPES); + + assertEquals(List.of(pattern.replace("\\", "\\\\")), onlyRow(statement, select)); + } + } + + @Test + void theEngineReadsATimeOfDayAsTheTimeItWasGiven() throws SQLException { + final String time = "23:59:58.123456"; + final String select = + sent(sql -> sql.sql("SELECT ").value(TypedValues.value(column(ColumnDataType.TIME), time))); + + try (Handle handle = TestSuiteBootstrap.getJdbi().open(); + Statement statement = unescaped(handle); + ResultSet rows = statement.executeQuery(select)) { + assertTrue(rows.next(), select); + assertEquals(LocalTime.parse(time), rows.getObject(1, LocalTime.class)); + } + } + + private static Column column(final ColumnDataType type) { + return new Column().withName("c").withDataType(type); + } + + /** {@code SELECT LIKE }. */ + private static String like(final String candidate, final String text) { + return sent( + sql -> + sql.sql("SELECT ") + .value(TypedValues.value(TEXT, candidate)) + .sql(" LIKE ") + .contains(TypedValues.searchText(TEXT, text))); + } + + /** + * The finished text as it reaches a driver. The reader of {@code :name} parameters has turned + * each {@code \:} back into a colon by then. + */ + private static String sent(final Consumer parts) { + final TypedStatement.Builder sql = TypedStatement.builder(); + parts.accept(sql); + return family().inline(sql.build()).replace("\\:", ":"); + } + + /** A statement that the driver sends as it is, with no JDBC escape syntax read out of it. */ + private static Statement unescaped(final Handle handle) throws SQLException { + final Statement statement = handle.getConnection().createStatement(); + statement.setEscapeProcessing(false); + return statement; + } + + private static List onlyRow(final Statement statement, final String select) + throws SQLException { + try (ResultSet rows = statement.executeQuery(select)) { + assertTrue(rows.next(), select); + final List row = new ArrayList<>(); + for (int column = 1; column <= rows.getMetaData().getColumnCount(); column++) { + row.add(rows.getString(column)); + } + assertFalse(rows.next(), select); + return row; + } + } + + private static boolean matches(final Statement statement, final String select) + throws SQLException { + try (ResultSet rows = statement.executeQuery(select)) { + assertTrue(rows.next(), select); + assertEquals(1, rows.getMetaData().getColumnCount(), select); + return rows.getBoolean(1); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologySqlValueCases.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologySqlValueCases.java new file mode 100644 index 000000000000..f826b7f662bb --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologySqlValueCases.java @@ -0,0 +1,53 @@ +/* + * 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; + +import com.fasterxml.jackson.databind.JsonNode; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.List; +import java.util.stream.StreamSupport; +import org.openmetadata.schema.utils.JsonUtils; + +/** + * The cases of {@code ontology/sql-value-cases.json}, which the service module ships with its + * tests. Each case gives a value as it can arrive and what must happen to it. + */ +final class OntologySqlValueCases { + private static final String CASES = "/ontology/sql-value-cases.json"; + + private OntologySqlValueCases() {} + + /** Every case whose outcome is of {@code kind}, in the order of the file. */ + static List withOutcome(final String kind) { + return all().stream() + .filter(json -> kind.equals(json.at("/expectedOutcome/kind").asText())) + .toList(); + } + + /** Every case that gives a value on {@code path}, whatever must happen to it. */ + static List onPath(final String path) { + return all().stream().filter(json -> path.equals(json.get("path").asText())).toList(); + } + + private static List all() { + try (InputStream cases = OntologySqlValueCases.class.getResourceAsStream(CASES)) { + return StreamSupport.stream(JsonUtils.getObjectMapper().readTree(cases).spliterator(), false) + .toList(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java new file mode 100644 index 000000000000..03af7dcf8ad5 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementRefusalIT.java @@ -0,0 +1,517 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; +import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; + +import java.net.URI; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyAggregateStatementRequest; +import org.openmetadata.schema.api.data.OntologyExpandStatementRequest; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; + +/** + * Every way the four statement endpoints of a class refuse a request, each with its status and + * its message. A refusal about a table names the class and never the table. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyStatementRefusalIT extends BaseOntologyApprovalIT { + private static final String ORDER = "https://example.org/columnRelation#Order"; + private static final String CUSTOMER = "https://example.org/columnRelation#Customer"; + private static final String PLACED_BY = "https://example.org/columnRelation#placedBy"; + private static final String ORDER_HIDDEN = + "The identity table of class " + ORDER + " is not visible to you"; + private static final String CUSTOMER_HIDDEN = + "The identity table of class " + CUSTOMER + " is not visible to you"; + private static final String LINK_HIDDEN = + "The table that links class https://example.org/linkTable#Order to class" + + " https://example.org/linkTable#Product for relation" + + " https://example.org/linkTable#contains is not visible to you"; + private static final String CUSTOMER_UNBOUND = "Class " + CUSTOMER + " has no identity table"; + private static final String NO_JOIN = + "Relation " + + PLACED_BY + + " has no join from class " + + ORDER + + " to the identity table of class " + + CUSTOMER; + private static final String JOIN_NOT_CONFIRMED = + "The join of relation " + + PLACED_BY + + " from class " + + ORDER + + " to class " + + CUSTOMER + + " is not confirmed"; + private static final String NOT_A_WHOLE_NUMBER = + " does not parse as INT: a whole number is written in ASCII digits, with a leading minus" + + " sign when negative and no leading zeros"; + private static final String RELATION_OR_COUNT = + "An aggregate over a relation takes the relation and the direction together. A count of the" + + " class takes neither, and no related class"; + private static final String STRANGER = "https://example.org/elsewhere#Stranger"; + private static final String THING = "http://www.w3.org/2002/07/owl#Thing"; + private static final List ALONG_THE_RELATION = + List.of("expand-forward", "expand-inverse", "aggregate-forward", "aggregate-inverse"); + + @Test + void aReaderWhoMayNotViewAnIdentityTableIsRefusedByClassAndNeverByTable(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "hiddenIdentity"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var first = new RdfAccessFixtures("stmtCustomers" + ns.shortPrefix()); + var second = new RdfAccessFixtures("stmtOrders" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient seesCustomers = ownerReader(first, Entity.TABLE); + fixture.ownedBy(seesCustomers, "customers"); + final OpenMetadataClient seesOrders = ownerReader(second, Entity.TABLE); + fixture.ownedBy(seesOrders, "orders"); + + for (final String start : List.of("find", "open", "count")) { + assertRefused(403, ORDER_HIDDEN, () -> ask(fixture, seesCustomers, start)); + } + for (final String relation : ALONG_THE_RELATION) { + assertRefused(403, ORDER_HIDDEN, () -> ask(fixture, seesCustomers, relation)); + assertRefused(403, CUSTOMER_HIDDEN, () -> ask(fixture, seesOrders, relation)); + } + assertEquals(OntologyStatementKind.FIND, ask(fixture, seesOrders, "find").getStatement()); + } + } + + @Test + void aReaderWhoMayNotViewTheLinkTableOfARelationIsRefusedWithoutItBeingNamed( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "hiddenLink"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, LINK_TABLE); + var access = new RdfAccessFixtures("stmtLink" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient reader = ownerReader(access, Entity.TABLE); + fixture.ownedBy(reader, "orders", "products"); + + for (final String relation : ALONG_THE_RELATION) { + assertRefused(403, LINK_HIDDEN, () -> ask(fixture, reader, relation)); + } + assertEquals( + List.of(fixture.table("orders").getFullyQualifiedName()), + ask(fixture, reader, "open").getTables()); + } + } + + @Test + void aClassWithoutAnIdentityTableGivesNoStatement(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "noIdentity"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + final List ofCustomer = + List.of( + new Ask( + "find", + OntologyStatementKind.FIND, + "Customer", + null, + null, + null, + null, + null, + null), + new Ask( + "open", + OntologyStatementKind.OPEN, + "Customer", + null, + List.of(1), + null, + null, + null, + null), + new Ask( + "count", + OntologyStatementKind.AGGREGATE, + "Customer", + null, + null, + null, + null, + null, + null)); + + ofCustomer.forEach( + ask -> assertRefused(409, CUSTOMER_UNBOUND, () -> fixture.ask(admin(), ask, DRAFT))); + fixture.bind( + new BindingSpec( + "Customer", + "customers", + null, + List.of(), + null, + List.of(new ColumnBindingSpec("customerName", "name", null)))); + ofCustomer.forEach( + ask -> assertRefused(409, CUSTOMER_UNBOUND, () -> fixture.ask(admin(), ask, DRAFT))); + fixture.bind(COLUMN_RELATION.binding("Order", "orders")); + for (final String relation : ALONG_THE_RELATION) { + assertRefused(409, CUSTOMER_UNBOUND, () -> ask(fixture, admin(), relation, DRAFT)); + } + } + } + + @Test + void aRelationIsFollowedOnlyOverAConfirmedJoin(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "joins"); + final BindingSpec orders = COLUMN_RELATION.binding("Order", "orders"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bind(COLUMN_RELATION.binding("Customer", "customers")); + + fixture.bind(withColumns(orders, List.of(orders.columns().getFirst()))); + for (final String relation : ALONG_THE_RELATION) { + assertRefused(409, NO_JOIN, () -> ask(fixture, admin(), relation, DRAFT)); + } + fixture.bind( + withColumns( + orders, + List.of( + orders.columns().getFirst(), + new ColumnBindingSpec( + "placedBy", + "customer_id", + new JoinSpec( + "customers", + OntologyJoinStatus.INFERRED, + List.of("customer_id"), + List.of("id")))))); + for (final String relation : ALONG_THE_RELATION) { + assertRefused(409, JOIN_NOT_CONFIRMED, () -> ask(fixture, admin(), relation, DRAFT)); + } + fixture.bind(orders); + for (final String relation : ALONG_THE_RELATION) { + final Ask asked = COLUMN_RELATION.ask(relation); + assertEquals(asked.kind(), fixture.ask(admin(), asked, DRAFT).getStatement()); + } + } + } + + @Test + void aDraftReadTakesEditRightsAndAReleaseReadTakesAnActiveRelease(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "versionRights"); + try (OntologyShapeFixture fixture = + new OntologyShapeFixture(ns, ontology, UNFILTERED_IDENTITY); + var access = new RdfAccessFixtures("stmtDraft" + ns.shortPrefix())) { + fixture.bindAll(); + final OpenMetadataClient consumer = client(access.userToken("consumer", List.of())); + final String name = readerReference(consumer).getName(); + + assertRefused( + 404, + "Ontology " + ontology.getFullyQualifiedName() + " has no active release", + () -> ask(fixture, admin(), "find")); + for (final Ask asked : UNFILTERED_IDENTITY.asks()) { + assertRefused( + 403, + "Principal: CatalogPrincipal{name='" + name + "'} operations [EditAll] not allowed", + () -> fixture.ask(consumer, asked, DRAFT)); + } + activate(ns, ontology); + + assertEquals( + OntologyStatementVersion.RELEASE, ask(fixture, consumer, "find").getVersion().getKind()); + assertEquals(DRAFT, ask(fixture, admin(), "find", DRAFT).getVersion().getKind()); + } + } + + @Test + void aReaderWhoMayNotViewTheClassIsRefusedOnEveryStatement(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "hiddenClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var access = new RdfAccessFixtures("stmtClass" + ns.shortPrefix())) { + fixture.bindAll(); + final var denied = access.denyRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CONCEPT); + final OpenMetadataClient reader = client(access.userToken("reader", List.of(denied.getId()))); + final String refusal = + "Principal: CatalogPrincipal{name='" + + readerReference(reader).getName() + + "'} operation ViewBasic denied"; + + for (final Ask asked : COLUMN_RELATION.asks()) { + final OpenMetadataException refused = + assertThrows(OpenMetadataException.class, () -> fixture.ask(reader, asked, null)); + assertEquals(403, refused.getStatusCode(), asked.name()); + assertTrue(refused.getMessage().startsWith(refusal), refused.getMessage()); + } + } + } + + @Test + void aKeyThatDoesNotFitTheSubjectKeyIsRefusedByColumnAndType(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "keys"); + final Ask open = COMPOSITE_KEY.ask("open"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COMPOSITE_KEY)) { + fixture.bindAll(); + + assertRefused( + 400, + "The key has 2 columns but the request gives 1 value", + () -> fixture.ask(admin(), withKey(open, List.of("eu")), DRAFT)); + assertRefused( + 400, + "The key has 2 columns but the request gives 0 values", + () -> fixture.ask(admin(), withKey(open, List.of()), DRAFT)); + assertRefused( + 400, + "The value for column customer_id" + NOT_A_WHOLE_NUMBER, + () -> fixture.ask(admin(), withKey(open, List.of("eu", "forty-two")), DRAFT)); + assertRefused( + 400, + "The value for column customer_id is null", + () -> fixture.ask(admin(), withKey(open, Arrays.asList("eu", null)), DRAFT)); + assertEquals(OntologyStatementKind.OPEN, fixture.ask(admin(), open, DRAFT).getStatement()); + } + } + + @Test + void aRelationRequestNamesAnObjectPropertyItsDirectionAndAKeyThatFits(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "relationRequests"); + final Ask forward = COLUMN_RELATION.ask("expand-forward"); + final Ask top = COLUMN_RELATION.ask("aggregate-forward"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + + assertRefused( + 400, + "The value for column id" + NOT_A_WHOLE_NUMBER, + () -> fixture.ask(admin(), withKey(forward, List.of("thirty-one")), DRAFT)); + assertRefused( + 400, + "Relation https://example.org/columnRelation#orderTotal is not an object property of" + + " the ontology of class " + + ORDER, + () -> fixture.ask(admin(), along(forward, "orderTotal", forward.direction()), DRAFT)); + assertRefused( + 400, RELATION_OR_COUNT, () -> fixture.ask(admin(), along(top, "placedBy", null), DRAFT)); + assertRefused( + 400, + RELATION_OR_COUNT, + () -> fixture.ask(admin(), along(top, null, OntologyStatementDirection.FORWARD), DRAFT)); + } + } + + @Test + void aRequestNamesTheRelatedClassWhenTheRelationDoesNotNameOne(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "relatedClass"); + final Ontology elsewhere = createOntology(ns, "elsewhere"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + final UUID order = fixture.type("Order").getId(); + final UUID customer = fixture.type("Customer").getId(); + final UUID stranger = declareClass(elsewhere, "Stranger", URI.create(STRANGER)).getId(); + final OntologyProperty placedBy = fixture.property("placedBy"); + final String toTheCustomer = fixture.golden(COLUMN_RELATION.ask("expand-forward")); + + final OntologyStatementPlan named = expand(order, placedBy, customer); + + assertEquals(toTheCustomer, named.getSql() + "\n"); + assertEquals(URI.create(CUSTOMER), named.getRelation().getRelatedClassIri()); + assertEquals(toTheCustomer, expand(order, placedBy, null).getSql() + "\n"); + assertRefused( + 400, + "Class " + STRANGER + " is not a class of the ontology of class " + ORDER, + () -> expand(order, placedBy, stranger)); + assertRefused( + 400, + RELATION_OR_COUNT, + () -> + post( + order, + "aggregate", + new OntologyAggregateStatementRequest() + .withVersion(DRAFT) + .withRelatedClass(customer))); + + rangeOf(placedBy, URI.create(CUSTOMER), URI.create(ORDER)); + assertRefused( + 400, + "Relation " + + PLACED_BY + + " names 2 classes in its range, so the request must name the related class", + () -> expand(order, placedBy, null)); + assertEquals(toTheCustomer, expand(order, placedBy, customer).getSql() + "\n"); + + rangeOf(placedBy, URI.create(THING)); + assertRefused( + 404, + "Class " + THING + " is not a class of ontology " + ontology.getFullyQualifiedName(), + () -> expand(order, placedBy, null)); + assertEquals(toTheCustomer, expand(order, placedBy, customer).getSql() + "\n"); + } + } + + @Test + void anInverseRequestNamesTheRelatedClassWhenTheDomainNamesSeveral(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "relatedDomain"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + final UUID order = fixture.type("Order").getId(); + final UUID customer = fixture.type("Customer").getId(); + final OntologyProperty placedBy = fixture.property("placedBy"); + final String toTheOrders = fixture.golden(COLUMN_RELATION.ask("expand-inverse")); + + assertEquals(toTheOrders, expandBack(customer, placedBy, null).getSql() + "\n"); + final String id = placedBy.getId().toString(); + admin() + .ontologyProperties() + .update( + id, + admin() + .ontologyProperties() + .get(id) + .withDomain(List.of(URI.create(ORDER), URI.create(CUSTOMER)))); + + assertRefused( + 400, + "Relation " + + PLACED_BY + + " names 2 classes in its domain, so the request must name the related class", + () -> expandBack(customer, placedBy, null)); + final OntologyStatementPlan named = expandBack(customer, placedBy, order); + assertEquals(toTheOrders, named.getSql() + "\n"); + assertEquals(URI.create(ORDER), named.getRelation().getRelatedClassIri()); + } + } + + /** Asks the expand statement of order 31 with a request that can name the related class. */ + private static OntologyStatementPlan expand( + final UUID type, final OntologyProperty relation, final UUID relatedClass) { + return post( + type, + "expand", + new OntologyExpandStatementRequest() + .withVersion(DRAFT) + .withKey(List.of(31)) + .withRelation(relation.getId()) + .withDirection(OntologyStatementDirection.FORWARD) + .withRelatedClass(relatedClass)); + } + + /** Asks for the orders of customer 2, against the relation that the orders hold. */ + private static OntologyStatementPlan expandBack( + final UUID type, final OntologyProperty relation, final UUID relatedClass) { + return post( + type, + "expand", + new OntologyExpandStatementRequest() + .withVersion(DRAFT) + .withKey(List.of(2)) + .withRelation(relation.getId()) + .withDirection(OntologyStatementDirection.INVERSE) + .withRelatedClass(relatedClass)); + } + + private static OntologyStatementPlan post( + final UUID type, final String statement, final Object request) { + return admin() + .getHttpClient() + .execute( + HttpMethod.POST, + "/v1/ontologyConcepts/" + type + "/statements/" + statement, + request, + OntologyStatementPlan.class); + } + + /** Makes the relation name these classes as its range in the working draft. */ + private static void rangeOf(final OntologyProperty relation, final URI... classes) { + final String id = relation.getId().toString(); + admin() + .ontologyProperties() + .update(id, admin().ontologyProperties().get(id).withRange(List.of(classes))); + } + + private static OntologyStatementPlan ask( + final OntologyShapeFixture fixture, final OpenMetadataClient client, final String name) { + return ask(fixture, client, name, null); + } + + /** Asks the statement that the shape of the fixture lists under {@code name}. */ + private static OntologyStatementPlan ask( + final OntologyShapeFixture fixture, + final OpenMetadataClient client, + final String name, + final OntologyStatementVersion version) { + return fixture.ask(client, fixture.shape().ask(name), version); + } + + private static Ask withKey(final Ask ask, final List key) { + return new Ask( + ask.name(), + ask.kind(), + ask.type(), + ask.matchText(), + key, + ask.relation(), + ask.direction(), + ask.columns(), + ask.rows()); + } + + private static Ask along( + final Ask ask, final String relation, final OntologyStatementDirection direction) { + return new Ask( + ask.name(), + ask.kind(), + ask.type(), + ask.matchText(), + ask.key(), + relation, + direction, + ask.columns(), + ask.rows()); + } + + private static BindingSpec withColumns( + final BindingSpec binding, final List columns) { + return new BindingSpec( + binding.type(), binding.table(), binding.role(), binding.key(), binding.filter(), columns); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementReleaseDeleteIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementReleaseDeleteIT.java new file mode 100644 index 000000000000..3e4f5a856caa --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementReleaseDeleteIT.java @@ -0,0 +1,423 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyBindingFixtures.assertRefused; +import static org.openmetadata.it.tests.OntologyBindingFixtures.client; +import static org.openmetadata.it.tests.OntologyBindingFixtures.ownerReader; +import static org.openmetadata.it.tests.OntologyBindingFixtures.readerReference; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.schema.api.data.OntologyStatementVersion.DRAFT; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.columnPlan; + +import java.net.URI; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyExpandStatementRequest; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; + +/** + * A statement that reads the active release answers as it was released, whatever is deleted from + * the working draft afterwards. The release holds the class, the relation, the related class and + * the properties, so a plain delete in the draft changes the release answer in no way, and the + * same request on the draft still answers from the draft. + */ +@ExtendWith(TestNamespaceExtension.class) +class OntologyStatementReleaseDeleteIT extends BaseOntologyApprovalIT { + private static final String ORDER = "https://example.org/columnRelation#Order"; + private static final String CUSTOMER = "https://example.org/columnRelation#Customer"; + private static final String LATE = "https://example.org/columnRelation#Late"; + private static final Ask MATCH_CUSTOMERS = + new Ask( + "find-match", + OntologyStatementKind.FIND, + "Customer", + "ada", + null, + null, + null, + null, + null); + private static final String ORDER_TOTAL = "1 property Order orderTotal"; + private static final String CUSTOMER_NAME = "2 displayName Customer customerName"; + + @Test + void aClassDeletedFromTheDraftIsStillReadOnTheRelease(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final Map before = everyAnswer(fixture, admin()); + + deleteClass(fixture, "Order", false); + + assertEquals(before, everyAnswer(fixture, admin())); + assertEquals(404, draftStatus(fixture, COLUMN_RELATION.ask("find"))); + assertEquals(404, draftStatus(fixture, COLUMN_RELATION.ask("expand-forward"))); + } + } + + @Test + void aRelationDeletedFromTheDraftIsStillFollowedOnTheRelease(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedRelation"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final Map before = everyAnswer(fixture, admin()); + + admin().ontologyProperties().delete(fixture.property("placedBy").getId().toString()); + + assertEquals(before, everyAnswer(fixture, admin())); + assertEquals(404, draftStatus(fixture, COLUMN_RELATION.ask("expand-forward"))); + assertEquals(404, draftStatus(fixture, COLUMN_RELATION.ask("aggregate-forward"))); + assertEquals( + List.of("0 key Order part 0", ORDER_TOTAL), + columnPlan(fixture.ask(admin(), COLUMN_RELATION.ask("open"), DRAFT).getColumns())); + } + } + + @Test + void aRelatedClassDeletedFromTheDraftIsStillReachedWithAndWithoutItBeingNamed( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedRelated"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final UUID order = fixture.type("Order").getId(); + final UUID customer = fixture.type("Customer").getId(); + final OntologyProperty placedBy = fixture.property("placedBy"); + final Map before = everyAnswer(fixture, admin()); + final String named = expandForward(order, placedBy, customer); + assertEquals(before.get("expand-forward"), named); + + deleteClass(fixture, "Customer", false); + + assertEquals(before, everyAnswer(fixture, admin())); + assertEquals(named, expandForward(order, placedBy, customer)); + assertEquals(named, expandForward(order, placedBy, null)); + assertEquals(404, draftStatus(fixture, COLUMN_RELATION.ask("expand-forward"))); + } + } + + @Test + void aDataPropertyDeletedFromTheDraftStaysInTheReleasePlan(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedProperty"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final Map before = everyAnswer(fixture, admin()); + + admin().ontologyProperties().delete(fixture.property("orderTotal").getId().toString()); + + assertEquals(before, everyAnswer(fixture, admin())); + assertEquals( + List.of("0 key Order part 0", ORDER_TOTAL), + columnPlan(fixture.ask(admin(), COLUMN_RELATION.ask("open"), null).getColumns())); + assertEquals( + List.of("0 key Order part 0"), + columnPlan(fixture.ask(admin(), COLUMN_RELATION.ask("open"), DRAFT).getColumns())); + } + } + + @Test + void theDisplayNameDeletedFromTheDraftStaysInTheReleaseAndMatchTextIsStillAccepted( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedDisplayName"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final Map before = everyAnswer(fixture, admin()); + assertTrue(before.get("find-match").contains("LIKE"), before.get("find-match")); + + admin().ontologyProperties().delete(fixture.property("customerName").getId().toString()); + + assertEquals(before, everyAnswer(fixture, admin())); + assertEquals( + List.of("0 key Order part 0", "1 key Customer part 0", CUSTOMER_NAME), + columnPlan( + fixture.ask(admin(), COLUMN_RELATION.ask("expand-forward"), null).getColumns())); + assertRefused( + 409, + "Class " + + CUSTOMER + + " binds no display name column on its identity table, so it takes no match text", + () -> fixture.ask(admin(), MATCH_CUSTOMERS, DRAFT)); + } + } + + @Test + void aReaderWithoutEditRightsReadsTheReleaseAndIsRefusedTheDraft(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedForReader"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var access = new RdfAccessFixtures("stmtDelRead" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient consumer = client(access.userToken("consumer", List.of())); + final String name = readerReference(consumer).getName(); + final Map before = everyAnswer(fixture, consumer); + + deleteClass(fixture, "Order", false); + admin().ontologyProperties().delete(fixture.property("placedBy").getId().toString()); + + assertEquals(before, everyAnswer(fixture, consumer)); + // The draft of a class that is still there is refused before anything else is read. + assertRefused( + 403, + "Principal: CatalogPrincipal{name='" + name + "'} operations [EditAll] not allowed", + () -> fixture.ask(consumer, MATCH_CUSTOMERS, DRAFT)); + } + } + + @Test + void aReaderWithoutViewBasicOnTheDeletedClassIsRefusedAsForALiveOne(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedHiddenClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var access = new RdfAccessFixtures("stmtDelClass" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final var denied = access.denyRole(MetadataOperation.VIEW_BASIC, Entity.ONTOLOGY_CONCEPT); + final OpenMetadataClient reader = client(access.userToken("reader", List.of(denied.getId()))); + final String refusal = + "Principal: CatalogPrincipal{name='" + + readerReference(reader).getName() + + "'} operation ViewBasic denied"; + final Map live = refusals(fixture, reader); + + deleteClass(fixture, "Order", false); + deleteClass(fixture, "Customer", false); + + assertEquals(live, refusals(fixture, reader)); + live.values().forEach(message -> assertTrue(message.startsWith(refusal), message)); + assertEquals(COLUMN_RELATION.asks().size(), live.size()); + } + } + + @Test + void aReaderWithoutViewBasicOnADeletedPropertyGetsThePlanWithoutIt(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedHiddenProperty"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var access = new RdfAccessFixtures("stmtDelProp" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient reader = ownerReader(access, Entity.ONTOLOGY_PROPERTY); + owns(reader, fixture.property("placedBy")); + owns(reader, fixture.property("customerName")); + final Ask open = COLUMN_RELATION.ask("open"); + final Ask expand = COLUMN_RELATION.ask("expand-forward"); + assertEquals( + List.of("0 key Order part 0"), columnPlan(fixture.ask(reader, open, null).getColumns())); + final String expandAnswer = fixture.answer(reader, expand, null); + + admin().ontologyProperties().delete(fixture.property("orderTotal").getId().toString()); + + assertEquals( + List.of("0 key Order part 0"), columnPlan(fixture.ask(reader, open, null).getColumns())); + assertEquals(expandAnswer, fixture.answer(reader, expand, null)); + assertEquals( + List.of("0 key Order part 0", ORDER_TOTAL), + columnPlan(fixture.ask(admin(), open, null).getColumns())); + } + } + + @Test + void aReaderWithoutViewBasicOnTheRelationIsRefusedByEveryStatementAlongIt( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "deletedHiddenRelation"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION); + var access = new RdfAccessFixtures("stmtDelRel" + ns.shortPrefix())) { + fixture.bindAll(); + activate(ns, ontology); + final OpenMetadataClient reader = ownerReader(access, Entity.ONTOLOGY_PROPERTY); + owns(reader, fixture.property("orderTotal")); + owns(reader, fixture.property("customerName")); + final String refusal = + "Principal: CatalogPrincipal{name='" + + readerReference(reader).getName() + + "'} operation ViewBasic denied"; + final String openAnswer = fixture.answer(reader, COLUMN_RELATION.ask("open"), null); + final Map live = alongTheRelation(fixture, reader); + + admin().ontologyProperties().delete(fixture.property("placedBy").getId().toString()); + + assertEquals(live, alongTheRelation(fixture, reader)); + assertEquals(4, live.size()); + live.values().forEach(message -> assertTrue(message.startsWith(refusal), message)); + assertEquals(openAnswer, fixture.answer(reader, COLUMN_RELATION.ask("open"), null)); + } + } + + @Test + void aClassDeletedForGoodLeavesNoRowToFindItsOntologyAndNoBindings(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "hardDeleted"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final UUID order = fixture.type("Order").getId(); + final UUID customer = fixture.type("Customer").getId(); + final OntologyProperty placedBy = fixture.property("placedBy"); + + deleteClass(fixture, "Customer", true); + + assertRefused( + 409, + "Class " + CUSTOMER + " has no identity table", + () -> expandForward(order, placedBy, customer)); + assertRefused( + 404, + "Class " + CUSTOMER + " is not a class of ontology " + ontology.getFullyQualifiedName(), + () -> expandForward(order, placedBy, null)); + assertRefused( + 404, + "ontologyConcept instance for " + customer + " not found", + () -> fixture.ask(admin(), COLUMN_RELATION.ask("expand-inverse"), null)); + } + } + + @Test + void aClassWhoseWorkingRowIsLiveButTheReleaseLacksIsNotInTheRelease(final TestNamespace ns) { + final Ontology ontology = createOntology(ns, "lateClass"); + try (OntologyShapeFixture fixture = new OntologyShapeFixture(ns, ontology, COLUMN_RELATION)) { + fixture.bindAll(); + activate(ns, ontology); + final UUID late = declareClass(ontology, "Late", URI.create(LATE)).getId(); + + assertRefused( + 404, + "Class " + + LATE + + " is not in the active release of ontology " + + ontology.getFullyQualifiedName(), + () -> postFind(late)); + } + } + + /** + * Deletes the class from the draft. A class that a property still names in its domain or range + * cannot be deleted, so the properties that name it go first and the class goes last. + */ + private static void deleteClass( + final OntologyShapeFixture fixture, final String name, final boolean hard) { + final URI iri = fixture.type(name).getIri(); + for (final String property : List.of("orderTotal", "customerName", "placedBy")) { + final OntologyProperty held = fixture.property(property); + final boolean names = held.getDomain().contains(iri) || held.getRange().contains(iri); + final var current = admin().ontologyProperties().get(held.getId().toString(), null, "all"); + if (names && !Boolean.TRUE.equals(current.getDeleted())) { + admin().ontologyProperties().delete(held.getId().toString()); + } + } + admin() + .ontologyConcepts() + .delete( + fixture.type(name).getId().toString(), Map.of("hardDelete", Boolean.toString(hard))); + } + + private static Map everyAnswer( + final OntologyShapeFixture fixture, final OpenMetadataClient client) { + final Map answers = new LinkedHashMap<>(); + for (final Ask asked : COLUMN_RELATION.asks()) { + answers.put(asked.name(), fixture.answer(client, asked, null)); + } + answers.put(MATCH_CUSTOMERS.name(), fixture.answer(client, MATCH_CUSTOMERS, null)); + return answers; + } + + private static Map refusals( + final OntologyShapeFixture fixture, final OpenMetadataClient client) { + final Map refused = new LinkedHashMap<>(); + for (final Ask asked : COLUMN_RELATION.asks()) { + refused.put(asked.name(), refusal(() -> fixture.ask(client, asked, null))); + } + return refused; + } + + private static Map alongTheRelation( + final OntologyShapeFixture fixture, final OpenMetadataClient client) { + final Map refused = new LinkedHashMap<>(); + for (final String name : + List.of("expand-forward", "expand-inverse", "aggregate-forward", "aggregate-inverse")) { + refused.put(name, refusal(() -> fixture.ask(client, COLUMN_RELATION.ask(name), null))); + } + return refused; + } + + private static String refusal(final Runnable request) { + final OpenMetadataException refused = assertThrows(OpenMetadataException.class, request::run); + assertEquals(403, refused.getStatusCode()); + return refused.getMessage(); + } + + private static int draftStatus(final OntologyShapeFixture fixture, final Ask asked) { + return assertThrows(OpenMetadataException.class, () -> fixture.ask(admin(), asked, DRAFT)) + .getStatusCode(); + } + + private static void owns(final OpenMetadataClient reader, final OntologyProperty property) { + final String id = property.getId().toString(); + admin() + .ontologyProperties() + .update( + id, + admin() + .ontologyProperties() + .get(id, "owners") + .withOwners(List.of(readerReference(reader)))); + } + + /** The body of the expand statement of order 31 on the release, as the server wrote it. */ + private static String expandForward( + final UUID type, final OntologyProperty relation, final UUID relatedClass) { + return admin() + .getHttpClient() + .executeForString( + HttpMethod.POST, + "/v1/ontologyConcepts/" + type + "/statements/expand", + new OntologyExpandStatementRequest() + .withKey(List.of(31)) + .withRelation(relation.getId()) + .withDirection(OntologyStatementDirection.FORWARD) + .withRelatedClass(relatedClass)); + } + + private static OntologyStatementPlan postFind(final UUID type) { + return admin() + .getHttpClient() + .execute( + HttpMethod.POST, + "/v1/ontologyConcepts/" + type + "/statements/find", + new org.openmetadata.schema.api.data.OntologyFindStatementRequest(), + OntologyStatementPlan.class); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementValueIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementValueIT.java new file mode 100644 index 000000000000..29f62ee2adba --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyStatementValueIT.java @@ -0,0 +1,378 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.it.factories.DatabaseSchemaTestFactory; +import org.openmetadata.it.factories.DatabaseTestFactory; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.schema.api.data.CreateOntologyProperty; +import org.openmetadata.schema.api.data.OntologyFindStatementRequest; +import org.openmetadata.schema.api.data.OntologyOpenStatementRequest; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.api.services.CreateDatabaseService; +import org.openmetadata.schema.api.services.CreateDatabaseService.DatabaseServiceType; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.services.DatabaseService; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyAssetBinding; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * Sends every key and every search text of the value cases file through the statement endpoints. + * A key goes to {@code open} and a search text goes to {@code find}, each on a class whose + * identity table sits in a service of the engine family that the case is written for. The text + * that a case expects must be the text in {@code escapedSql}, and a value that a case refuses + * must be a 400 on every family. + * + *

One key case has the outcome {@code bound}. It gives values that a later statement reads + * from an earlier result and binds as parameters. A plan holds its values in its text and has no + * parameters, so no endpoint takes that case. + */ +class OntologyStatementValueIT { + private static final TestNamespace NAMESPACE = new TestNamespace("OntologyStatementValueIT"); + private static final URI XSD_STRING = URI.create("http://www.w3.org/2001/XMLSchema#string"); + private static final String KEY = "keyValue"; + private static final String SEARCH = "searchText"; + private static final String RENDERED = "rendered"; + private static final String REFUSED = "refusedAtRequest"; + private static final String ANY_FAMILY = "any"; + private static final String TSQL = "tsql"; + private static final Column SEARCHED = column("name", ColumnDataType.VARCHAR); + + /** + * One subject key that the cases give values for. + * + * @param searched the column that holds the display name, or null when the class has none + */ + private record KeyTable(String table, List key, Column searched) { + Column[] columns() { + return Stream.concat(key.stream(), Stream.ofNullable(searched)).toArray(Column[]::new); + } + + String signature() { + return OntologyStatementValueIT.signature(key); + } + } + + private static final List KEY_TABLES = + List.of( + new KeyTable( + "customers_by_number", + List.of(column("customer_no", ColumnDataType.VARCHAR)), + SEARCHED), + new KeyTable( + "customers_by_tenant", + List.of( + column("tenant_id", ColumnDataType.VARCHAR), + column("customer_id", ColumnDataType.INT)), + null), + new KeyTable("customers_by_id", List.of(column("customer_id", ColumnDataType.INT)), null), + new KeyTable( + "customers_by_day", List.of(column("created_on", ColumnDataType.DATE)), null)); + + /** The class of each engine family that each key identifies, by family and key signature. */ + private static final Map CLASSES = new ConcurrentHashMap<>(); + + @BeforeAll + static void bindAClassForEveryKeyInAServiceOfEveryFamily() { + final Ontology ontology = BaseOntologyApprovalIT.createOntology(NAMESPACE, "statementValues"); + firstServiceTypes().forEach((family, serviceType) -> bind(ontology, family, serviceType)); + } + + @AfterAll + static void deleteWhatTheClassCreated() { + BaseOntologyIT.deleteRoots(NAMESPACE); + } + + static Stream renderedKeys() { + return cases(KEY, RENDERED).map(json -> Arguments.of(json.get("id").asText(), json)); + } + + static Stream renderedSearches() { + return cases(SEARCH, RENDERED).map(json -> Arguments.of(json.get("id").asText(), json)); + } + + /** Every refused key and search text, once for each engine family. */ + static Stream refusedOnEveryFamily() { + final List families = List.copyOf(firstServiceTypes().keySet()); + return Stream.concat(cases(KEY, REFUSED), cases(SEARCH, REFUSED)) + .flatMap( + json -> + families.stream() + .map(family -> Arguments.of(json.get("id").asText(), family, json))); + } + + @Test + void everyKeyAndSearchCaseIsSentToAnEndpointOrIsTheOneBoundCase() { + final Map outcomes = + Stream.concat( + OntologySqlValueCases.onPath(KEY).stream(), + OntologySqlValueCases.onPath(SEARCH).stream()) + .collect( + Collectors.groupingBy( + json -> + json.get("path").asText() + " " + json.at("/expectedOutcome/kind").asText(), + Collectors.counting())); + + assertEquals( + Map.of( + "keyValue rendered", 45L, + "keyValue refusedAtRequest", 7L, + "keyValue bound", 1L, + "searchText rendered", 81L, + "searchText refusedAtRequest", 2L), + outcomes); + assertEquals(9, firstServiceTypes().size()); + assertEquals( + List.of(ANY_FAMILY), + Stream.concat(cases(KEY, REFUSED), cases(SEARCH, REFUSED)) + .map(json -> json.get("engineFamily").asText()) + .distinct() + .toList()); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("renderedKeys") + void aKeyReachesTheEscapedStatementAsItsCaseWritesIt(final String id, final JsonNode json) { + final String family = json.get("engineFamily").asText(); + final List key = keyOf(json); + final String[] parts = json.at("/expectedOutcome/text").asText().split(" \\| ", key.size()); + + final OntologyStatementPlan plan = open(typeOf(family, json), key); + + final List where = whereLines(plan.getEscapedSql()); + for (int part = 0; part < parts.length; part++) { + assertTrue(where.get(part).endsWith(" = " + parts[part]), plan::getEscapedSql); + } + assertEquals(limitLines(family, "LIMIT 101"), where.subList(parts.length, where.size())); + assertEquals(family, plan.getFamily().value()); + assertEquals(plan.getEscapedSql().replace("\\:", ":"), plan.getSql()); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("renderedSearches") + void aSearchTextReachesTheEscapedStatementAsItsCaseWritesIt( + final String id, final JsonNode json) { + final String family = json.get("engineFamily").asText(); + final String text = json.at("/expectedOutcome/text").asText(); + + final OntologyStatementPlan plan = find(typeOf(family, json), json.get("input").asText()); + + final List where = whereLines(plan.getEscapedSql()); + assertTrue(where.get(0).endsWith(" IS NOT NULL"), plan::getEscapedSql); + assertTrue(where.get(1).endsWith(" LIKE " + text), plan::getEscapedSql); + assertEquals(limitLines(family, "LIMIT 25"), where.subList(2, where.size())); + assertEquals(family, plan.getFamily().value()); + assertEquals(plan.getEscapedSql().replace("\\:", ":"), plan.getSql()); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("refusedOnEveryFamily") + void aValueThatItsCaseRefusesIsRefusedOnEveryFamily( + final String id, final String family, final JsonNode json) { + final OntologyConcept type = typeOf(family, json); + + final OpenMetadataException refused = + assertThrows( + OpenMetadataException.class, + () -> { + if (KEY.equals(json.get("path").asText())) { + open(type, keyOf(json)); + } else { + find(type, json.get("input").asText()); + } + }); + + assertEquals(json.at("/expectedOutcome/status").asInt(), refused.getStatusCode()); + for (final JsonNode words : json.at("/expectedOutcome/messageContains")) { + assertTrue(refused.getMessage().contains(words.asText()), refused::getMessage); + } + } + + private static Stream cases(final String path, final String outcome) { + return OntologySqlValueCases.onPath(path).stream() + .filter(json -> outcome.equals(json.at("/expectedOutcome/kind").asText())); + } + + /** The first service type that the cases list for each engine family, in the order of the file. */ + private static Map firstServiceTypes() { + final Map first = new LinkedHashMap<>(); + Stream.concat(cases(KEY, RENDERED), cases(SEARCH, RENDERED)) + .forEach( + json -> + first.putIfAbsent( + json.get("engineFamily").asText(), json.at("/serviceTypes/0").asText())); + return first; + } + + private static void bind(final Ontology ontology, final String family, final String serviceType) { + final DatabaseService service = + NAMESPACE.trackRoot( + Entity.DATABASE_SERVICE, + admin() + .databaseServices() + .create( + new CreateDatabaseService() + .withName(NAMESPACE.prefix(family)) + .withServiceType(DatabaseServiceType.fromValue(serviceType)))); + final DatabaseSchema schema = + DatabaseSchemaTestFactory.create( + DatabaseTestFactory.create(NAMESPACE, service.getFullyQualifiedName()) + .getFullyQualifiedName(), + "sales"); + KEY_TABLES.forEach(keyed -> bind(ontology, family, schema, keyed)); + } + + private static void bind( + final Ontology ontology, + final String family, + final DatabaseSchema schema, + final KeyTable keyed) { + final String name = family + "_" + keyed.table(); + final OntologyConcept type = + BaseOntologyApprovalIT.declareClass( + ontology, name, URI.create("https://example.org/values#" + name)); + final Table table = OntologyMappingFixtures.table(schema, keyed.table(), keyed.columns()); + final OntologyAssetBinding identity = + binding( + table, + OntologyBindingRole.IDENTITY, + keyed.key().stream().map(Column::getName).toArray(String[]::new)); + CLASSES.put(family + " " + keyed.signature(), type); + if (keyed.searched() != null) { + identity.withColumns( + List.of(column(displayName(ontology, type), keyed.searched().getName()))); + CLASSES.put(family + " " + signature(List.of(keyed.searched())), type); + } + put(admin(), type, identity, 0L); + } + + private static OntologyProperty displayName(final Ontology ontology, final OntologyConcept type) { + return admin() + .ontologyProperties() + .create( + new CreateOntologyProperty() + .withName(type.getName() + "_name") + .withOntology(ontology.getFullyQualifiedName()) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(type.getIri())) + .withRange(List.of(XSD_STRING)) + .withIsDisplayName(true)); + } + + /** The class of the family whose key, or whose display name, is the column of the case. */ + private static OntologyConcept typeOf(final String family, final JsonNode json) { + final JsonNode column = json.get("column"); + final List names = new ArrayList<>(); + if (column.get(0).isArray()) { + column.forEach(path -> names.add(path.get(0).asText())); + } else { + names.add(column.get(0).asText()); + } + final String signature = String.join(",", names) + "|" + json.get("columnType").asText(); + return Objects.requireNonNull( + CLASSES.get(family + " " + signature), () -> "No class has the columns " + signature); + } + + private static String signature(final List columns) { + return columns.stream().map(Column::getName).collect(Collectors.joining(",")) + + "|" + + columns.stream() + .map(column -> column.getDataType().value()) + .collect(Collectors.joining(",")); + } + + /** The input of a key case is the whole key when it is a list, and its one value otherwise. */ + private static List keyOf(final JsonNode json) { + final Object input = JsonUtils.treeToValue(json.get("input"), Object.class); + return input instanceof List parts + ? new ArrayList<>(parts) + : Collections.singletonList(input); + } + + private static OntologyStatementPlan open(final OntologyConcept type, final List key) { + return statement( + type, + "open", + new OntologyOpenStatementRequest() + .withVersion(OntologyStatementVersion.DRAFT) + .withKey(key)); + } + + private static OntologyStatementPlan find(final OntologyConcept type, final String matchText) { + return statement( + type, + "find", + new OntologyFindStatementRequest() + .withVersion(OntologyStatementVersion.DRAFT) + .withMatchText(matchText)); + } + + private static OntologyStatementPlan statement( + final OntologyConcept type, final String kind, final Object request) { + return admin() + .getHttpClient() + .execute( + HttpMethod.POST, + "/v1/ontologyConcepts/" + type.getId() + "/statements/" + kind, + request, + OntologyStatementPlan.class); + } + + /** The lines of a statement from its {@code WHERE} on. */ + private static List whereLines(final String sql) { + return sql.substring(sql.indexOf("\nWHERE ") + 1).lines().toList(); + } + + /** T-SQL writes its row limit after {@code SELECT}, so nothing follows its last condition. */ + private static List limitLines(final String family, final String limit) { + return TSQL.equals(family) ? List.of() : List.of(limit); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java new file mode 100644 index 000000000000..8bfee138c1b0 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OntologyTableMappingsIT.java @@ -0,0 +1,686 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.binding; +import static org.openmetadata.it.tests.OntologyMappingFixtures.bindings; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.dataProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.filter; +import static org.openmetadata.it.tests.OntologyMappingFixtures.join; +import static org.openmetadata.it.tests.OntologyMappingFixtures.objectProperty; +import static org.openmetadata.it.tests.OntologyMappingFixtures.put; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import jakarta.ws.rs.ClientErrorException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; +import org.jdbi.v3.core.Jdbi; +import org.jdbi.v3.core.statement.SqlLogger; +import org.jdbi.v3.core.statement.StatementContext; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.SqlQueryCounter; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyTableMapping; +import org.openmetadata.service.ontology.OntologyTableMapping.ClassMapping; +import org.openmetadata.service.ontology.OntologyTableMapping.TableBinding; +import org.openmetadata.service.ontology.OntologyTableMappings; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.auth.CatalogSecurityContext; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; +import org.slf4j.LoggerFactory; + +/** + * The table mapping of a whole version of an ontology, read in the server as three callers read it: + * an administrator, a reader who may not view some of the tables, classes or properties, and a + * person who may not read the working draft. It also counts the statements of a read of 300 classes + * with 600 bindings, and changes a binding while the read is in flight. + */ +@Isolated("Counts SQL statements and writes bindings in the middle of a read") +@ExtendWith(TestNamespaceExtension.class) +class OntologyTableMappingsIT extends BaseOntologyApprovalIT { + private static final URI CUSTOMER = URI.create("urn:Customer"); + private static final URI ORDER = URI.create("urn:Order"); + private static final URI PRODUCT = URI.create("urn:Product"); + private static final String NOT_THE_OWNER = "!isOwner()"; + private static final String EVERY_RESOURCE = "All"; + private static final int CLASSES = 300; + + /** Three classes and a relation: Customer with a contributing table, Order, and Product. */ + private record Scene( + Ontology ontology, + OntologyConcept customer, + OntologyConcept order, + OntologyConcept product, + OntologyProperty name, + OntologyProperty total, + OntologyProperty placedBy, + Table customers, + Table notes, + Table orders, + Table products) {} + + private static Scene scene(final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept customer = declareClass(ontology, "Customer", CUSTOMER); + final OntologyConcept order = declareClass(ontology, "Order", ORDER); + final OntologyConcept product = declareClass(ontology, "Product", PRODUCT); + final DatabaseSchema schema = schema(ns); + final Table customers = + table( + schema, + "customers", + column("id", ColumnDataType.BIGINT), + column("name", ColumnDataType.VARCHAR)); + final Table notes = + table( + schema, + "customer_notes", + column("customer_id", ColumnDataType.BIGINT), + column("note", ColumnDataType.VARCHAR)); + final Table orders = + table( + schema, + "orders", + column("id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT), + column("total", ColumnDataType.DECIMAL)); + final Table products = + table( + schema, + "products", + column("sku", ColumnDataType.VARCHAR), + column("alias", ColumnDataType.VARCHAR)); + final OntologyProperty name = dataProperty(ontology, "name", customer); + final OntologyProperty total = dataProperty(ontology, "total", order); + final OntologyProperty placedBy = objectProperty(ontology, "placedBy", order, customer); + put( + admin(), + customer, + binding(customers, OntologyBindingRole.IDENTITY, "id") + .withColumns(List.of(column(name, "name"))), + 0L); + put(admin(), customer, binding(notes, OntologyBindingRole.CONTRIBUTING, "customer_id"), 1L); + put( + admin(), + order, + binding(orders, OntologyBindingRole.IDENTITY, "id") + .withColumns( + List.of( + column(total, "total"), + column(placedBy, "customer_id") + .withJoin( + join(customers, OntologyJoinStatus.CONFIRMED, "customer_id", "id")))), + 0L); + put(admin(), product, binding(products, OntologyBindingRole.IDENTITY, "sku"), 0L); + return new Scene( + ontology, customer, order, product, name, total, placedBy, customers, notes, orders, + products); + } + + private static OntologyTableMappings service() { + final var dao = Entity.getCollectionDAO(); + final Authorizer authorizer = Entity.getAuthorizer(); + return new OntologyTableMappings( + new OntologyConceptBindingStore(dao, OntologyConceptBindingStore.registeredAssetTables()), + dao, + authorizer, + Entity::getEntityRepository, + (context, ontologyId) -> + authorizer.authorize( + context, + new OperationContext(Entity.ONTOLOGY, MetadataOperation.EDIT_ALL), + new ResourceContext<>(Entity.ONTOLOGY, ontologyId, null))); + } + + private static Access as(final String user) { + return new Access(null, new CatalogSecurityContext(() -> user, "https", "JWT", Set.of())); + } + + private static OntologyTableMapping read( + final String user, final Ontology ontology, final OntologyStatementVersion version) { + return service().read(as(user), ontology.getId(), version); + } + + /** A caller who holds every right but one: the right to view what they do not own. */ + private static String readerWhoViewsOnlyWhatTheyOwn( + final RdfAccessFixtures fixtures, final String resource) { + final var everything = fixtures.allowRole(MetadataOperation.ALL, EVERY_RESOURCE); + final var denied = fixtures.denyRole(MetadataOperation.VIEW_BASIC, resource, NOT_THE_OWNER); + final OpenMetadataClient client = + OntologyBindingFixtures.client( + fixtures.userToken("reader", List.of(everything.getId(), denied.getId()))); + return OntologyBindingFixtures.readerReference(client).getName(); + } + + private static EntityReference user(final String name) { + return admin().users().getByName(name).getEntityReference(); + } + + private static void owns(final String reader, final Table table) { + final String id = table.getId().toString(); + admin() + .tables() + .update(id, admin().tables().get(id, "owners").withOwners(List.of(user(reader)))); + } + + private static void owns(final String reader, final OntologyConcept type) { + final String id = type.getId().toString(); + admin() + .ontologyConcepts() + .update(id, admin().ontologyConcepts().get(id, "owners").withOwners(List.of(user(reader)))); + } + + private static void owns(final String reader, final OntologyProperty property) { + final String id = property.getId().toString(); + admin() + .ontologyProperties() + .update( + id, admin().ontologyProperties().get(id, "owners").withOwners(List.of(user(reader)))); + } + + private static List iris(final OntologyTableMapping mapping) { + return mapping.classes().stream().map(type -> type.iri().toString()).toList(); + } + + private static List tableNames(final ClassMapping type) { + return type.tables().stream() + .map(bound -> bound.table().fullyQualifiedName()) + .map(fqn -> fqn.substring(fqn.lastIndexOf('.') + 1)) + .toList(); + } + + private static ClassMapping of(final OntologyTableMapping mapping, final URI iri) { + return mapping.classes().stream() + .filter(type -> type.iri().equals(iri)) + .findFirst() + .orElseThrow(); + } + + @Test + void anAdministratorReadsTheWholeMappingOfTheReleaseAndOfTheDraft(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + + final OntologyTableMapping release = read("admin", scene.ontology(), null); + final OntologyTableMapping draft = + read("admin", scene.ontology(), OntologyStatementVersion.DRAFT); + + for (final OntologyTableMapping mapping : List.of(release, draft)) { + assertEquals(List.of("urn:Customer", "urn:Order", "urn:Product"), iris(mapping)); + assertEquals(List.of("customers", "customer_notes"), tableNames(of(mapping, CUSTOMER))); + assertEquals(List.of("orders"), tableNames(of(mapping, ORDER))); + assertEquals(List.of("products"), tableNames(of(mapping, PRODUCT))); + assertEquals(0, mapping.hiddenTables()); + assertEquals(0, mapping.hiddenClasses()); + assertEquals(0, mapping.hiddenProperties()); + } + assertEquals(OntologyStatementVersion.RELEASE, release.version().getKind()); + assertEquals(OntologyStatementVersion.DRAFT, draft.version().getKind()); + final TableBinding orders = of(release, ORDER).tables().getFirst(); + assertEquals(OntologyBindingRole.IDENTITY, orders.role()); + assertEquals(List.of(List.of("id")), orders.subjectKey()); + assertNull(orders.rowFilter()); + assertEquals(1, orders.dataColumns().size()); + assertEquals(List.of("total"), orders.dataColumns().getFirst().columnPath()); + assertEquals(1, orders.relationColumns().size()); + final var relation = orders.relationColumns().getFirst(); + assertEquals(scene.placedBy().getIri(), relation.relationIri()); + assertEquals(List.of("customer_id"), relation.columnPath()); + assertEquals(OntologyJoinStatus.CONFIRMED, relation.join().status()); + assertEquals(scene.customers().getId(), relation.join().targetTableId()); + assertEquals( + List.of(List.of("customer_id")), + relation.join().on().stream().map(p -> p.child()).toList()); + assertEquals( + List.of(List.of("id")), relation.join().on().stream().map(p -> p.parent()).toList()); + assertEquals( + List.of("urn:Customer"), + relation.join().objectClasses().stream().map(URI::toString).toList()); + assertEquals(List.of(), orders.absentFromVersion()); + assertEquals(List.of(), orders.missingColumns()); + } + + @Test + void aReleaseNeedsAnActiveReleaseAndAnOntologyWithNoneIs404(final TestNamespace ns) { + final Scene scene = scene(ns); + + final EntityNotFoundException none = + assertThrows(EntityNotFoundException.class, () -> read("admin", scene.ontology(), null)); + assertEquals( + "Ontology " + scene.ontology().getFullyQualifiedName() + " has no active release", + none.getMessage()); + assertEquals( + 3, read("admin", scene.ontology(), OntologyStatementVersion.DRAFT).classes().size()); + } + + @Test + void aReaderWhoMayNotViewATableReadsTheRestAndOneHiddenTable(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + try (var fixtures = new RdfAccessFixtures("mapTb" + ns.shortPrefix())) { + final String reader = readerWhoViewsOnlyWhatTheyOwn(fixtures, Entity.TABLE); + for (final Table table : List.of(scene.customers(), scene.orders(), scene.products())) { + owns(reader, table); + } + + final OntologyTableMapping seen = read(reader, scene.ontology(), null); + + assertEquals(List.of("urn:Customer", "urn:Order", "urn:Product"), iris(seen)); + assertEquals(List.of("customers"), tableNames(of(seen, CUSTOMER))); + assertEquals(List.of("orders"), tableNames(of(seen, ORDER))); + assertEquals(List.of("products"), tableNames(of(seen, PRODUCT))); + assertEquals(1, seen.hiddenTables()); + assertEquals(0, seen.hiddenClasses()); + assertEquals(0, seen.hiddenProperties()); + assertNamesNothingOf(seen, scene.notes().getId().toString(), "customer_notes"); + } + } + + @Test + void aReaderWhoMayNotViewTheJoinTargetCountsItAndSeesNoRelationColumn(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + try (var fixtures = new RdfAccessFixtures("mapJn" + ns.shortPrefix())) { + final String reader = readerWhoViewsOnlyWhatTheyOwn(fixtures, Entity.TABLE); + owns(reader, scene.orders()); + owns(reader, scene.products()); + owns(reader, scene.notes()); + + final OntologyTableMapping seen = read(reader, scene.ontology(), null); + + assertEquals(List.of(), of(seen, ORDER).tables().getFirst().relationColumns()); + assertEquals(List.of("customer_notes"), tableNames(of(seen, CUSTOMER))); + assertEquals(1, seen.hiddenTables()); + assertNamesNothingOf(seen, scene.customers().getId().toString(), "\"customers\""); + } + } + + @Test + void aReaderWhoMayNotViewAClassReadsTheOthersAndOneHiddenClass(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + try (var fixtures = new RdfAccessFixtures("mapCl" + ns.shortPrefix())) { + final String reader = readerWhoViewsOnlyWhatTheyOwn(fixtures, Entity.ONTOLOGY_CONCEPT); + owns(reader, scene.customer()); + owns(reader, scene.order()); + + final OntologyTableMapping seen = read(reader, scene.ontology(), null); + + assertEquals(List.of("urn:Customer", "urn:Order"), iris(seen)); + assertEquals(1, seen.hiddenClasses()); + assertEquals(0, seen.hiddenTables()); + assertEquals(0, seen.hiddenProperties()); + assertNamesNothingOf(seen, scene.product().getId().toString(), "Product", "products"); + } + } + + @Test + void aReaderWhoMayNotViewAPropertyReadsTheOthersAndOneHiddenProperty(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + try (var fixtures = new RdfAccessFixtures("mapPr" + ns.shortPrefix())) { + final String reader = readerWhoViewsOnlyWhatTheyOwn(fixtures, Entity.ONTOLOGY_PROPERTY); + owns(reader, scene.total()); + owns(reader, scene.placedBy()); + + final OntologyTableMapping seen = read(reader, scene.ontology(), null); + + assertEquals(List.of(), of(seen, CUSTOMER).tables().getFirst().dataColumns()); + assertEquals(1, of(seen, ORDER).tables().getFirst().dataColumns().size()); + assertEquals(1, of(seen, ORDER).tables().getFirst().relationColumns().size()); + assertEquals(1, seen.hiddenProperties()); + assertEquals(0, seen.hiddenTables()); + assertEquals(0, seen.hiddenClasses()); + assertNamesNothingOf(seen, scene.name().getId().toString(), "urn:name"); + } + } + + private static void assertNamesNothingOf( + final OntologyTableMapping mapping, final String... hidden) { + final String text = mapping.toString(); + final String json = org.openmetadata.schema.utils.JsonUtils.pojoToJson(mapping); + for (final String name : hidden) { + assertFalse(text.contains(name), name); + assertFalse(json.contains(name), name); + } + } + + @Test + void theDraftNeedsTheRightToReadTheWorkingDraftAndTheReleaseDoesNot(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + try (var fixtures = new RdfAccessFixtures("mapDr" + ns.shortPrefix())) { + final var everything = fixtures.allowRole(MetadataOperation.ALL, EVERY_RESOURCE); + final var noEdit = fixtures.denyRole(MetadataOperation.EDIT_ALL, Entity.ONTOLOGY); + final var viewer = + OntologyBindingFixtures.client( + fixtures.userToken("viewer", List.of(everything.getId(), noEdit.getId()))); + final String user = OntologyBindingFixtures.readerReference(viewer).getName(); + final var editor = + OntologyBindingFixtures.client(fixtures.userToken("editor", List.of(everything.getId()))); + final String editorName = OntologyBindingFixtures.readerReference(editor).getName(); + + assertThrows( + AuthorizationException.class, + () -> read(user, scene.ontology(), OntologyStatementVersion.DRAFT)); + assertEquals(3, read(user, scene.ontology(), null).classes().size()); + assertEquals( + 3, read(editorName, scene.ontology(), OntologyStatementVersion.DRAFT).classes().size()); + } + } + + @Test + void aReadLogsOnlyCountsAndNeverAHiddenName(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + final Logger logger = (Logger) LoggerFactory.getLogger(OntologyTableMappings.class); + final Level before = logger.getLevel(); + final ListAppender lines = new ListAppender<>(); + lines.start(); + logger.addAppender(lines); + logger.setLevel(Level.DEBUG); + try (var fixtures = new RdfAccessFixtures("mapLg" + ns.shortPrefix())) { + final String reader = readerWhoViewsOnlyWhatTheyOwn(fixtures, Entity.TABLE); + owns(reader, scene.customers()); + owns(reader, scene.orders()); + owns(reader, scene.products()); + + read(reader, scene.ontology(), null); + + assertEquals(1, lines.list.size()); + assertEquals( + "Read the table mapping of ontology " + + scene.ontology().getId() + + ": 3 classes, 1 hidden tables, 0 hidden classes, 0 hidden properties", + lines.list.getFirst().getFormattedMessage()); + } finally { + logger.detachAppender(lines); + logger.setLevel(before); + } + } + + /** Counts the table row reads of the reading thread and writes a binding after each. */ + private static final class WriteAfterBindingRows implements SqlLogger { + private final Thread reader = Thread.currentThread(); + private final AtomicInteger writes = new AtomicInteger(); + private final int most; + private final Runnable write; + + WriteAfterBindingRows(final int most, final Runnable write) { + this.most = most; + this.write = write; + } + + @Override + public void logAfterExecution(final StatementContext context) { + final String sql = context.getRenderedSql().toLowerCase(java.util.Locale.ROOT); + if (Thread.currentThread() == reader + && sql.contains("from ontology_concept_binding") + && sql.contains("bindingorder") + && writes.get() < most) { + writes.incrementAndGet(); + write.run(); + } + } + } + + private static Runnable flipProductKey(final Scene scene) { + final AtomicInteger flips = new AtomicInteger(); + return () -> { + final String key = flips.getAndIncrement() % 2 == 0 ? "alias" : "sku"; + put( + admin(), + scene.product(), + binding(scene.products(), OntologyBindingRole.IDENTITY, key), + bindings(admin(), scene.product()).getRevision()); + }; + } + + @Test + void aBindingChangedWhileTheRowsAreReadGivesTheNewMappingAndNeverAMix(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + final Jdbi jdbi = Entity.getJdbi(); + final SqlLogger previous = + jdbi.getConfig(org.jdbi.v3.core.statement.SqlStatements.class).getSqlLogger(); + final var changing = new WriteAfterBindingRows(1, flipProductKey(scene)); + jdbi.setSqlLogger(changing); + final OntologyTableMapping seen; + try { + seen = read("admin", scene.ontology(), null); + } finally { + jdbi.setSqlLogger(previous); + } + + assertEquals(1, changing.writes.get()); + assertEquals(List.of(List.of("alias")), of(seen, PRODUCT).tables().getFirst().subjectKey()); + assertEquals(List.of(List.of("id")), of(seen, ORDER).tables().getFirst().subjectKey()); + } + + /** Writes once, after the first statement of the reading thread that holds {@code fragment}. */ + private static final class WriteAfterStatement implements SqlLogger { + private final Thread reader = Thread.currentThread(); + private final AtomicInteger writes = new AtomicInteger(); + private final String fragment; + private final Runnable write; + + WriteAfterStatement(final String fragment, final Runnable write) { + this.fragment = fragment; + this.write = write; + } + + @Override + public void logAfterExecution(final StatementContext context) { + final String sql = context.getRenderedSql().toLowerCase(java.util.Locale.ROOT); + if (Thread.currentThread() == reader + && sql.contains(fragment) + && writes.getAndIncrement() == 0) { + write.run(); + } + } + } + + @Test + void aClassBoundForTheFirstTimeWhileTheDraftIsReadGivesBothClassesWithTheirNewKeysNeverAMix( + final TestNamespace ns) { + final Ontology ontology = createOntology(ns); + final OntologyConcept bound = declareClass(ontology, "Bound", URI.create("urn:Bound")); + final OntologyConcept later = declareClass(ontology, "Later", URI.create("urn:Later")); + final DatabaseSchema schema = schema(ns); + final Table boundRows = + table( + schema, + "bound_rows", + column("id", ColumnDataType.BIGINT), + column("alt", ColumnDataType.BIGINT)); + final Table laterRows = table(schema, "later_rows", column("id", ColumnDataType.BIGINT)); + put(admin(), bound, binding(boundRows, OntologyBindingRole.IDENTITY, "id"), 0L); + final Runnable bindsThenRekeys = + () -> { + put(admin(), later, binding(laterRows, OntologyBindingRole.IDENTITY, "id"), 0L); + put( + admin(), + bound, + binding(boundRows, OntologyBindingRole.IDENTITY, "alt"), + bindings(admin(), bound).getRevision()); + }; + final Jdbi jdbi = Entity.getJdbi(); + final SqlLogger previous = + jdbi.getConfig(org.jdbi.v3.core.statement.SqlStatements.class).getSqlLogger(); + final var changing = new WriteAfterStatement("assetcount", bindsThenRekeys); + jdbi.setSqlLogger(changing); + OntologyTableMapping seen = null; + ClientErrorException refused = null; + try { + seen = read("admin", ontology, OntologyStatementVersion.DRAFT); + } catch (final ClientErrorException conflict) { + refused = conflict; + } finally { + jdbi.setSqlLogger(previous); + } + + assertTrue(changing.writes.get() >= 1); + if (refused != null) { + assertEquals(409, refused.getResponse().getStatus()); + } else { + assertEquals(List.of("urn:Bound", "urn:Later"), iris(seen)); + assertEquals( + List.of(List.of("alt")), + of(seen, URI.create("urn:Bound")).tables().getFirst().subjectKey()); + assertEquals( + List.of(List.of("id")), + of(seen, URI.create("urn:Later")).tables().getFirst().subjectKey()); + } + } + + @Test + void aBindingThatKeepsChangingIsA409AfterThreeReads(final TestNamespace ns) { + final Scene scene = scene(ns); + activate(ns, scene.ontology()); + final Jdbi jdbi = Entity.getJdbi(); + final SqlLogger previous = + jdbi.getConfig(org.jdbi.v3.core.statement.SqlStatements.class).getSqlLogger(); + final var changing = new WriteAfterBindingRows(Integer.MAX_VALUE, flipProductKey(scene)); + jdbi.setSqlLogger(changing); + final ClientErrorException refused; + try { + refused = + assertThrows(ClientErrorException.class, () -> read("admin", scene.ontology(), null)); + } finally { + jdbi.setSqlLogger(previous); + } + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "The table bindings changed while the mapping was read. Ask again", refused.getMessage()); + assertEquals(3, changing.writes.get()); + } + + @Test + void aVersionOf300ClassesAndFilteredBindingsCostsTheSameStatementsAsOneOfThree( + final TestNamespace ns) { + final Scene small = scene(ns); + activate(ns, small.ontology()); + final Ontology ontology = createOntology(ns, "wide"); + final DatabaseSchema schema = schema(ns); + final Table rows = + table( + schema, + "rows", + column("id", ColumnDataType.BIGINT), + column("kind", ColumnDataType.VARCHAR)); + final Table extras = + table( + schema, + "extras", + column("row_id", ColumnDataType.BIGINT), + column("note", ColumnDataType.VARCHAR)); + final List classes = new ArrayList<>(); + IntStream.range(0, CLASSES) + .forEach( + index -> { + final OntologyConcept type = + declareClass(ontology, "Kind" + index, URI.create("urn:Kind" + index)); + classes.add(type); + put( + admin(), + type, + binding(rows, OntologyBindingRole.IDENTITY, "id") + .withRowFilter(filter("kind", OntologyRowFilterOperator.EQUALS, "k" + index)), + 0L); + put(admin(), type, binding(extras, OntologyBindingRole.CONTRIBUTING, "row_id"), 1L); + }); + final OntologyProperty follows = + objectProperty(ontology, "follows", classes.get(0), classes.get(1)); + put( + admin(), + classes.get(0), + binding(rows, OntologyBindingRole.IDENTITY, "id") + .withRowFilter(filter("kind", OntologyRowFilterOperator.EQUALS, "k0")) + .withColumns( + List.of( + column(follows, "id") + .withJoin(join(rows, OntologyJoinStatus.CONFIRMED, "id", "id")))), + 2L); + activate(ns, ontology); + + final int threeRelease = statements(small.ontology(), null); + final int threeDraft = statements(small.ontology(), OntologyStatementVersion.DRAFT); + final int release = statements(ontology, null); + final int draft = statements(ontology, OntologyStatementVersion.DRAFT); + + System.out.printf( + "TABLE-MAPPING-COST threeRelease=%d threeDraft=%d release300=%d draft300=%d%n", + threeRelease, threeDraft, release, draft); + assertEquals(CLASSES, read("admin", ontology, null).classes().size()); + assertEquals( + 2 * CLASSES, + read("admin", ontology, null).classes().stream() + .mapToInt(type -> type.tables().size()) + .sum()); + assertEquals(45, threeRelease); + assertEquals(46, threeDraft); + assertEquals(45, release); + assertEquals(46, draft); + } + + private static int statements(final Ontology ontology, final OntologyStatementVersion version) { + final SqlQueryCounter counter = new SqlQueryCounter(Entity.getJdbi(), ""); + try { + read("admin", ontology, version); + return counter.count(); + } finally { + counter.close(); + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfOntologyChangeSetViewIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfOntologyChangeSetViewIT.java new file mode 100644 index 000000000000..c31c251c9e94 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RdfOntologyChangeSetViewIT.java @@ -0,0 +1,123 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.openmetadata.it.tests.OntologyDraftFixtures.callerWithout; +import static org.openmetadata.it.tests.OntologyDraftFixtures.creates; +import static org.openmetadata.it.tests.OntologyDraftFixtures.draft; +import static org.openmetadata.it.tests.OntologyDraftFixtures.evidence; +import static org.openmetadata.it.tests.OntologyDraftFixtures.proposedClass; +import static org.openmetadata.it.tests.OntologyMappingFixtures.CUSTOMER; +import static org.openmetadata.it.tests.OntologyMappingFixtures.admin; +import static org.openmetadata.it.tests.OntologyMappingFixtures.column; +import static org.openmetadata.it.tests.OntologyMappingFixtures.schema; +import static org.openmetadata.it.tests.OntologyMappingFixtures.table; + +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.util.RdfAccessFixtures; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.service.Entity; + +/** + * A change set is a draft, read with the draft read right and with its evidence masked per reader, + * so the knowledge graph holds none of it and its RDF view refuses every caller. + */ +@ExtendWith(TestNamespaceExtension.class) +class RdfOntologyChangeSetViewIT extends BaseOntologyApprovalIT { + private static final String COLUMN = "hidden_evidence_column"; + private static final String OPERATIONS = "https://open-metadata.org/ontology/operations"; + private static final int POLLS = 12; + private static final long POLL_MILLIS = 1500; + + @Test + void noCallerReadsAChangeSetAsRdfOrFindsItsOperationsInTheGraph(final TestNamespace ns) + throws InterruptedException { + final Ontology ontology = createOntology(ns); + try (var editor = new RdfAccessFixtures("rdfEditor" + ns.shortPrefix()); + var viewer = new RdfAccessFixtures("rdfViewer" + ns.shortPrefix())) { + final OpenMetadataClient reader = + callerWithout(editor, MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final var deny = viewer.denyRole(MetadataOperation.VIEW_BASIC, Entity.TABLE, null); + final OpenMetadataClient plain = + OntologyBindingFixtures.client(viewer.userToken("plain", List.of(deny.getId()))); + final Table hidden = table(schema(ns), "hidden", column(COLUMN, ColumnDataType.BIGINT)); + final OntologyChangeSet draft = + draft( + admin(), + ns, + ontology, + creates(proposedClass(ontology, "Customer", CUSTOMER)) + .withEvidence( + List.of( + evidence(hidden, OntologyChangeEvidenceKind.NAME) + .withColumns(List.of(List.of(COLUMN)))))); + + for (final OpenMetadataClient caller : List.of(reader, plain, admin())) { + for (final String format : List.of("turtle", "jsonld", "ntriples", "rdfxml")) { + final OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> + caller + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/rdf/entity/ontologyChangeSet/" + + draft.getId() + + "?format=" + + format, + null), + format); + assertEquals(403, refusal.getStatusCode(), format); + assertFalse(refusal.getMessage().contains(hidden.getId().toString()), format); + } + } + + viewer.markProjectionReady(); + final String query = + "SELECT ?o WHERE { <" + + OPERATIONS + + "> ?o }"; + for (int poll = 0; poll < POLLS; poll++) { + for (final OpenMetadataClient caller : List.of(plain, reader, admin())) { + final String body = + caller + .getHttpClient() + .executeForString( + HttpMethod.POST, "/v1/rdf/sparql/agent", Map.of("query", query)); + assertFalse(body.contains(hidden.getId().toString()), body); + assertFalse(body.contains(COLUMN), body); + } + Thread.sleep(POLL_MILLIS); + } + } + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java index 3d2ab4111c24..76be7d7a0425 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java @@ -29,6 +29,7 @@ import java.util.UUID; import java.util.function.BiFunction; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.awaitility.Awaitility; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; @@ -1387,6 +1388,230 @@ void testCreatedEndpointSupportsStatusFilter(TestNamespace ns) { "Cancelled created tasks should not include open task"); } + @Test + void testListReturnsEachTasksReviewersAndDomainsAsAGetByIdDoes(TestNamespace ns) { + SharedEntities shared = SharedEntities.get(); + Domain domainA = createDomain(ns, "bulk-fields-domain-a"); + Domain domainB = createDomain(ns, "bulk-fields-domain-b"); + Table tableInDomainA = + createTableWithDomainAndOwners(ns, domainA.getEntityReference(), List.of(shared.USER1_REF)); + Table tableInDomainB = + createTableWithDomainAndOwners(ns, domainB.getEntityReference(), List.of(shared.USER1_REF)); + Task taskA = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "bulk-fields-a", tableInDomainA) + .withAssignees(List.of(shared.USER1.getFullyQualifiedName())) + .withReviewers(List.of(shared.USER2.getFullyQualifiedName()))); + Task taskB = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "bulk-fields-b", tableInDomainB) + .withAssignees(List.of(shared.USER1.getFullyQualifiedName())) + .withReviewers(List.of(shared.USER3.getFullyQualifiedName()))); + String goneName = "bulkgone" + UUID.randomUUID().toString().substring(0, 8); + User gone = + SdkClients.adminClient() + .users() + .create(new CreateUser().withName(goneName).withEmail(goneName + "@test.om.org")); + Task taskWithDeletedReviewer = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "bulk-fields-gone", tableInDomainA) + .withAssignees(List.of(shared.USER1.getFullyQualifiedName())) + .withReviewers(List.of(gone.getFullyQualifiedName()))); + Task taskWithoutReviewer = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "bulk-fields-none", tableInDomainB) + .withAssignees(List.of(shared.USER1.getFullyQualifiedName()))); + SdkClients.adminClient().users().delete(gone.getId()); + + ListResponse listed = + SdkClients.user1Client() + .tasks() + .listAssigned( + null, + "open", + domainA.getFullyQualifiedName() + "," + domainB.getFullyQualifiedName(), + "reviewers,domains"); + + Task listedA = taskIn(listed, taskA); + Task listedB = taskIn(listed, taskB); + Task listedGone = taskIn(listed, taskWithDeletedReviewer); + Task listedNone = taskIn(listed, taskWithoutReviewer); + assertEquals( + List.of(goneName), + listedGone.getReviewers().stream().map(EntityReference::getName).toList()); + assertEquals( + List.of(Boolean.TRUE), + listedGone.getReviewers().stream().map(EntityReference::getDeleted).toList()); + assertEquals(List.of(), listedNone.getReviewers()); + assertEquals( + List.of(shared.USER2.getName()), + listedA.getReviewers().stream().map(EntityReference::getName).toList()); + assertEquals( + List.of(domainA.getFullyQualifiedName()), + listedA.getDomains().stream().map(EntityReference::getFullyQualifiedName).toList()); + assertEquals( + List.of(shared.USER3.getName()), + listedB.getReviewers().stream().map(EntityReference::getName).toList()); + assertEquals( + List.of(domainB.getFullyQualifiedName()), + listedB.getDomains().stream().map(EntityReference::getFullyQualifiedName).toList()); + for (Task listedTask : List.of(listedA, listedB, listedGone, listedNone)) { + Task byId = + SdkClients.adminClient().tasks().get(listedTask.getId().toString(), "reviewers,domains"); + assertEquals( + byId.getReviewers().stream().map(EntityReference::getName).toList(), + listedTask.getReviewers().stream().map(EntityReference::getName).toList()); + assertEquals( + byId.getReviewers().stream().map(EntityReference::getDeleted).toList(), + listedTask.getReviewers().stream().map(EntityReference::getDeleted).toList()); + assertEquals( + byId.getDomains().stream().map(EntityReference::getName).toList(), + listedTask.getDomains().stream().map(EntityReference::getName).toList()); + } + } + + @Test + void testListGivesReviewersAndDomainsInTheOrderAGetDoes(TestNamespace ns) { + SharedEntities shared = SharedEntities.get(); + String assignee = shared.USER1.getFullyQualifiedName(); + List domains = + Stream.of("e", "d", "c", "b", "a") + .map(letter -> createDomain(ns, "order-" + letter)) + .toList(); + Domain firstDomain = domains.getFirst(); + String suffix = UUID.randomUUID().toString().substring(0, 8); + String aboutName = "orderabout" + suffix; + User about = + SdkClients.adminClient() + .users() + .create( + new CreateUser() + .withName(aboutName) + .withEmail(aboutName + "@test.om.org") + .withDomains(domains.stream().map(Domain::getFullyQualifiedName).toList())); + List reviewersCreated = + Stream.of("f", "e", "d", "c", "b", "a") + .map(letter -> "orderrev" + letter + suffix) + .toList(); + List reviewersInOrder = + List.of( + "orderreva" + suffix, + "orderrevb" + suffix, + "orderrevc" + suffix, + "orderrevd" + suffix, + "orderreve" + suffix, + "orderrevf" + suffix); + for (String name : reviewersCreated) { + SdkClients.adminClient() + .users() + .create(new CreateUser().withName(name).withEmail(name + "@test.om.org")); + } + Table inDomainZ = + createTableWithDomainAndOwners( + ns, firstDomain.getEntityReference(), List.of(shared.USER1_REF)); + Table withoutDomain = createTableWithDomainAndOwners(ns, null, List.of(shared.USER1_REF)); + Task aboutUser = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "order-user", inDomainZ) + .withAbout(entityLink("user", about.getFullyQualifiedName())) + .withAssignees(List.of(assignee))); + Task twoReviewers = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "order-reviewers", inDomainZ) + .withAssignees(List.of(assignee)) + .withReviewers(reviewersCreated)); + Task noDomain = + SdkClients.adminClient() + .tasks() + .create( + createTaskRequestAboutTable(ns, "order-none", withoutDomain) + .withAssignees(List.of(assignee))); + String filter = + domains.stream().map(Domain::getFullyQualifiedName).collect(Collectors.joining(",")); + + ListResponse assigned = + SdkClients.user1Client() + .tasks() + .listAssigned(null, "open", filter, "reviewers,domains", 1000); + ListResponse assignedUnfiltered = + SdkClients.user1Client() + .tasks() + .listAssigned(null, "open", null, "reviewers,domains", 1000); + ListResponse created = + SdkClients.adminClient() + .tasks() + .listCreated(null, "open", filter, "reviewers,domains", 1000); + ListResponse owned = + SdkClients.user1Client().tasks().listOwned(null, "open", filter, "reviewers,domains"); + + List domainsOfUser = domains.reversed().stream().map(Domain::getName).toList(); + for (ListResponse listed : List.of(assigned, created)) { + assertEquals(domainsOfUser, namesOf(taskIn(listed, aboutUser).getDomains())); + assertEquals(reviewersInOrder, namesOf(taskIn(listed, twoReviewers).getReviewers())); + } + assertEquals(reviewersInOrder, namesOf(taskIn(owned, twoReviewers).getReviewers())); + assertEquals(List.of(), taskIn(assignedUnfiltered, noDomain).getDomains()); + assertEquals(List.of(), taskIn(assignedUnfiltered, noDomain).getReviewers()); + for (Task listedTask : + List.of( + taskIn(assigned, aboutUser), + taskIn(assigned, twoReviewers), + taskIn(created, aboutUser), + taskIn(created, twoReviewers), + taskIn(assignedUnfiltered, noDomain))) { + Task byId = + SdkClients.adminClient().tasks().get(listedTask.getId().toString(), "reviewers,domains"); + assertEquals(namesOf(byId.getDomains()), namesOf(listedTask.getDomains())); + assertEquals(namesOf(byId.getReviewers()), namesOf(listedTask.getReviewers())); + } + assertEquals( + domainsOfUser, + namesOf( + SdkClients.adminClient() + .tasks() + .get(aboutUser.getId().toString(), "domains") + .getDomains())); + ListResponse domainsOnly = + SdkClients.adminClient() + .tasks() + .listWithFilters( + Map.of("aboutEntity", about.getFullyQualifiedName(), "fields", "domains")); + assertEquals( + List.of("order-a", "order-b", "order-c", "order-d", "order-e").stream() + .map(ns::prefix) + .toList(), + namesOf(taskIn(domainsOnly, aboutUser).getDomains())); + ListResponse reviewersOnly = + SdkClients.adminClient() + .tasks() + .listWithFilters( + Map.of("aboutEntity", inDomainZ.getFullyQualifiedName(), "fields", "reviewers")); + assertEquals(reviewersInOrder, namesOf(taskIn(reviewersOnly, twoReviewers).getReviewers())); + } + + private static List namesOf(List references) { + return references == null ? null : references.stream().map(EntityReference::getName).toList(); + } + + private static Task taskIn(ListResponse listed, Task wanted) { + return listed.getData().stream() + .filter(task -> task.getId().equals(wanted.getId())) + .findFirst() + .orElseThrow(() -> new AssertionError("task " + wanted.getName() + " is not in the list")); + } + @Test void testAssignedEndpointSupportsStatusGroupAndDomainFilter(TestNamespace ns) { SharedEntities shared = SharedEntities.get(); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java new file mode 100644 index 000000000000..0e30a81c651d --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskTableConstraintSuggestionIT.java @@ -0,0 +1,1579 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.openmetadata.it.bootstrap.SharedEntities; +import org.openmetadata.it.factories.DatabaseSchemaTestFactory; +import org.openmetadata.it.factories.DatabaseServiceTestFactory; +import org.openmetadata.it.factories.TableTestFactory; +import org.openmetadata.it.factories.UserTestFactory; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.classification.CreateClassification; +import org.openmetadata.schema.api.classification.CreateTag; +import org.openmetadata.schema.api.tasks.BulkTaskOperation; +import org.openmetadata.schema.api.tasks.CreateTask; +import org.openmetadata.schema.api.tasks.ResolveTask; +import org.openmetadata.schema.entity.classification.Classification; +import org.openmetadata.schema.entity.classification.Tag; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.feed.FormSchema; +import org.openmetadata.schema.entity.feed.TaskFormSchema; +import org.openmetadata.schema.entity.feed.UiSchema; +import org.openmetadata.schema.entity.services.DatabaseService; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.BulkTaskOperationParams; +import org.openmetadata.schema.type.BulkTaskOperationResult; +import org.openmetadata.schema.type.BulkTaskOperationType; +import org.openmetadata.schema.type.DescriptionUpdatePayload; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TableConstraint.ConstraintType; +import org.openmetadata.schema.type.TableConstraint.RelationshipType; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.schema.type.TaskCategory; +import org.openmetadata.schema.type.TaskEntityStatus; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.type.TaskResolutionType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.ForbiddenException; +import org.openmetadata.sdk.exceptions.InvalidRequestException; +import org.openmetadata.sdk.models.ListParams; +import org.openmetadata.sdk.models.ListResponse; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; +import org.openmetadata.service.Entity; +import org.openmetadata.service.governance.workflows.WorkflowHandler; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * A suggestion task can propose a table constraint. Approving it needs EditAll on the table and adds + * the constraint as the approver; rejecting it leaves the table as it was. + */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +public class TaskTableConstraintSuggestionIT { + private static final String TABLE_FIELDS = "tableConstraints,tags,description"; + + @Test + void approvingAsAnOwnerAddsThePrimaryKeyToTheTable(TestNamespace ns) { + Table table = ownedTable(ns, "pk"); + Task task = suggest(ns, table, "pk", constraint(ConstraintType.PRIMARY_KEY, "id"), null); + + Task approved = apply(SdkClients.user3Client(), task); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(table); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.PRIMARY_KEY, constraints.get(0).getConstraintType()); + assertEquals(List.of("id"), constraints.get(0).getColumns()); + } + + @Test + void approvingAForeignKeyToAnotherTablesColumnAddsItWithItsRelationshipType(TestNamespace ns) { + Table orders = adminTable(ns, "orders"); + Table customers = adminTable(ns, "customers"); + String customerId = FullyQualifiedName.add(customers.getFullyQualifiedName(), "id"); + TableConstraint foreignKey = + constraint(ConstraintType.FOREIGN_KEY, "id") + .withReferredColumns(List.of(customerId)) + .withRelationshipType(RelationshipType.MANY_TO_ONE); + Task task = suggest(ns, orders, "fk", foreignKey, null); + + Task approved = apply(SdkClients.adminClient(), task); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(orders); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.FOREIGN_KEY, constraints.get(0).getConstraintType()); + assertEquals(List.of("id"), constraints.get(0).getColumns()); + assertEquals(List.of(customerId), constraints.get(0).getReferredColumns()); + assertEquals(RelationshipType.MANY_TO_ONE, constraints.get(0).getRelationshipType()); + } + + @Test + void approvingWithoutEditAllIsForbiddenAndLeavesTheTableAndTaskAsTheyWere(TestNamespace ns) { + Table table = ownedTable(ns, "denied"); + Task task = + suggest( + ns, + table, + "denied", + constraint(ConstraintType.UNIQUE, "name"), + List.of(SharedEntities.get().USER2.getFullyQualifiedName())); + + ForbiddenException denied = + assertThrows(ForbiddenException.class, () -> apply(SdkClients.user2Client(), task)); + + assertTrue(denied.getMessage().contains("EditAll"), denied.getMessage()); + assertEquals(List.of(), constraintsOf(table)); + assertEquals( + TaskEntityStatus.Open, + SdkClients.adminClient().tasks().get(task.getId().toString()).getStatus()); + } + + @Test + void approvingWhenAnEqualConstraintIsPresentLeavesOneConstraint(TestNamespace ns) { + Table table = adminTable(ns, "equal"); + addConstraint(table, constraint(ConstraintType.UNIQUE, "name")); + Task task = suggest(ns, table, "equal", constraint(ConstraintType.UNIQUE, "name"), null); + + Task approved = apply(SdkClients.adminClient(), task); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + assertEquals(1, constraintsOf(table).size()); + assertEquals(ConstraintType.UNIQUE, constraintsOf(table).get(0).getConstraintType()); + } + + @Test + void rejectingLeavesTheTableAsItWasAndTheRejectionIsListedByTableAndStatus(TestNamespace ns) { + Table table = adminTable(ns, "reject"); + TableConstraint proposed = constraint(ConstraintType.PRIMARY_KEY, "id"); + Task task = suggest(ns, table, "reject", proposed, null); + awaitWorkflowTask(task); + addConstraint(table, constraint(ConstraintType.PRIMARY_KEY, "name")); + + Task rejected = + SdkClients.adminClient() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask() + .withResolutionType(TaskResolutionType.Rejected) + .withComment("id is not unique")); + + assertEquals(TaskEntityStatus.Rejected, rejected.getStatus()); + List kept = constraintsOf(table); + assertEquals(1, kept.size()); + assertEquals(ConstraintType.PRIMARY_KEY, kept.get(0).getConstraintType()); + assertEquals(List.of("name"), kept.get(0).getColumns()); + ListParams params = new ListParams(); + params.addFilter("aboutEntity", table.getFullyQualifiedName()); + params.addFilter("type", "Suggestion"); + params.addFilter("status", "Rejected"); + List listed = SdkClients.adminClient().tasks().list(params).getData(); + assertEquals(1, listed.size()); + assertEquals(task.getId(), listed.get(0).getId()); + Map payload = JsonUtils.convertValue(listed.get(0).getPayload(), Map.class); + assertEquals("TableConstraint", payload.get("suggestionType")); + assertEquals(JsonUtils.pojoToJson(proposed), payload.get("suggestedValue")); + } + + @Test + void aSecondPrimaryKeyIsRefusedNamingTheExistingOneAndTheTaskStaysOpen(TestNamespace ns) { + Table table = adminTable(ns, "second"); + addConstraint(table, constraint(ConstraintType.PRIMARY_KEY, "id")); + Task task = suggest(ns, table, "second", constraint(ConstraintType.PRIMARY_KEY, "name"), null); + + InvalidRequestException refused = + assertThrows(InvalidRequestException.class, () -> apply(SdkClients.adminClient(), task)); + + assertTrue( + refused + .getMessage() + .contains( + "Table '" + + table.getFullyQualifiedName() + + "' already has a primary key on columns [id]; a table has one primary key"), + refused.getMessage()); + assertEquals( + TaskEntityStatus.Open, + SdkClients.adminClient().tasks().get(task.getId().toString()).getStatus()); + assertEquals(1, constraintsOf(table).size()); + assertEquals(List.of("id"), constraintsOf(table).get(0).getColumns()); + } + + @Test + void aSuggestionThatNamesNoValidConstraintIsRefusedWhenFiled(TestNamespace ns) { + Table table = adminTable(ns, "invalid"); + String tableFqn = table.getFullyQualifiedName(); + + assertEquals( + "Table constraint type SORT_KEY cannot be suggested; use PRIMARY_KEY, UNIQUE or FOREIGN_KEY", + fileRefused( + ns, table, "sort", JsonUtils.pojoToJson(constraint(ConstraintType.SORT_KEY, "id")))); + assertEquals( + "Column 'missing' is not a column of table '" + tableFqn + "'", + fileRefused( + ns, + table, + "column", + JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "missing")))); + assertEquals( + "Referred column '" + + tableFqn + + ".ghost' does not resolve to a column of an existing table", + fileRefused( + ns, + table, + "referred", + JsonUtils.pojoToJson( + constraint(ConstraintType.FOREIGN_KEY, "id") + .withReferredColumns(List.of(tableFqn + ".ghost"))))); + assertEquals( + "Suggested value is not a table constraint: not a constraint", + fileRefused(ns, table, "malformed", "not a constraint")); + } + + @Test + void listingBySuggestionTypeCountsAndPagesOnlyThoseTypes(TestNamespace ns) { + Table table = adminTable(ns, "bytype"); + file( + ns, + table, + "pk", + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "id"))), + null); + Task description = + file( + ns, + table, + "description", + Map.of( + "suggestionType", "Description", + "fieldPath", "description", + "suggestedValue", "Orders placed by customers"), + null); + Task tag = + file( + ns, + table, + "tag", + Map.of( + "suggestionType", "Tag", + "fieldPath", "tags", + "suggestedValue", "[{\"tagFQN\":\"PII.Sensitive\",\"source\":\"Classification\"}]"), + null); + + ListParams params = suggestionsAbout(table, "Description,Tag").setLimit(1); + ListResponse first = SdkClients.adminClient().tasks().list(params); + assertEquals(2, first.getPaging().getTotal()); + assertEquals(1, first.getData().size()); + + ListResponse second = + SdkClients.adminClient().tasks().list(params.setAfter(first.getPaging().getAfter())); + assertEquals(2, second.getPaging().getTotal()); + assertEquals(1, second.getData().size()); + assertEquals( + Set.of(description.getId(), tag.getId()), + Set.of(first.getData().get(0).getId(), second.getData().get(0).getId())); + + ListResponse all = SdkClients.adminClient().tasks().list(suggestionsAbout(table, null)); + assertEquals(3, all.getPaging().getTotal()); + assertThrows( + InvalidRequestException.class, + () -> + SdkClients.adminClient().tasks().list(suggestionsAbout(table, "Description,NotAType"))); + } + + private static ListParams suggestionsAbout(Table table, String suggestionType) { + ListParams params = new ListParams(); + params.addFilter("aboutEntity", table.getFullyQualifiedName()); + params.addFilter("type", "Suggestion"); + if (suggestionType != null) { + params.addFilter("suggestionType", suggestionType); + } + return params; + } + + @Test + void aDescriptionAndATagSuggestionStillApply(TestNamespace ns) { + Table table = adminTable(ns, "others"); + Task description = + file( + ns, + table, + "description", + Map.of( + "suggestionType", "Description", + "fieldPath", "description", + "suggestedValue", "Orders placed by customers"), + null); + Task tag = + file( + ns, + table, + "tag", + Map.of( + "suggestionType", "Tag", + "fieldPath", "tags", + "suggestedValue", + "[{\"tagFQN\":\"PII.Sensitive\",\"source\":\"Classification\"," + + "\"labelType\":\"Manual\",\"state\":\"Confirmed\"}]"), + null); + + assertEquals( + TaskEntityStatus.Approved, apply(SdkClients.adminClient(), description).getStatus()); + assertEquals(TaskEntityStatus.Approved, apply(SdkClients.adminClient(), tag).getStatus()); + + Table updated = + SdkClients.adminClient().tables().getByName(table.getFullyQualifiedName(), TABLE_FIELDS); + assertEquals("Orders placed by customers", updated.getDescription()); + assertEquals( + List.of("PII.Sensitive"), updated.getTags().stream().map(t -> t.getTagFQN()).toList()); + } + + private static final String TYPE_CHANGE_REFUSED = + "A resolution cannot change the suggestion type of a task to or from TableConstraint: " + + "the task is '%s', the resolution says '%s'"; + + @Test + void aDescriptionSuggestionCannotBeResolvedIntoAConstraintByAnAssigneeWhoMayOnlyEditDescriptions( + TestNamespace ns) { + Table table = adminTable(ns, "switch"); + String before = descriptionOf(table); + Task task = + file( + ns, + table, + "switch", + Map.of( + "suggestionType", "Description", + "fieldPath", "description", + "suggestedValue", "a description"), + List.of(SharedEntities.get().USER2.getFullyQualifiedName())); + awaitWorkflowTask(task); + + InvalidRequestException refused = + assertThrows( + InvalidRequestException.class, + () -> + resolve( + SdkClients.user2Client(), + task, + payload(JsonUtils.pojoToJson(constraint(ConstraintType.PRIMARY_KEY, "id"))))); + + assertTrue( + refused + .getMessage() + .contains(TYPE_CHANGE_REFUSED.formatted("Description", "TableConstraint")), + refused.getMessage()); + assertEquals(List.of(), constraintsOf(table)); + assertEquals(before, descriptionOf(table)); + assertStillOpen(task); + } + + @Test + void aConstraintSuggestionCannotBeResolvedAsAnotherType(TestNamespace ns) { + Table table = adminTable(ns, "asowner"); + Task task = suggest(ns, table, "asowner", constraint(ConstraintType.PRIMARY_KEY, "id"), null); + awaitWorkflowTask(task); + + InvalidRequestException refused = + assertThrows( + InvalidRequestException.class, + () -> resolve(SdkClients.adminClient(), task, Map.of("suggestionType", "Owner"))); + + assertTrue( + refused.getMessage().contains(TYPE_CHANGE_REFUSED.formatted("TableConstraint", "Owner")), + refused.getMessage()); + assertEquals(List.of(), constraintsOf(table)); + assertStillOpen(task); + } + + @Test + void aDescriptionSuggestionResolvedWithATagPayloadStillAppliesTheTags(TestNamespace ns) { + Table table = ownedTable(ns, "todescription"); + String before = descriptionOf(table); + Task task = + file( + ns, + table, + "totag", + Map.of( + "suggestionType", "Description", + "fieldPath", "description", + "suggestedValue", "a description"), + List.of(SharedEntities.get().USER3.getFullyQualifiedName())); + awaitWorkflowTask(task); + Map tagPayload = new LinkedHashMap<>(); + tagPayload.put("suggestionType", "Tag"); + tagPayload.put("fieldPath", "tags"); + tagPayload.put( + "suggestedValue", + "[{\"tagFQN\":\"PII.Sensitive\",\"source\":\"Classification\"," + + "\"labelType\":\"Manual\",\"state\":\"Confirmed\"}]"); + + Task resolved = resolve(SdkClients.user3Client(), task, tagPayload); + + assertEquals(TaskEntityStatus.Approved, resolved.getStatus()); + Table updated = + SdkClients.adminClient().tables().getByName(table.getFullyQualifiedName(), TABLE_FIELDS); + assertEquals( + List.of("PII.Sensitive"), updated.getTags().stream().map(t -> t.getTagFQN()).toList()); + assertEquals(before, descriptionOf(table)); + } + + @Test + void approvingIsRefusedWhileAnExistingForeignKeyReferstoADeletedTableAndTheTaskCanBeRejected( + TestNamespace ns) { + Table orders = adminTable(ns, "stuckorders"); + Table customers = adminTable(ns, "stuckcustomers"); + String customerId = FullyQualifiedName.add(customers.getFullyQualifiedName(), "id"); + addConstraint( + orders, + constraint(ConstraintType.FOREIGN_KEY, "id") + .withReferredColumns(List.of(customerId)) + .withRelationshipType(RelationshipType.MANY_TO_ONE)); + SdkClients.adminClient() + .tables() + .delete(customers.getId().toString(), Map.of("hardDelete", "true", "recursive", "true")); + Task task = suggest(ns, orders, "stuck", constraint(ConstraintType.UNIQUE, "name"), null); + awaitWorkflowTask(task); + + InvalidRequestException refused = + assertThrows(InvalidRequestException.class, () -> apply(SdkClients.adminClient(), task)); + + assertTrue( + refused.getMessage().contains("Table not found: " + customers.getFullyQualifiedName()), + refused.getMessage()); + assertEquals(1, constraintsOf(orders).size()); + assertStillOpen(task); + assertTrue(WorkflowHandler.getInstance().hasActiveRuntimeTask(task.getId())); + + Task rejected = + SdkClients.adminClient() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + + assertEquals(TaskEntityStatus.Rejected, rejected.getStatus()); + } + + private static String descriptionOf(Table table) { + return SdkClients.adminClient() + .tables() + .getByName(table.getFullyQualifiedName(), TABLE_FIELDS) + .getDescription(); + } + + /** + * A form that applies suggestions to a custom task, and lets a user who may only edit descriptions + * resolve it, gives that user no way to add a table constraint. The form is bound to custom tasks + * of the Review category, which no other test files, so it cannot change another test's task. + */ + @Test + void aCustomTaskCarryingAConstraintPayloadAddsNoConstraintForAUserWhoMayOnlyEditDescriptions( + TestNamespace ns) { + User editor = UserTestFactory.createUser(ns, "constraint_editor"); + OpenMetadataClient editorClient = + SdkClients.createClient(editor.getName(), editor.getEmail(), new String[] {}); + String assignee = editor.getFullyQualifiedName(); + Table filed = adminTable(ns, "customfiled"); + Table switched = adminTable(ns, "customswitched"); + TaskFormSchema form = createSuggestionForm(ns); + try { + Task constraintTask = + fileCustom( + ns, + filed, + "filed", + payload(JsonUtils.pojoToJson(constraint(ConstraintType.SORT_KEY, "id"))), + assignee); + Task descriptionTask = + fileCustom( + ns, + switched, + "switched", + Map.of( + "suggestionType", "Description", + "fieldPath", "description", + "suggestedValue", "a description"), + assignee); + String filedUpdatedBy = updatedByOf(filed); + String switchedUpdatedBy = updatedByOf(switched); + + Task approvedConstraint = + editorClient + .tasks() + .resolve( + constraintTask.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + Task approvedSwitch = + resolve( + editorClient, + descriptionTask, + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name")))); + + assertEquals(TaskEntityStatus.Approved, approvedConstraint.getStatus()); + assertEquals( + TaskEntityStatus.Approved, + SdkClients.adminClient().tasks().get(constraintTask.getId().toString()).getStatus()); + assertEquals(List.of(), constraintsOf(filed)); + assertEquals(filedUpdatedBy, updatedByOf(filed)); + assertEquals(TaskEntityStatus.Approved, approvedSwitch.getStatus()); + assertEquals( + TaskEntityStatus.Approved, + SdkClients.adminClient().tasks().get(descriptionTask.getId().toString()).getStatus()); + assertEquals(List.of(), constraintsOf(switched)); + assertEquals(switchedUpdatedBy, updatedByOf(switched)); + } finally { + SdkClients.adminClient() + .taskFormSchemas() + .delete(form.getId().toString(), Map.of("hardDelete", "true", "recursive", "true")); + } + } + + /** A form is found by its task type and category, so two forms for one pair must not coexist. */ + private static final String REVIEW_FORMS = "suggestionReviewForms"; + + private static final String EDIT_ALL_REQUIRED = + "Principal: CatalogPrincipal{name='shared_user2'} operations [EditAll] not allowed"; + + /** + * A task form bound to the category of a constraint suggestion can narrow the right to resolve + * the task. It cannot narrow the right to add a table constraint: that stays EditAll on the table + * for each way of resolving. Another test also binds a form to suggestions of the Review + * category, so the two hold {@link #REVIEW_FORMS} and never run together. + */ + @Test + @ResourceLock(REVIEW_FORMS) + void aFormNamingEditDescriptionDoesNotLowerTheRightToApproveAConstraintSuggestion( + TestNamespace ns) { + String user2 = SharedEntities.get().USER2.getFullyQualifiedName(); + OpenMetadataClient user2Client = SdkClients.user2Client(); + Table table = ownedTable(ns, "formperm"); + Table applied = ownedTable(ns, "formpermapply"); + Table bulked = ownedTable(ns, "formpermbulk"); + TaskFormSchema form = createSuggestionFormFor(ns, TaskCategory.Review, "suggestion", null); + try { + Task resolved = fileConstraint(ns, TaskCategory.Review, table, "resolve", user2); + Task viaApply = fileConstraint(ns, TaskCategory.Review, applied, "apply", user2); + Task viaBulk = fileConstraint(ns, TaskCategory.Review, bulked, "bulk", user2); + String updatedBy = updatedByOf(table); + awaitWorkflowTask(resolved); + awaitWorkflowTask(viaApply); + awaitWorkflowTask(viaBulk); + + ForbiddenException resolveDenied = + assertThrows( + ForbiddenException.class, + () -> + user2Client + .tasks() + .resolve( + resolved.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved))); + ForbiddenException applyDenied = + assertThrows(ForbiddenException.class, () -> apply(user2Client, viaApply)); + BulkTaskOperationResult bulkResult = bulkApprove(user2Client, viaBulk); + + assertEquals(EDIT_ALL_REQUIRED, resolveDenied.getMessage()); + assertEquals(EDIT_ALL_REQUIRED, applyDenied.getMessage()); + assertEquals(0, bulkResult.getSuccessful()); + assertEquals(1, bulkResult.getFailed()); + assertEquals(EDIT_ALL_REQUIRED, bulkResult.getResults().get(0).getError()); + for (Task task : List.of(resolved, viaApply, viaBulk)) { + assertStillOpen(task); + } + assertEquals(List.of(), constraintsOf(table)); + assertEquals(List.of(), constraintsOf(applied)); + assertEquals(List.of(), constraintsOf(bulked)); + assertEquals(updatedBy, updatedByOf(table)); + + Task approved = + SdkClients.user3Client() + .tasks() + .resolve( + resolved.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(table); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.UNIQUE, constraints.get(0).getConstraintType()); + assertEquals(List.of("name"), constraints.get(0).getColumns()); + assertEquals("shared_user3", updatedByOf(table)); + } finally { + deleteForm(form); + } + } + + /** + * What approving a constraint suggestion does comes from the suggestion, not from a form bound to + * its category: under a form that names another handler, no action, or an action that writes + * another field, approving adds the constraint and nothing else, and rejecting writes nothing. + * Each form has a category of its own that no other test files a suggestion under. + */ + @Test + void aFormNamingAnotherHandlerOrActionsChangesNothingApprovingAConstraintSuggestionDoes( + TestNamespace ns) { + Object noActions = List.of(); + Object patchesTheDescription = + List.of( + Map.of( + "type", + "patchEntityField", + "entityField", + "description", + "value", + "from the form")); + Object[][] forms = { + {TaskCategory.Approval, "approval", noActions}, + {TaskCategory.Incident, "suggestion", patchesTheDescription}, + {TaskCategory.Custom, "custom", List.of(Map.of("type", "setDescription"))} + }; + for (Object[] bound : forms) { + TaskCategory category = (TaskCategory) bound[0]; + Table approvedTable = ownedTable(ns, "approve" + category.value().toLowerCase()); + Table rejectedTable = ownedTable(ns, "reject" + category.value().toLowerCase()); + TaskFormSchema form = createSuggestionFormFor(ns, category, (String) bound[1], bound[2]); + try { + Task approving = fileConstraint(ns, category, approvedTable, "approve", null); + Task rejecting = fileConstraint(ns, category, rejectedTable, "reject", null); + awaitWorkflowTask(approving); + awaitWorkflowTask(rejecting); + String descriptionBefore = descriptionOf(approvedTable); + + Task approved = + SdkClients.user3Client() + .tasks() + .resolve( + approving.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + Task rejected = + SdkClients.user3Client() + .tasks() + .resolve( + rejecting.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Rejected)); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus(), category.value()); + List constraints = constraintsOf(approvedTable); + assertEquals(1, constraints.size(), category.value()); + assertEquals(ConstraintType.UNIQUE, constraints.get(0).getConstraintType()); + assertEquals(List.of("name"), constraints.get(0).getColumns()); + assertEquals(descriptionBefore, descriptionOf(approvedTable), category.value()); + assertEquals(TaskEntityStatus.Rejected, rejected.getStatus(), category.value()); + assertEquals(List.of(), constraintsOf(rejectedTable), category.value()); + assertEquals(descriptionBefore, descriptionOf(rejectedTable), category.value()); + } finally { + deleteForm(form); + } + } + } + + /** + * A task of another type that carries a constraint payload keeps what its form says: the form's + * action runs, and no constraint is added. The form is bound to custom tasks of the Incident + * category, which no other test files. + */ + @Test + void aCustomTaskCarryingAConstraintPayloadStillRunsItsFormsActionsAndAddsNoConstraint( + TestNamespace ns) { + Table table = adminTable(ns, "customactions"); + TaskFormSchema form = + createFormFor( + ns, + TaskEntityType.CustomTask, + TaskCategory.Incident, + List.of( + Map.of( + "type", + "patchEntityField", + "entityField", + "description", + "value", + "from form"))); + try { + Task task = + SdkClients.adminClient() + .tasks() + .create( + new CreateTask() + .withName(ns.prefix("custom-actions")) + .withCategory(TaskCategory.Incident) + .withType(TaskEntityType.CustomTask) + .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) + .withPayload( + payload( + JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))))); + + Task approved = + SdkClients.adminClient() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask().withResolutionType(TaskResolutionType.Approved)); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + assertEquals("from form", descriptionOf(table)); + assertEquals(List.of(), constraintsOf(table)); + } finally { + deleteForm(form); + } + } + + private static final String KEYS_REFUSED = + "A table constraint suggestion carries only the keys of the suggestion payload (confidence, " + + "currentValue, fieldPath, reasoning, source, suggestedValue, suggestionType); not allowed: "; + + @Test + void aSuggestionNamingAChangeRequestIsRefusedWhenFiledAndNoTaskIsStored(TestNamespace ns) { + Table table = ownedTable(ns, "crkey"); + + assertEquals( + KEYS_REFUSED + "changeRequestId", + fileWithExtraKey(ns, table, "crkey", "changeRequestId", UUID.randomUUID().toString())); + + assertEquals(List.of(), tasksAbout(table)); + assertEquals(List.of(), constraintsOf(table)); + } + + @Test + void aSuggestionCarryingTheKeyOfAFormActionIsRefusedWhenFiledAndNoTaskIsStored(TestNamespace ns) { + Table table = ownedTable(ns, "ownerskey"); + List> newOwners = + List.of(Map.of("id", SharedEntities.get().USER2.getId().toString(), "type", "user")); + + assertEquals( + KEYS_REFUSED + "newOwners", + fileWithExtraKey(ns, table, "ownerskey", "newOwners", newOwners)); + + assertEquals(List.of(), tasksAbout(table)); + } + + @Test + void aKeyThatDiffersFromADeclaredKeyOnlyInCaseIsRefused(TestNamespace ns) { + Table table = ownedTable(ns, "casekey"); + + assertEquals( + KEYS_REFUSED + "SuggestedValue", + fileWithExtraKey(ns, table, "casekey", "SuggestedValue", "x")); + assertEquals(List.of(), tasksAbout(table)); + } + + @Test + void aSuggestionCarryingEveryDeclaredKeyIsFiledAndApprovingAddsExactlyItsConstraint( + TestNamespace ns) { + Table table = ownedTable(ns, "allkeys"); + Map payload = + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))); + payload.put("currentValue", "[]"); + + Task task = + file( + ns, + table, + "allkeys", + payload, + List.of(SharedEntities.get().USER3.getFullyQualifiedName())); + + assertEquals( + List.of( + "confidence", + "currentValue", + "fieldPath", + "reasoning", + "source", + "suggestedValue", + "suggestionType"), + storedPayloadKeys(task)); + awaitWorkflowTask(task); + Task approved = resolve(SdkClients.user3Client(), task, null); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(table); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.UNIQUE, constraints.get(0).getConstraintType()); + assertEquals(List.of("name"), constraints.get(0).getColumns()); + assertEquals(null, constraints.get(0).getReferredColumns()); + assertEquals("shared_user3", updatedByOf(table)); + } + + @Test + void approvingWithANewValueAddsTheFiledConstraintAndTheCommentNamesIt(TestNamespace ns) { + Table table = ownedTable(ns, "newvalue"); + Task task = + file( + ns, + table, + "newvalue", + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + List.of(SharedEntities.get().USER3.getFullyQualifiedName())); + awaitWorkflowTask(task); + String otherConstraint = JsonUtils.pojoToJson(constraint(ConstraintType.PRIMARY_KEY, "id")); + + Task approved = + SdkClients.user3Client() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask() + .withResolutionType(TaskResolutionType.Approved) + .withNewValue(otherConstraint)); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(table); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.UNIQUE, constraints.get(0).getConstraintType()); + assertEquals(List.of("name"), constraints.get(0).getColumns()); + Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); + assertEquals(otherConstraint, stored.getResolution().getNewValue()); + assertEquals( + List.of("Added table constraint: UNIQUE on [name]"), + stored.getComments().stream().map(comment -> comment.getMessage()).toList()); + assertEquals( + List.of("shared_user3"), + stored.getComments().stream().map(comment -> comment.getAuthor().getName()).toList()); + } + + @Test + void approvingWithAnotherConstraintInThePayloadAddsItAndTheCommentNamesIt(TestNamespace ns) { + Table table = ownedTable(ns, "otherconstraint"); + TableConstraint filed = constraint(ConstraintType.UNIQUE, "name"); + String primaryKey = JsonUtils.pojoToJson(constraint(ConstraintType.PRIMARY_KEY, "id")); + Task task = suggest(ns, table, "otherconstraint", filed, null); + awaitWorkflowTask(task); + + Task approved = resolve(SdkClients.adminClient(), task, Map.of("suggestedValue", primaryKey)); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(table); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.PRIMARY_KEY, constraints.get(0).getConstraintType()); + assertEquals(List.of("id"), constraints.get(0).getColumns()); + Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); + assertEquals( + Map.of("suggestedValue", primaryKey), + JsonUtils.getMap(stored.getResolution().getPayload())); + assertEquals( + JsonUtils.pojoToJson(filed), JsonUtils.getMap(stored.getPayload()).get("suggestedValue")); + assertEquals( + List.of("Added table constraint: PRIMARY_KEY on [id]"), + stored.getComments().stream().map(comment -> comment.getMessage()).toList()); + assertEquals( + List.of("admin"), + stored.getComments().stream().map(comment -> comment.getAuthor().getName()).toList()); + } + + @Test + void anApprovalWhoseApplyFailsLeavesNoCommentAndTheTaskOpen(TestNamespace ns) { + Table table = ownedTable(ns, "applyfails"); + Tag tag = createTag(ns, "applyfails"); + table.setTags(List.of(tagLabelOf(tag))); + table = SdkClients.adminClient().tables().update(table.getId().toString(), table); + Task task = suggest(ns, table, "applyfails", constraint(ConstraintType.UNIQUE, "name"), null); + awaitWorkflowTask(task); + tag.setDisabled(true); + SdkClients.adminClient().tags().update(tag.getId().toString(), tag); + + InvalidRequestException refused = + assertThrows( + InvalidRequestException.class, () -> resolve(SdkClients.adminClient(), task, null)); + + assertEquals( + "Tag label " + + tag.getFullyQualifiedName() + + " is disabled and can't be assigned to a data asset.", + refused.getMessage()); + assertEquals(400, refused.getStatusCode()); + Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); + assertEquals(TaskEntityStatus.Open, stored.getStatus()); + assertEquals(List.of(), stored.getComments() == null ? List.of() : stored.getComments()); + assertEquals(List.of(), constraintsOf(table)); + } + + @Test + void aRejectionStoresNoCommentAndAddsNoConstraint(TestNamespace ns) { + Table table = adminTable(ns, "rejectnocomment"); + Task task = + suggest(ns, table, "rejectnocomment", constraint(ConstraintType.UNIQUE, "name"), null); + awaitWorkflowTask(task); + + Task rejected = + SdkClients.adminClient() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask() + .withResolutionType(TaskResolutionType.Rejected) + .withComment("Not unique")); + + assertEquals(TaskEntityStatus.Rejected, rejected.getStatus()); + Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); + assertEquals(TaskEntityStatus.Rejected, stored.getStatus()); + assertEquals(List.of(), stored.getComments() == null ? List.of() : stored.getComments()); + assertEquals(List.of(), constraintsOf(table)); + } + + @Test + void approvingADescriptionUpdateWithAValueStoresItsCommentAndWritesTheValue(TestNamespace ns) { + Table table = adminTable(ns, "descriptioncomment"); + CreateTask request = + new CreateTask() + .withName(ns.prefix("description-update-comment")) + .withCategory(TaskCategory.MetadataUpdate) + .withType(TaskEntityType.DescriptionUpdate) + .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) + .withPayload( + new DescriptionUpdatePayload() + .withFieldPath("description") + .withCurrentDescription(table.getDescription()) + .withNewDescription("A filed description")); + Task task = SdkClients.adminClient().tasks().create(request); + + Task approved = + SdkClients.adminClient() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask() + .withResolutionType(TaskResolutionType.Approved) + .withNewValue("An edited description")); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + assertEquals("An edited description", descriptionOf(table)); + Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); + assertEquals( + List.of("Resolved with description: An edited description"), + stored.getComments().stream().map(comment -> comment.getMessage()).toList()); + } + + @Test + void theKeysOfAnOpenSuggestionCannotChangeAfterItIsFiled(TestNamespace ns) { + Table table = ownedTable(ns, "frozen"); + Task task = + file( + ns, + table, + "frozen", + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + List.of(SharedEntities.get().USER3.getFullyQualifiedName())); + awaitWorkflowTask(task); + List filed = storedPayloadKeys(task); + + assertEquals( + KEYS_REFUSED + "changeRequestId", + patchRefused( + task, + "[{\"op\":\"add\",\"path\":\"/payload/changeRequestId\",\"value\":\"" + + UUID.randomUUID() + + "\"}]")); + assertEquals(filed, storedPayloadKeys(task)); + assertEquals( + KEYS_REFUSED + "newOwners", + patchRefused(task, "[{\"op\":\"add\",\"path\":\"/payload/newOwners\",\"value\":[]}]")); + assertEquals(filed, storedPayloadKeys(task)); + assertEquals(filed, storedPayloadKeys(task)); + assertStillOpen(task); + + patchAccepted( + task, "[{\"op\":\"replace\",\"path\":\"/payload/reasoning\",\"value\":\"edited\"}]"); + assertEquals( + "edited", + JsonUtils.getMap( + SdkClients.adminClient().tasks().get(task.getId().toString(), "*").getPayload()) + .get("reasoning")); + assertStillOpen(task); + } + + @Test + void aResolutionThatAddsAKeyIsRefusedAndTheTaskStaysOpen(TestNamespace ns) { + Table table = ownedTable(ns, "reskey"); + Task task = + file( + ns, + table, + "reskey", + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + List.of(SharedEntities.get().USER3.getFullyQualifiedName())); + awaitWorkflowTask(task); + Map extra = Map.of("changeRequestId", UUID.randomUUID().toString()); + + assertEquals( + KEYS_REFUSED + "changeRequestId", + assertThrows( + InvalidRequestException.class, () -> resolve(SdkClients.user3Client(), task, extra)) + .getMessage()); + assertEquals( + KEYS_REFUSED + "changeRequestId", + assertThrows( + InvalidRequestException.class, + () -> + SdkClients.adminClient() + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask() + .withResolutionType(TaskResolutionType.Rejected) + .withPayload( + JsonUtils.convertValue( + extra, org.openmetadata.schema.api.tasks.Payload.class)))) + .getMessage()); + + assertEquals(List.of(), constraintsOf(table)); + assertStillOpen(task); + assertEquals( + List.of(), + storedPayloadKeys(task).stream().filter(k -> k.equals("changeRequestId")).toList()); + } + + @Test + void aSuggestionFiledByPutWithAKeyOutsideTheSchemaIsRefusedAndNoTaskIsStored(TestNamespace ns) { + Table table = ownedTable(ns, "putkey"); + CreateTask put = + new CreateTask() + .withName(ns.prefix("constraint-putkey")) + .withCategory(TaskCategory.MetadataUpdate) + .withType(TaskEntityType.Suggestion) + .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) + .withPayload( + withKey( + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + "newOwners", + List.of())); + + assertEquals( + KEYS_REFUSED + "newOwners", + assertThrows( + InvalidRequestException.class, + () -> + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.PUT, "/v1/tasks", put, Task.class)) + .getMessage()); + + assertEquals(List.of(), tasksAbout(table)); + } + + @Test + void aPatchThatTurnsADescriptionSuggestionIntoAConstraintCannotAddAKey(TestNamespace ns) { + Table table = ownedTable(ns, "typepatch"); + Task task = + file( + ns, + table, + "typepatch", + Map.of( + "suggestionType", "Description", + "fieldPath", "description", + "suggestedValue", "Orders placed by customers"), + List.of(SharedEntities.get().USER3.getFullyQualifiedName())); + awaitWorkflowTask(task); + List filed = storedPayloadKeys(task); + + assertEquals( + KEYS_REFUSED + "newOwners", + patchRefused( + task, + "[{\"op\":\"replace\",\"path\":\"/payload/suggestionType\",\"value\":\"TableConstraint\"}," + + "{\"op\":\"replace\",\"path\":\"/payload/fieldPath\",\"value\":\"tableConstraints\"}," + + "{\"op\":\"replace\",\"path\":\"/payload/suggestedValue\",\"value\":" + + JsonUtils.pojoToJson( + JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))) + + "},{\"op\":\"add\",\"path\":\"/payload/newOwners\",\"value\":[]}]")); + + Map stored = + JsonUtils.getMap( + SdkClients.adminClient().tasks().get(task.getId().toString(), "*").getPayload()); + assertEquals("Description", stored.get("suggestionType")); + assertEquals(filed, storedPayloadKeys(task)); + assertStillOpen(task); + } + + @Test + @ResourceLock(REVIEW_FORMS) + void aVoteThatWouldWriteAKeyOutsideTheSchemaIsRefusedWhateverItDecidesAndTheTaskStaysOpen( + TestNamespace ns) { + String workflowName = "constraintVotes" + UUID.randomUUID().toString().substring(0, 8); + JsonNode workflow = createVotingWorkflow(workflowName); + TaskFormSchema form = null; + try { + form = createVotingForm(ns, workflowName, "changeRequestId"); + Table table = ownedTable(ns, "votes"); + Task task = fileForVotes(ns, table, "votes"); + List filed = storedPayloadKeys(task); + + assertEquals( + KEYS_REFUSED + "changeRequestId", + assertThrows( + InvalidRequestException.class, + () -> + vote( + SdkClients.user3Client(), + task, + TaskResolutionType.Rejected, + UUID.randomUUID().toString())) + .getMessage()); + assertEquals(filed, storedPayloadKeys(task)); + assertStillOpen(task); + + assertEquals( + TaskEntityStatus.Open, + vote(SdkClients.user3Client(), task, TaskResolutionType.Rejected, null).getStatus()); + assertEquals(filed, storedPayloadKeys(task)); + assertStillOpen(task); + assertEquals(List.of(), constraintsOf(table)); + + Table approvedTable = ownedTable(ns, "votesapproved"); + Task approving = fileForVotes(ns, approvedTable, "votesapproved"); + vote(SdkClients.user3Client(), approving, TaskResolutionType.Approved, null); + Task approved = vote(SdkClients.adminClient(), approving, TaskResolutionType.Approved, null); + + assertEquals(TaskEntityStatus.Approved, approved.getStatus()); + List constraints = constraintsOf(approvedTable); + assertEquals(1, constraints.size()); + assertEquals(ConstraintType.UNIQUE, constraints.get(0).getConstraintType()); + assertEquals(List.of("name"), constraints.get(0).getColumns()); + } finally { + if (form != null) { + deleteForm(form); + } + deleteWorkflow(workflow); + } + } + + private static JsonNode createVotingWorkflow(String name) { + ObjectNode workflow; + try (InputStream in = + TaskTableConstraintSuggestionIT.class.getResourceAsStream( + "/json/data/governance/workflows/SuggestionTaskWorkflow.json")) { + workflow = + (ObjectNode) JsonUtils.readTree(new String(in.readAllBytes(), StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + workflow.put("name", name).put("displayName", name); + workflow.remove("fullyQualifiedName"); + ObjectNode review = (ObjectNode) workflow.get("nodes").get(1).get("config"); + review.put("approvalThreshold", 2).put("rejectionThreshold", 2); + return JsonUtils.readTree( + SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.POST, + "/v1/governance/workflowDefinitions", + JsonUtils.convertValue(workflow, Map.class), + RequestOptions.builder().build())); + } + + private static void deleteWorkflow(JsonNode workflow) { + SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.DELETE, + "/v1/governance/workflowDefinitions/" + + workflow.get("id").asText() + + "?hardDelete=true&recursive=true", + null, + RequestOptions.builder().build()); + } + + private static TaskFormSchema createVotingForm( + TestNamespace ns, String workflowName, String valueField) { + return SdkClients.adminClient() + .taskFormSchemas() + .create( + new TaskFormSchema() + .withId(UUID.randomUUID()) + .withName(ns.prefix("form-votes")) + .withTaskType(TaskEntityType.Suggestion.value()) + .withTaskCategory(TaskCategory.Review.value()) + .withWorkflowDefinitionRef(workflowName) + .withFormSchema( + new FormSchema() + .withAdditionalProperty("type", "object") + .withAdditionalProperty("properties", Map.of())) + .withUiSchema( + new UiSchema() + .withAdditionalProperty( + "ui:handler", + Map.of( + "type", + "suggestion", + "permission", + "EditAll", + "valueField", + valueField)))); + } + + /** Files a constraint suggestion for the voting workflow, assigned to two users. */ + private static Task fileForVotes(TestNamespace ns, Table table, String label) { + Task task = + fileConstraintTo( + ns, + TaskCategory.Review, + table, + label, + List.of(SharedEntities.get().USER3.getFullyQualifiedName(), "admin")); + awaitWorkflowTask(task); + return task; + } + + private static Task vote( + OpenMetadataClient client, Task task, TaskResolutionType type, String newValue) { + ResolveTask request = new ResolveTask().withResolutionType(type).withComment("vote"); + if (newValue != null) { + request.setNewValue(newValue); + } + return client.tasks().resolve(task.getId().toString(), request); + } + + private static Map withKey( + Map payload, String key, Object value) { + payload.put(key, value); + return payload; + } + + private static String fileWithExtraKey( + TestNamespace ns, Table table, String label, String key, Object value) { + return assertThrows( + InvalidRequestException.class, + () -> + file( + ns, + table, + label, + withKey( + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + key, + value), + List.of(SharedEntities.get().USER3.getFullyQualifiedName()))) + .getMessage(); + } + + private static List tasksAbout(Table table) { + ListParams params = new ListParams(); + params.addFilter("aboutEntity", table.getFullyQualifiedName()); + return SdkClients.adminClient().tasks().list(params).getData(); + } + + private static List storedPayloadKeys(Task task) { + Task stored = SdkClients.adminClient().tasks().get(task.getId().toString(), "*"); + return JsonUtils.getMap(stored.getPayload()).keySet().stream().sorted().toList(); + } + + private static String patchRefused(Task task, String patch) { + return assertThrows(InvalidRequestException.class, () -> patchTask(task, patch)).getMessage(); + } + + private static void patchAccepted(Task task, String patch) { + patchTask(task, patch); + } + + private static void patchTask(Task task, String patch) { + SdkClients.adminClient() + .getHttpClient() + .executeForString( + HttpMethod.PATCH, + "/v1/tasks/" + task.getId(), + patch, + org.openmetadata.sdk.network.RequestOptions.builder() + .header("Content-Type", "application/json-patch+json") + .build()); + } + + private static Task fileConstraint( + TestNamespace ns, TaskCategory category, Table table, String label, String assignee) { + return fileConstraintTo( + ns, category, table, label, assignee == null ? null : List.of(assignee)); + } + + private static Task fileConstraintTo( + TestNamespace ns, TaskCategory category, Table table, String label, List assignees) { + return fileIn( + ns, + category, + table, + label, + payload(JsonUtils.pojoToJson(constraint(ConstraintType.UNIQUE, "name"))), + assignees); + } + + private static TaskFormSchema createSuggestionFormFor( + TestNamespace ns, TaskCategory category, String handler, Object approveActions) { + return createFormFor(ns, TaskEntityType.Suggestion, category, handler, approveActions); + } + + private static TaskFormSchema createFormFor( + TestNamespace ns, TaskEntityType type, TaskCategory category, Object approveActions) { + return createFormFor(ns, type, category, "custom", approveActions); + } + + private static TaskFormSchema createFormFor( + TestNamespace ns, + TaskEntityType type, + TaskCategory category, + String handler, + Object approveActions) { + UiSchema ui = + new UiSchema() + .withAdditionalProperty( + "ui:handler", Map.of("type", handler, "permission", "EditDescription")); + if (approveActions != null) { + ui.withAdditionalProperty( + "ui:execution", Map.of("approve", Map.of("actions", approveActions))); + } + return SdkClients.adminClient() + .taskFormSchemas() + .create( + new TaskFormSchema() + .withId(UUID.randomUUID()) + .withName(ns.prefix("form-" + type.value() + "-" + category.value().toLowerCase())) + .withTaskType(type.value()) + .withTaskCategory(category.value()) + .withFormSchema( + new FormSchema() + .withAdditionalProperty("type", "object") + .withAdditionalProperty("properties", Map.of())) + .withUiSchema(ui)); + } + + private static void deleteForm(TaskFormSchema form) { + SdkClients.adminClient() + .taskFormSchemas() + .delete(form.getId().toString(), Map.of("hardDelete", "true", "recursive", "true")); + } + + private static BulkTaskOperationResult bulkApprove(OpenMetadataClient client, Task task) { + BulkTaskOperation operation = + new BulkTaskOperation() + .withTaskIds(List.of(task.getId().toString())) + .withOperation(BulkTaskOperationType.Approve) + .withParams(new BulkTaskOperationParams().withComment("approve")); + return client + .getHttpClient() + .execute(HttpMethod.POST, "/v1/tasks/bulk", operation, BulkTaskOperationResult.class); + } + + private static TaskFormSchema createSuggestionForm(TestNamespace ns) { + return SdkClients.adminClient() + .taskFormSchemas() + .create( + new TaskFormSchema() + .withId(UUID.randomUUID()) + .withName(ns.prefix("suggestion-form")) + .withTaskType(TaskEntityType.CustomTask.value()) + .withTaskCategory(TaskCategory.Review.value()) + .withFormSchema( + new FormSchema() + .withAdditionalProperty("type", "object") + .withAdditionalProperty("properties", Map.of())) + .withUiSchema( + new UiSchema() + .withAdditionalProperty( + "ui:handler", + Map.of("type", "suggestion", "permission", "EditDescription")))); + } + + private static Task fileCustom( + TestNamespace ns, Table table, String label, Map payload, String assignee) { + return SdkClients.adminClient() + .tasks() + .create( + new CreateTask() + .withName(ns.prefix("custom-" + label)) + .withCategory(TaskCategory.Review) + .withType(TaskEntityType.CustomTask) + .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) + .withPayload(payload) + .withAssignees(List.of(assignee))); + } + + private static String updatedByOf(Table table) { + return SdkClients.adminClient() + .tables() + .getByName(table.getFullyQualifiedName(), TABLE_FIELDS) + .getUpdatedBy(); + } + + private static void assertStillOpen(Task task) { + assertEquals( + TaskEntityStatus.Open, + SdkClients.adminClient().tasks().get(task.getId().toString()).getStatus()); + assertTrue(WorkflowHandler.getInstance().hasActiveRuntimeTask(task.getId())); + } + + private static Task resolve(OpenMetadataClient client, Task task, Map payload) { + return client + .tasks() + .resolve( + task.getId().toString(), + new ResolveTask() + .withResolutionType(TaskResolutionType.Approved) + .withPayload( + JsonUtils.convertValue( + payload, org.openmetadata.schema.api.tasks.Payload.class))); + } + + private static String fileRefused( + TestNamespace ns, Table table, String label, String suggestedValue) { + return assertThrows( + InvalidRequestException.class, + () -> file(ns, table, label, payload(suggestedValue), null)) + .getMessage(); + } + + private static Tag createTag(TestNamespace ns, String name) { + Classification classification = + ns.trackRoot( + Entity.CLASSIFICATION, + SdkClients.adminClient() + .classifications() + .create( + new CreateClassification() + .withName(ns.shortPrefix("cls_" + name)) + .withDescription("A classification a table is tagged with"))); + return SdkClients.adminClient() + .tags() + .create( + new CreateTag() + .withName(ns.shortPrefix("tag_" + name)) + .withClassification(classification.getFullyQualifiedName()) + .withDescription("A tag a table is tagged with")); + } + + private static TagLabel tagLabelOf(Tag tag) { + return new TagLabel() + .withTagFQN(tag.getFullyQualifiedName()) + .withSource(TagLabel.TagSource.CLASSIFICATION) + .withLabelType(TagLabel.LabelType.MANUAL) + .withState(TagLabel.State.CONFIRMED); + } + + private static Table adminTable(TestNamespace ns, String label) { + DatabaseService service = DatabaseServiceTestFactory.createPostgres(ns); + DatabaseSchema schema = DatabaseSchemaTestFactory.createSimple(ns, service); + return TableTestFactory.createWithName(ns, schema.getFullyQualifiedName(), label); + } + + /** A table the shared third user owns, which gives that user EditAll on it. */ + private static Table ownedTable(TestNamespace ns, String label) { + Table table = adminTable(ns, label); + table.setOwners(List.of(SharedEntities.get().USER3_REF)); + return SdkClients.adminClient().tables().update(table.getId().toString(), table); + } + + private static void addConstraint(Table table, TableConstraint constraint) { + SdkClients.adminClient() + .tables() + .patch( + table.getId().toString(), + JsonUtils.readTree( + "[{\"op\":\"add\",\"path\":\"/tableConstraints\",\"value\":[" + + JsonUtils.pojoToJson(constraint) + + "]}]")); + } + + private static List constraintsOf(Table table) { + Table stored = + SdkClients.adminClient().tables().getByName(table.getFullyQualifiedName(), TABLE_FIELDS); + return stored.getTableConstraints() == null ? List.of() : stored.getTableConstraints(); + } + + private static TableConstraint constraint(ConstraintType type, String... columns) { + return new TableConstraint().withConstraintType(type).withColumns(List.of(columns)); + } + + private static Task suggest( + TestNamespace ns, + Table table, + String label, + TableConstraint constraint, + List assignees) { + return file(ns, table, label, payload(JsonUtils.pojoToJson(constraint)), assignees); + } + + private static Map payload(String suggestedValue) { + Map payload = new LinkedHashMap<>(); + payload.put("suggestionType", "TableConstraint"); + payload.put("fieldPath", "tableConstraints"); + payload.put("suggestedValue", suggestedValue); + payload.put("source", "Agent"); + payload.put("confidence", 80.0); + payload.put("reasoning", "The column is unique in the sampled rows"); + return payload; + } + + private static Task file( + TestNamespace ns, + Table table, + String label, + Map payload, + List assignees) { + return fileIn(ns, TaskCategory.MetadataUpdate, table, label, payload, assignees); + } + + private static Task fileIn( + TestNamespace ns, + TaskCategory category, + Table table, + String label, + Map payload, + List assignees) { + CreateTask request = + new CreateTask() + .withName(ns.prefix("constraint-" + label)) + .withCategory(category) + .withType(TaskEntityType.Suggestion) + .withAbout(String.format("<#E::table::%s>", table.getFullyQualifiedName())) + .withPayload(payload); + if (assignees != null) { + request.setAssignees(assignees); + } + return SdkClients.adminClient().tasks().create(request); + } + + private static Task apply(OpenMetadataClient client, Task task) { + awaitWorkflowTask(task); + return client + .getHttpClient() + .execute( + HttpMethod.PUT, "/v1/tasks/" + task.getId() + "/suggestion/apply", null, Task.class); + } + + private static void awaitWorkflowTask(Task task) { + UUID taskId = task.getId(); + Awaitility.await("workflow task for " + taskId) + .atMost(Duration.ofSeconds(20)) + .pollInterval(Duration.ofMillis(250)) + .untilAsserted( + () -> { + Task stored = + SdkClients.adminClient() + .tasks() + .get(taskId.toString(), "status,workflowDefinitionId,workflowStageId"); + assertNotNull(stored.getWorkflowStageId()); + assertTrue(WorkflowHandler.getInstance().hasActiveRuntimeTask(taskId)); + }); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java new file mode 100644 index 000000000000..890810336ad3 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/OntologyChangeSetEventDeliveryIT.java @@ -0,0 +1,157 @@ +/* + * 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.alerts; + +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 static org.openmetadata.schema.entity.events.SubscriptionDestination.SubscriptionType.WEBHOOK; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.openmetadata.it.tests.OntologyDraftScene; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.events.CreateEventSubscription; +import org.openmetadata.schema.entity.events.AlertType; +import org.openmetadata.schema.entity.events.EventSubscription; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; + +/** + * An event reaches every subscriber, destination and the audit log, and the server that stores it + * cannot know who will read it. So a stored event of a change set holds no operations, in its + * entity or in the old and new value of a recorded field change, and a subscriber who may not read the draft + * receives none of its binding. The draft itself still returns its operations to a reader. + */ +@Isolated +@ExtendWith(TestNamespaceExtension.class) +class OntologyChangeSetEventDeliveryIT { + private static final int ONE_DAY_SECONDS = 86400; + private static final int MAX_TICKS = 30; + + @Test + void aWebhookOnEveryResourceReceivesNoOperationsOfADraft(final TestNamespace ns) + throws Exception { + final OpenMetadataClient creator = AlertFixtures.alertCreatorClient(); + try (RecordingReceiver receiver = new RecordingReceiver()) { + final EventSubscription alert = webhookOnEveryResource(ns, creator, receiver); + QuietAlert.settle(alert); + + final OntologyDraftScene.Built scene = OntologyDraftScene.build(ns); + OntologyDraftScene.saveAgainAndApply(scene); + final String draftId = scene.draft().getId().toString(); + for (int tick = 0; tick < MAX_TICKS && !hasApplied(receiver, draftId); tick++) { + DirectTick.run(alert); + } + + final List events = eventsOf(receiver, draftId); + assertEquals( + Set.of("entityCreated", "entityUpdated", "ontologyChangeSetApplied"), + new TreeSet<>(events.stream().map(event -> event.path("eventType").asText()).toList())); + for (final JsonNode event : events) { + assertNoOperations(event, scene); + } + assertTrue( + events.stream().anyMatch(event -> !operationChangesOf(event).isEmpty()), + "a stored event still names the change of the operations"); + assertTrue(OntologyDraftScene.read(scene).contains(scene.table().getId().toString())); + assertTrue(OntologyDraftScene.read(scene).contains(OntologyDraftScene.VALUE)); + assertTrue(versionsHoldOperations(OntologyDraftScene.versions(scene), scene)); + } + } + + /** A stored version is the content of the draft, so an earlier one still holds its operations. */ + private static boolean versionsHoldOperations( + final String versions, final OntologyDraftScene.Built scene) { + final List held = new java.util.ArrayList<>(); + JsonUtils.readTree(versions).path("versions").forEach(version -> held.add(version)); + return !held.isEmpty() + && held.stream() + .map(version -> version.isTextual() ? JsonUtils.readTree(version.asText()) : version) + .allMatch( + version -> + version.path("operations").size() > 0 + && version + .path("operations") + .toString() + .contains(scene.table().getId().toString())); + } + + private static EventSubscription webhookOnEveryResource( + final TestNamespace ns, final OpenMetadataClient creator, final RecordingReceiver receiver) { + final CreateEventSubscription request = + new CreateEventSubscription() + .withName(ns.prefix("draft_events")) + .withAlertType(AlertType.NOTIFICATION) + .withResources(List.of("all")) + .withEnabled(true) + .withBatchSize(100) + .withPollInterval(ONE_DAY_SECONDS) + .withDestinations(List.of(AlertFixtures.external(WEBHOOK, receiver.url("/draft")))); + return AlertFixtures.stored(creator.eventSubscriptions().create(request).getId()); + } + + private static boolean hasApplied(final RecordingReceiver receiver, final String draftId) { + return eventsOf(receiver, draftId).stream() + .anyMatch(event -> "ontologyChangeSetApplied".equals(event.path("eventType").asText())); + } + + private static List eventsOf(final RecordingReceiver receiver, final String draftId) { + return receiver.received().stream() + .map(RecordingReceiver.Received::body) + .filter(body -> body.contains(draftId)) + .map(JsonUtils::readTree) + .filter(event -> "ontologyChangeSet".equals(event.path("entityType").asText())) + .toList(); + } + + private static void assertNoOperations( + final JsonNode event, final OntologyDraftScene.Built scene) { + final String body = event.toString(); + assertFalse(body.contains(scene.table().getId().toString()), body); + assertFalse(body.contains(OntologyDraftScene.COLUMN), body); + assertFalse(body.contains(OntologyDraftScene.VALUE), body); + final JsonNode entity = event.path("entity"); + final JsonNode held = entity.isTextual() ? JsonUtils.readTree(entity.asText()) : entity; + assertEquals(scene.draft().getName(), held.path("name").asText(), body); + assertFalse(held.has("operations"), body); + for (final JsonNode change : operationChangesOf(event)) { + assertFalse(change.has("oldValue") || change.has("newValue"), body); + } + } + + // The change keeps its name, so an alert on a change of the operations still matches. + private static List operationChangesOf(final JsonNode event) { + final List changes = new ArrayList<>(); + for (final String kind : List.of("fieldsAdded", "fieldsUpdated", "fieldsDeleted")) { + event + .path("changeDescription") + .path(kind) + .forEach( + change -> { + if ("operations".equals(change.path("name").asText())) { + changes.add(change); + } + }); + } + return changes; + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyConceptBindingDaoIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyConceptBindingDaoIT.java index 9badd0193ed7..c9835aea597c 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyConceptBindingDaoIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyConceptBindingDaoIT.java @@ -1,7 +1,9 @@ package org.openmetadata.it.tests.ontology; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.openmetadata.it.tests.ontology.OntologyTestDatabase.migrate; +import static org.openmetadata.it.tests.ontology.OntologyTestDatabase.repositoryRoot; import static org.openmetadata.it.tests.ontology.OntologyTestDatabase.withDatabase; import java.util.List; @@ -11,8 +13,13 @@ import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.openmetadata.it.util.ScratchDatabase; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.StoredBinding; import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.migration.utils.MigrationFile; @Execution(ExecutionMode.CONCURRENT) class OntologyConceptBindingDaoIT { @@ -47,6 +54,162 @@ void firstTablesReadsTheEarliestTableRowsOfEveryConceptInOneStatement() { }); } + @Test + void aRowKeepsItsRoleKeyFilterAndJoinAndARowWrittenBeforeThemReadsBackUnassigned() { + ConnectionType dialect = ScratchDatabase.dialect(); + withDatabase( + handle -> { + handle.execute("DROP TABLE IF EXISTS ontology_concept_binding"); + migrate(handle, dialect); + bind(handle, CUSTOMER, 1, "table"); + final var dao = handle.attach(CollectionDAO.class).ontologyConceptBindingDAO(); + dao.upsert(stored(CUSTOMER, 2, "identity", "[[\"tenant\"],[\"id\"]]")); + dao.upsert(stored(CUSTOMER, 3, "contributing", "[[\"customer_id\"]]")); + dao.upsert(stored(TRANSFER, 4, "contributing", "[[\"customer_id\"]]")); + dao.upsert(stored(TRANSFER, 5, "identity", "[[\"id\"]]")); + + final var older = dao.find(CUSTOMER, asset(1)); + assertNull(older.role()); + assertNull(older.subjectKey()); + assertNull(older.rowFilter()); + assertEquals(List.of(), older.columns()); + + final var identity = dao.find(CUSTOMER, asset(2)); + assertEquals(OntologyBindingRole.IDENTITY, identity.role()); + assertEquals(List.of(List.of("tenant"), List.of("id")), identity.subjectKey()); + assertEquals(List.of("status"), identity.rowFilter().getColumn()); + assertEquals(OntologyRowFilterOperator.IN, identity.rowFilter().getOperator()); + assertEquals(List.of("OPEN", 7, true), identity.rowFilter().getValue()); + final var join = identity.columns().getFirst().getJoin(); + assertEquals(asset(9), join.getTargetAssetId()); + assertEquals(OntologyJoinStatus.INFERRED, join.getStatus()); + assertEquals(List.of("customer_id"), join.getOn().getFirst().getChild()); + assertEquals(List.of("id"), join.getOn().getFirst().getParent()); + + assertEquals( + List.of(TRANSFER + "/" + asset(5), CUSTOMER + "/" + asset(2)), + dao + .listIdentityRows( + List.of(CUSTOMER.toString(), TRANSFER.toString(), UNBOUND.toString())) + .stream() + .map(row -> row.conceptId() + "/" + row.assetId()) + .toList()); + }); + } + + @Test + void rewritingARowReplacesItsRoleKeyAndFilterAndCanClearThem() { + ConnectionType dialect = ScratchDatabase.dialect(); + withDatabase( + handle -> { + handle.execute("DROP TABLE IF EXISTS ontology_concept_binding"); + migrate(handle, dialect); + final var dao = handle.attach(CollectionDAO.class).ontologyConceptBindingDAO(); + dao.upsert(stored(CUSTOMER, 2, "identity", "[[\"id\"]]")); + + dao.upsert( + new StoredBinding( + CUSTOMER.toString(), + asset(2).toString(), + "table", + "hash2", + "[]", + null, + null, + null)); + + final var cleared = dao.find(CUSTOMER, asset(2)); + assertNull(cleared.role()); + assertNull(cleared.subjectKey()); + assertNull(cleared.rowFilter()); + assertEquals(List.of(), cleared.columns()); + assertEquals(List.of(), dao.listIdentityRows(List.of(CUSTOMER.toString()))); + }); + } + + @Test + void theMigrationAddsItsColumnsToATableThatHoldsRowsAndASecondRunChangesNothing() { + ConnectionType dialect = ScratchDatabase.dialect(); + withDatabase( + handle -> { + handle.execute("DROP TABLE IF EXISTS ontology_concept_binding"); + createTableAsFirstShipped(handle, dialect); + bind(handle, CUSTOMER, 1, "table"); + assertEquals( + List.of("conceptid", "assetid", "assettype", "assetfqnhash", "columnbindings"), + columnNames(handle, dialect)); + + migrate(handle, dialect); + final var dao = handle.attach(CollectionDAO.class).ontologyConceptBindingDAO(); + dao.upsert(stored(CUSTOMER, 2, "identity", "[[\"tenant\"],[\"id\"]]")); + migrate(handle, dialect); + + assertEquals( + List.of( + "conceptid", + "assetid", + "assettype", + "assetfqnhash", + "columnbindings", + "bindingrole", + "subjectkey", + "rowfilter"), + columnNames(handle, dialect)); + final var older = dao.find(CUSTOMER, asset(1)); + assertNull(older.role()); + assertNull(older.subjectKey()); + assertNull(older.rowFilter()); + final var identity = dao.find(CUSTOMER, asset(2)); + assertEquals(OntologyBindingRole.IDENTITY, identity.role()); + assertEquals(List.of(List.of("tenant"), List.of("id")), identity.subjectKey()); + assertEquals(List.of("OPEN", 7, true), identity.rowFilter().getValue()); + assertEquals(asset(9), identity.columns().getFirst().getJoin().getTargetAssetId()); + }); + } + + /** The table as the 2.1.0 migration creates it, before 2.2.0 adds its three columns. */ + private static void createTableAsFirstShipped(final Handle handle, final ConnectionType dialect) { + final var migration = + repositoryRoot() + .resolve("bootstrap/sql/migrations/native/2.1.0") + .resolve(dialect == ConnectionType.MYSQL ? "mysql" : "postgres") + .resolve("schemaChanges.sql"); + MigrationFile.parseSQLFile(migration.toFile(), dialect).stream() + .filter( + statement -> + statement.contains("CREATE TABLE IF NOT EXISTS ontology_concept_binding (")) + .forEach(handle::execute); + } + + private static List columnNames(final Handle handle, final ConnectionType dialect) { + return handle + .createQuery( + "SELECT lower(column_name) FROM information_schema.columns" + + " WHERE table_name = 'ontology_concept_binding' AND table_schema = " + + (dialect == ConnectionType.MYSQL ? "DATABASE()" : "current_schema()") + + " ORDER BY ordinal_position") + .mapTo(String.class) + .list(); + } + + /** A table row with one relation column joined to asset 9 and a list row filter. */ + private static StoredBinding stored( + final UUID concept, final int asset, final String role, final String subjectKey) { + return new StoredBinding( + concept.toString(), + asset(asset).toString(), + "table", + "hash" + asset, + """ + [{"propertyId":"%s","columnPath":["customer_id"],"join":{"targetAssetId":"%s",\ + "status":"inferred","on":[{"child":["customer_id"],"parent":["id"]}]}}]\ + """ + .formatted(new UUID(0xb1, 0), asset(9)), + role, + subjectKey, + "{\"column\":[\"status\"],\"operator\":\"in\",\"value\":[\"OPEN\",7,true]}"); + } + private static void bind( final Handle handle, final UUID concept, final int asset, final String assetType) { handle.execute( diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyDeclinedDefinitionDaoIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyDeclinedDefinitionDaoIT.java new file mode 100644 index 000000000000..97f55354c29d --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyDeclinedDefinitionDaoIT.java @@ -0,0 +1,148 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.openmetadata.it.tests.ontology.OntologyTestDatabase.migrate; +import static org.openmetadata.it.tests.ontology.OntologyTestDatabase.withDatabase; + +import java.time.Clock; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.apache.commons.codec.digest.DigestUtils; +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.ScratchDatabase; +import org.openmetadata.schema.type.OntologyDeclinedDefinition; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionPage; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.OntologyDeclinedDefinitionDAO.StoredDeclinedDefinition; +import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.ontology.OntologyDeclinedDefinitions; + +@Execution(ExecutionMode.CONCURRENT) +class OntologyDeclinedDefinitionDaoIT { + private static final UUID ONTOLOGY = new UUID(0xb1, 0); + private static final UUID OTHER_ONTOLOGY = new UUID(0xb2, 0); + private static final String IRI = "https://example.org/sales/Order"; + + @Test + void theMigrationRunsTwiceAndLeavesTheRowsItHolds() { + final ConnectionType dialect = ScratchDatabase.dialect(); + withDatabase( + handle -> { + handle.execute("DROP TABLE IF EXISTS ontology_declined_definition"); + migrate(handle, dialect); + final var dao = handle.attach(CollectionDAO.class).ontologyDeclinedDefinitionDAO(); + dao.insertIfAbsent(row(ONTOLOGY, IRI, "a", 10L, "ana")); + + migrate(handle, dialect); + + assertEquals(1, dao.findByIriHashes(ONTOLOGY.toString(), List.of(hash(IRI))).size()); + }); + } + + @Test + void aDefinitionDeclinedTwiceKeepsItsFirstDecision() { + final ConnectionType dialect = ScratchDatabase.dialect(); + withDatabase( + handle -> { + handle.execute("DROP TABLE IF EXISTS ontology_declined_definition"); + migrate(handle, dialect); + final var dao = handle.attach(CollectionDAO.class).ontologyDeclinedDefinitionDAO(); + + dao.insertIfAbsent(row(ONTOLOGY, IRI, "a", 10L, "ana")); + dao.insertIfAbsent(row(ONTOLOGY, IRI, "a", 20L, "bo")); + dao.insertIfAbsent(row(ONTOLOGY, IRI, "b", 30L, "bo")); + dao.insertIfAbsent(row(OTHER_ONTOLOGY, IRI, "a", 40L, "bo")); + + final List found = + dao.findByIriHashes(ONTOLOGY.toString(), List.of(hash(IRI))); + assertEquals(2, found.size()); + final OntologyDeclinedDefinition first = + found.stream() + .filter(row -> row.getPayloadDigest().startsWith("a")) + .findFirst() + .get(); + assertEquals("ana", first.getDeclinedBy()); + assertEquals(10L, first.getDeclinedAt()); + assertNull(first.getReason()); + assertEquals(IRI, first.getIri().toString()); + }); + } + + @Test + void pagesRecordsInTheOrderTheyWereDeclinedEvenWhenTheyShareATime() { + final ConnectionType dialect = ScratchDatabase.dialect(); + withDatabase( + handle -> { + handle.execute("DROP TABLE IF EXISTS ontology_declined_definition"); + migrate(handle, dialect); + final var dao = handle.attach(CollectionDAO.class).ontologyDeclinedDefinitionDAO(); + for (int index = 0; index < 7; index++) { + dao.insertIfAbsent( + row(ONTOLOGY, IRI + index, "d" + index, index < 4 ? 100L : 200L + index, "ana")); + } + dao.insertIfAbsent(row(OTHER_ONTOLOGY, IRI, "z", 1L, "ana")); + final var declined = new OntologyDeclinedDefinitions(dao, Clock.systemUTC()); + + final List times = new ArrayList<>(); + final List digests = new ArrayList<>(); + int pages = 0; + String after = null; + do { + final OntologyDeclinedDefinitionPage page = declined.list(ONTOLOGY, 3, after); + page.getRecords() + .forEach( + record -> { + times.add(record.getDeclinedAt()); + digests.add(record.getPayloadDigest()); + }); + after = page.getAfter(); + pages++; + } while (after != null); + + assertEquals(3, pages); + assertEquals(List.of(100L, 100L, 100L, 100L, 205L, 206L, 207L).size(), times.size()); + assertEquals(times.stream().sorted().toList(), times); + assertEquals(7, digests.stream().distinct().count()); + }); + } + + private static StoredDeclinedDefinition row( + final UUID ontology, + final String iri, + final String digestPrefix, + final long declinedAt, + final String by) { + return new StoredDeclinedDefinition( + ontology.toString(), + "UPSERT_CONCEPT", + iri, + hash(iri), + digestPrefix + "0".repeat(63 - digestPrefix.length() + 1), + by, + declinedAt, + null, + new UUID(0xc1, 0).toString(), + UUID.randomUUID().toString()); + } + + private static String hash(final String iri) { + return DigestUtils.sha256Hex(iri); + } +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyReleaseCaptureIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyReleaseCaptureIT.java index 9dbf3d4d6ff3..50f75681653d 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyReleaseCaptureIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyReleaseCaptureIT.java @@ -467,7 +467,7 @@ void captureIncludesAllPagesAndRepeatCaptureReturnsTheSameRelease() { 101, fixture .releases - .listMembers(first.getId(), MemberKind.CONCEPT, 200, null) + .listViewableMembers(first.getId(), MemberKind.CONCEPT, 200, null, all -> all) .getData() .size()); assertEquals(first.getId(), second.getId()); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyTestDatabase.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyTestDatabase.java index cdb6c0775e24..c651aec921ea 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyTestDatabase.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ontology/OntologyTestDatabase.java @@ -142,16 +142,23 @@ private static void migrateTableColumns( public static void migrate(Handle handle, ConnectionType dialect) { migrateRepositoryTables(handle, dialect); + ontologyStatements(dialect, "2.1.0").stream() + .dropWhile(statement -> !statement.contains("CREATE TABLE IF NOT EXISTS ontology_entity (")) + .forEach(handle::execute); + ontologyStatements(dialect, "2.2.0").forEach(handle::execute); + } + + /** Only ontology statements: the rest of a version's file needs tables this database lacks. */ + private static List ontologyStatements(ConnectionType dialect, String version) { Path migration = repositoryRoot() - .resolve("bootstrap/sql/migrations/native/2.1.0") + .resolve("bootstrap/sql/migrations/native") + .resolve(version) .resolve(dialect == ConnectionType.MYSQL ? "mysql" : "postgres") .resolve("schemaChanges.sql"); - // Only ontology statements: the rest of the file needs tables this database lacks. - MigrationFile.parseSQLFile(migration.toFile(), dialect).stream() - .dropWhile(statement -> !statement.contains("CREATE TABLE IF NOT EXISTS ontology_entity (")) + return MigrationFile.parseSQLFile(migration.toFile(), dialect).stream() .filter(statement -> statement.toLowerCase(Locale.ROOT).contains("ontology")) - .forEach(handle::execute); + .toList(); } public static Path repositoryRoot() { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/service/jdbi3/OntologyServedBindingsStorageIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/service/jdbi3/OntologyServedBindingsStorageIT.java index 426ad6c65969..76eea806c2ea 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/service/jdbi3/OntologyServedBindingsStorageIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/service/jdbi3/OntologyServedBindingsStorageIT.java @@ -36,6 +36,7 @@ import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BoundAsset; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.StoredBinding; import org.openmetadata.service.jdbi3.locator.ConnectionType; import org.openmetadata.service.ontology.OntologyConceptBindingService; import org.openmetadata.service.rdf.RdfLiveWrite; @@ -275,6 +276,14 @@ private static void bind( Entity.getCollectionDAO() .ontologyConceptBindingDAO() .upsert( - concept.getId(), asset, type.value(), "hash" + asset, JsonUtils.pojoToJson(columns)); + new StoredBinding( + concept.getId().toString(), + asset.toString(), + type.value(), + "hash" + asset, + JsonUtils.pojoToJson(columns), + null, + null, + null)); } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcileAccess.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcileAccess.java new file mode 100644 index 000000000000..59ea3699eb74 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcileAccess.java @@ -0,0 +1,40 @@ +/* + * 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.ontology; + +import java.util.UUID; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.TaskRepository; + +/** + * Lets an integration test run the reconcile of shape checks outside the queue of this server, as + * the queue of a second server would, and close a suggestion task the way a person who cancels it + * does. + */ +public final class OntologyCheckReconcileAccess { + private OntologyCheckReconcileAccess() {} + + /** One run over every class of the ontology, made by the calling thread. */ + public static OntologyCheckReconciler.Outcome runAsAnotherServer(final UUID ontologyId) { + return new OntologyCheckReconciler(Entity.getCollectionDAO(), Entity.getAuthorizer()) + .run(ontologyId, OntologyCheckReconciler.Scope.everything(), "admin"); + } + + public static void cancel(final UUID taskId) { + final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); + final Task task = tasks.get(null, taskId, tasks.getFields("*")); + tasks.closeTaskAndCancelWorkflowRun(task, "admin", "Cancelled by a test"); + } +} diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CommonUtils.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CommonUtils.java index 9549280cbbf0..3a998bfcb2dd 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CommonUtils.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/CommonUtils.java @@ -11,6 +11,7 @@ import org.openmetadata.schema.CreateEntity; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.entity.context.ContextMemory; +import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.entity.teams.Team; import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.type.EntityReference; @@ -22,6 +23,8 @@ import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.jdbi3.TeamRepository; import org.openmetadata.service.jdbi3.UserRepository; +import org.openmetadata.service.ontology.OntologyChangeEvidenceView; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.resources.context.ContextMemoryDocumentAccess; import org.openmetadata.service.resources.context.ContextMemoryEvidenceAccess; import org.openmetadata.service.resources.context.ContextMemoryVisibility; @@ -92,7 +95,9 @@ private static EntityInterface readVisibleEntity( /** * Returns {@code entity} as the caller may read it: a context memory's references to Queries the * caller cannot view keep only their id and type, as in every REST memory response ({@link - * ContextMemoryEvidenceAccess}); a metric's or metric group's relations keep only the entities + * ContextMemoryEvidenceAccess}); the operations of an ontology change set keep only the evidence + * about tables the caller may view, as in every REST change set response ({@link + * OntologyChangeEvidenceView}); a metric's or metric group's relations keep only the entities * the caller may view ({@link MetricRelationVisibility}); every other entity type is returned as * is. Applied where a tool answers with the entity, not on reads it only checks. */ @@ -104,6 +109,10 @@ public static EntityInterface withVisibleEvidence( ContextMemoryDocumentAccess.redactDocuments(List.of(copy), securityContext); return copy; } + if (entity instanceof OntologyChangeSet changeSet) { + return OntologyChangeEvidenceView.of(authorizer, new Access(null, securityContext)) + .apply(JsonUtils.deepCopy(changeSet, OntologyChangeSet.class)); + } return MetricRelationVisibility.visibleTo(entity, authorizer, securityContext); } diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java index 24b57e5ecbdd..04d136729834 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/GetEntityTool.java @@ -37,6 +37,7 @@ import org.openmetadata.service.jdbi3.LineageRepository; import org.openmetadata.service.limits.Limits; import org.openmetadata.service.lineage.LineagePermissionFilter; +import org.openmetadata.service.ontology.OntologyChangeSetReadAccess; import org.openmetadata.service.search.vector.PageBodyTextContributor; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.auth.CatalogSecurityContext; @@ -354,6 +355,7 @@ private Map readOne( String fqn) { List includes = McpParams.getStringList(params, INCLUDE_PARAM).stream().distinct().toList(); + requireDraftRead(authorizer, securityContext, entityType, fqn); return includes.size() == 1 && includes.contains(INCLUDE_CONTENT) ? readContentOnly(authorizer, securityContext, params, entityType, fqn) : readFullDetails(authorizer, securityContext, params, entityType, fqn, includes); @@ -408,6 +410,24 @@ private Map readFullDetails( return windowed; } + /** + * A change set holds operations no release has published, so it is read with the right that + * edits its scope, as the REST resource does, whatever sections the call asks for. + */ + private static void requireDraftRead( + Authorizer authorizer, + CatalogSecurityContext securityContext, + String entityType, + String fqn) { + if (Entity.ONTOLOGY_CHANGE_SET.equals(entityType)) { + OntologyChangeSetReadAccess.requireRead( + authorizer, + securityContext, + Entity.getEntityByName( + entityType, fqn, OntologyChangeSetReadAccess.SCOPE_FIELDS, Include.ALL)); + } + } + private static Map readContentOnly( Authorizer authorizer, CatalogSecurityContext securityContext, diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/PatchEntityTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/PatchEntityTool.java index 6dd055e14f2b..534317828adb 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/PatchEntityTool.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/PatchEntityTool.java @@ -65,6 +65,8 @@ public class PatchEntityTool implements McpTool { // ingestionPipeline secret decryptOrNullify on the response // intakeForm authorizeAdmin // notificationTemplate provider-aware EDIT_ALL authorization + // ontologyChangeSet edit lease and scope authorization, and evidence shown per reader, + // which a copy, move or test would read; its resource has no PATCH // persona authorizeAdmin // testCase table-or-testCase authorization, sample cleanup // testSuite getAuthRequestsForUpdate authorization @@ -83,6 +85,7 @@ public class PatchEntityTool implements McpTool { Entity.INGESTION_PIPELINE, Entity.INTAKE_FORM, Entity.NOTIFICATION_TEMPLATE, + Entity.ONTOLOGY_CHANGE_SET, Entity.PERSONA, Entity.TEST_CASE, Entity.TEST_SUITE, @@ -157,6 +160,14 @@ private static void requireTarget(String entityType, String fqn) { } private static void requireGenericPatchLifecycle(String entityType) { + if (Entity.ONTOLOGY_CHANGE_SET.equals(entityType)) { + throw new IllegalArgumentException( + "entityType '" + + entityType + + "' cannot be patched through patch_entity because a change set is saved whole," + + " with its edit lease and the evidence each reader may see. A change set has no" + + " PATCH endpoint. Nothing was changed."); + } if (DEDICATED_PATCH_LIFECYCLES.contains(entityType)) { throw new IllegalArgumentException( "entityType '" diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/PatchEntityToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/PatchEntityToolTest.java index 19ce58ec6996..467f5105ee0e 100644 --- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/PatchEntityToolTest.java +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/PatchEntityToolTest.java @@ -405,6 +405,21 @@ void execute_rejectsEntitiesWhoseResourceOwnsThePatchLifecycle(String entityType verifyNoInteractions(authorizer); } + @Test + void execute_refusesAChangeSetWithoutNamingAnEndpointItLacks() { + Map params = new HashMap<>(); + params.put("entityType", "ontologyChangeSet"); + params.put("fqn", "target"); + params.put("patch", "[]"); + + assertThatThrownBy(() -> new PatchEntityTool().execute(authorizer, securityContext, params)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("A change set has no PATCH endpoint") + .hasMessageNotContaining("dedicated OpenMetadata REST PATCH API") + .hasMessageContaining("Nothing was changed"); + verifyNoInteractions(authorizer); + } + @Test void execute_rejectsTimeSeriesEntitiesBeforeAuthorization() { Map params = new HashMap<>(); diff --git a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/client/OpenMetadataClient.java b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/client/OpenMetadataClient.java index 3a681d3808fd..801023d57a50 100644 --- a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/client/OpenMetadataClient.java +++ b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/client/OpenMetadataClient.java @@ -57,6 +57,7 @@ import org.openmetadata.sdk.services.ontology.OntologyBulkService; import org.openmetadata.sdk.services.ontology.OntologyChangeSetService; import org.openmetadata.sdk.services.ontology.OntologyConceptService; +import org.openmetadata.sdk.services.ontology.OntologyDeclinedDefinitionService; import org.openmetadata.sdk.services.ontology.OntologyEditLockService; import org.openmetadata.sdk.services.ontology.OntologyImpactService; import org.openmetadata.sdk.services.ontology.OntologyPackService; @@ -65,6 +66,7 @@ import org.openmetadata.sdk.services.ontology.OntologyReasoningService; import org.openmetadata.sdk.services.ontology.OntologyReleaseService; import org.openmetadata.sdk.services.ontology.OntologyService; +import org.openmetadata.sdk.services.ontology.OntologyShapeService; import org.openmetadata.sdk.services.ontology.RelationshipTypeService; import org.openmetadata.sdk.services.policies.PolicyService; import org.openmetadata.sdk.services.search.SearchAPI; @@ -146,6 +148,7 @@ public class OpenMetadataClient { // Ontology private final RelationshipTypeService relationshipTypes; private final OntologyAxiomService ontologyAxioms; + private final OntologyShapeService ontologyShapes; private final OntologyService ontologies; private final OntologyConceptService ontologyConcepts; private final OntologyPropertyService ontologyProperties; @@ -153,6 +156,7 @@ public class OpenMetadataClient { private final OntologyAiService ontologyAi; private final OntologyBulkService ontologyBulk; private final OntologyChangeSetService ontologyChangeSets; + private final OntologyDeclinedDefinitionService ontologyDeclinedDefinitions; private final OntologyEditLockService ontologyEditLocks; private final OntologyImpactService ontologyImpacts; private final InferenceRuleService inferenceRules; @@ -291,6 +295,7 @@ public OpenMetadataClient(OpenMetadataConfig config) { // Initialize Ontology services this.relationshipTypes = new RelationshipTypeService(httpClient); this.ontologyAxioms = new OntologyAxiomService(httpClient); + this.ontologyShapes = new OntologyShapeService(httpClient); this.ontologies = new OntologyService(httpClient); this.ontologyConcepts = new OntologyConceptService(httpClient); this.ontologyProperties = new OntologyPropertyService(httpClient); @@ -298,6 +303,7 @@ public OpenMetadataClient(OpenMetadataConfig config) { this.ontologyAi = new OntologyAiService(httpClient); this.ontologyBulk = new OntologyBulkService(httpClient); this.ontologyChangeSets = new OntologyChangeSetService(httpClient); + this.ontologyDeclinedDefinitions = new OntologyDeclinedDefinitionService(httpClient); this.ontologyEditLocks = new OntologyEditLockService(httpClient); this.ontologyImpacts = new OntologyImpactService(httpClient); this.inferenceRules = new InferenceRuleService(httpClient); @@ -512,6 +518,10 @@ public OntologyAxiomService ontologyAxioms() { return ontologyAxioms; } + public OntologyShapeService ontologyShapes() { + return ontologyShapes; + } + public OntologyService ontologies() { return ontologies; } @@ -540,6 +550,10 @@ public OntologyChangeSetService ontologyChangeSets() { return ontologyChangeSets; } + public OntologyDeclinedDefinitionService ontologyDeclinedDefinitions() { + return ontologyDeclinedDefinitions; + } + public OntologyEditLockService ontologyEditLocks() { return ontologyEditLocks; } diff --git a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/ontology/OntologyDeclinedDefinitionService.java b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/ontology/OntologyDeclinedDefinitionService.java new file mode 100644 index 000000000000..7333fe735272 --- /dev/null +++ b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/ontology/OntologyDeclinedDefinitionService.java @@ -0,0 +1,71 @@ +/* + * 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.sdk.services.ontology; + +import java.util.UUID; +import org.openmetadata.schema.api.data.DeclineOntologyDefinitions; +import org.openmetadata.schema.api.data.MatchOntologyDeclinedDefinitions; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionMatches; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionPage; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; + +/** Typed SDK client for the definitions declined for an ontology. */ +public final class OntologyDeclinedDefinitionService { + private final HttpClient httpClient; + + public OntologyDeclinedDefinitionService(final HttpClient httpClient) { + this.httpClient = httpClient; + } + + public OntologyDeclinedDefinitionPage decline( + final UUID ontologyId, final DeclineOntologyDefinitions request) + throws OpenMetadataException { + return httpClient.execute( + HttpMethod.POST, path(ontologyId), request, OntologyDeclinedDefinitionPage.class); + } + + public OntologyDeclinedDefinitionPage list( + final UUID ontologyId, final Integer limit, final String after) throws OpenMetadataException { + final RequestOptions.Builder options = RequestOptions.builder(); + if (limit != null) { + options.queryParam("limit", String.valueOf(limit)); + } + if (after != null) { + options.queryParam("after", after); + } + return httpClient.execute( + HttpMethod.GET, + path(ontologyId), + null, + OntologyDeclinedDefinitionPage.class, + options.build()); + } + + public OntologyDeclinedDefinitionMatches match( + final UUID ontologyId, final MatchOntologyDeclinedDefinitions request) + throws OpenMetadataException { + return httpClient.execute( + HttpMethod.POST, + path(ontologyId) + "/match", + request, + OntologyDeclinedDefinitionMatches.class); + } + + private static String path(final UUID ontologyId) { + return "/v1/ontologies/" + ontologyId + "/declinedDefinitions"; + } +} diff --git a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/ontology/OntologyShapeService.java b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/ontology/OntologyShapeService.java new file mode 100644 index 000000000000..f3b7ab56bd85 --- /dev/null +++ b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/ontology/OntologyShapeService.java @@ -0,0 +1,49 @@ +/* + * 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.sdk.services.ontology; + +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.data.ImportOntologyShapes; +import org.openmetadata.schema.api.data.OntologyShapeImportResult; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.services.EntityServiceBase; + +/** Typed SDK client for ontology shapes and their SHACL import. */ +public final class OntologyShapeService extends EntityServiceBase { + public OntologyShapeService(final HttpClient httpClient) { + super(httpClient, "/v1/ontologyShapes"); + } + + public OntologyShape create(final CreateOntologyShape request) throws OpenMetadataException { + return httpClient.execute(HttpMethod.POST, basePath, request, OntologyShape.class); + } + + public OntologyShape upsert(final CreateOntologyShape request) throws OpenMetadataException { + return httpClient.execute(HttpMethod.PUT, basePath, request, OntologyShape.class); + } + + public OntologyShapeImportResult importShapes(final ImportOntologyShapes request) + throws OpenMetadataException { + return httpClient.execute( + HttpMethod.POST, basePath + "/import", request, OntologyShapeImportResult.class); + } + + @Override + protected Class getEntityClass() { + return OntologyShape.class; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/Entity.java b/openmetadata-service/src/main/java/org/openmetadata/service/Entity.java index dee493cb8b03..6e7eafdf5b7b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/Entity.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/Entity.java @@ -225,6 +225,7 @@ public final class Entity { public static final String ONTOLOGY_PROPERTY = "ontologyProperty"; public static final String ONTOLOGY_RELEASE = "ontologyRelease"; public static final String ONTOLOGY_AXIOM = "ontologyAxiom"; + public static final String ONTOLOGY_SHAPE = "ontologyShape"; public static final String ONTOLOGY_CHANGE_SET = "ontologyChangeSet"; public static final String TAG = "tag"; public static final String CLASSIFICATION = "classification"; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/AbstractNativeApplication.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/AbstractNativeApplication.java index 6a0f3d41fae1..a33ee0daefb3 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/AbstractNativeApplication.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/AbstractNativeApplication.java @@ -142,6 +142,14 @@ protected void validateConfig(Map config) { LOG.warn("validateConfig is not implemented for this application. Skipping validation."); } + /** + * Check the configuration the server is about to store for this application. It reads only the + * configuration and has no side effect, so the server can call it on an instance that was never + * initialized. It is separate from {@link #validateConfig}, which an application may also use to + * refuse a run because of the server's state. By default every configuration is accepted. + */ + public void validateConfigForSave(Map config) {} + public void scheduleInternal() { // Validate Native Application AppRuntime runtime = JsonUtils.convertValue(app.getRuntime(), ScheduledExecutionContext.class); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationHandler.java index 0b798afb433e..026a8b8a55e4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/ApplicationHandler.java @@ -10,8 +10,10 @@ import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Collection; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.api.configuration.apps.AppPrivateConfig; @@ -184,6 +186,62 @@ public AbstractNativeApplication initializeApplicationForTrigger( } } + /** + * Ask the application to check the configuration that is about to be stored. The instance comes + * from its constructor alone: {@code init} registers the app in the application context and the + * install steps schedule it, and neither must happen for a configuration that may be refused. An + * application that inherits the default check is not built, because that check accepts every + * configuration. + */ + public void validateConfigurationForSave( + App app, CollectionDAO daoCollection, SearchRepository searchRepository) { + try { + Optional> nativeClass = + findNativeApplicationClass(app.getClassName()) + .filter(ApplicationHandler::declaresOwnSaveCheck); + if (nativeClass.isPresent()) { + nativeClass + .get() + .getDeclaredConstructor(CollectionDAO.class, SearchRepository.class) + .newInstance(daoCollection, searchRepository) + .validateConfigForSave(configurationAsMap(app)); + } + } catch (NoSuchMethodException + | InvocationTargetException + | InstantiationException + | IllegalAccessException e) { + LOG.error("Failed to check the configuration of application {}", app.getName(), e); + throw AppException.byMessage( + app.getName(), "validateConfig", e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR); + } + } + + private static Optional> findNativeApplicationClass( + String className) { + try { + Class clz = Class.forName(className); + return AbstractNativeApplication.class.isAssignableFrom(clz) + ? Optional.of(clz.asSubclass(AbstractNativeApplication.class)) + : Optional.empty(); + } catch (ClassNotFoundException e) { + return Optional.empty(); + } + } + + private static boolean declaresOwnSaveCheck(Class clz) { + try { + return clz.getMethod("validateConfigForSave", Map.class).getDeclaringClass() + != AbstractNativeApplication.class; + } catch (NoSuchMethodException e) { + throw new IllegalStateException(e); + } + } + + private static Map configurationAsMap(App app) { + Map configuration = JsonUtils.getMap(app.getAppConfiguration()); + return configuration == null ? new HashMap<>() : configuration; + } + public void installApplication( App app, CollectionDAO daoCollection, SearchRepository searchRepository, String installedBy) { try { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/cache/CacheWarmupApp.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/cache/CacheWarmupApp.java index 6b374c7dd33e..6ad6a50ccb57 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/cache/CacheWarmupApp.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/cache/CacheWarmupApp.java @@ -852,6 +852,11 @@ public void stop() { @Override protected void validateConfig(Map appConfig) { + validateConfigForSave(appConfig); + } + + @Override + public void validateConfigForSave(Map appConfig) { try { normalizeAppConfig(appConfig); } catch (IllegalArgumentException e) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/DataInsightsReportApp.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/DataInsightsReportApp.java index 664da68a633e..fff503562b8c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/DataInsightsReportApp.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/insights/DataInsightsReportApp.java @@ -107,6 +107,11 @@ public void execute(JobExecutionContext jobExecutionContext) { @Override protected void validateConfig(Map config) { + validateConfigForSave(config); + } + + @Override + public void validateConfigForSave(Map config) { try { JsonUtils.convertValue(config, DataInsightsReportAppConfig.class); } catch (IllegalArgumentException e) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/rdf/RdfIndexApp.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/rdf/RdfIndexApp.java index 8808de2cab33..bee3920df401 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/rdf/RdfIndexApp.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/rdf/RdfIndexApp.java @@ -1116,6 +1116,11 @@ public void stop() { @Override protected void validateConfig(Map appConfig) { + validateConfigForSave(appConfig); + } + + @Override + public void validateConfigForSave(Map appConfig) { try { JsonUtils.convertValue(appConfig, EventPublisherJob.class); } catch (IllegalArgumentException e) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/SearchIndexApp.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/SearchIndexApp.java index 44daa1d9fe35..b5257745b180 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/SearchIndexApp.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/SearchIndexApp.java @@ -179,6 +179,11 @@ private void purgeSearchIndexTables() { @Override protected void validateConfig(Map appConfig) { + validateConfigForSave(appConfig); + } + + @Override + public void validateConfigForSave(Map appConfig) { try { JsonUtils.convertValue( SearchIndexAppConfigSanitizer.copyWithoutRemovedOptions(appConfig), diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java index 81f8f734ac54..81e714eef580 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/audit/AuditLogRepository.java @@ -363,7 +363,8 @@ public int streamExportAsJson( eventType, startTs, endTs, - searchTerm), + searchTerm, + null), totalLimit, userName, actorType, @@ -409,7 +410,8 @@ public int streamExportAsJson( null, // before afterCursor, false, // skip the count — it would re-run once per batch - readsUserEmails); + readsUserEmails, + null); if (batch.getData().isEmpty()) { break; @@ -492,6 +494,43 @@ public ResultList list( String before, String after, boolean readsUserEmails) { + return list( + userName, + actorType, + serviceName, + entityType, + entityFqn, + eventType, + startTs, + endTs, + searchTerm, + limitParam, + before, + after, + readsUserEmails, + null); + } + + /** + * As above, limited to the rows of one entity when {@code entityId} is set. A name can be held by + * an entity that no longer exists and by another that took it, and the rows of the two are not + * the same reader's to see. + */ + public ResultList list( + String userName, + String actorType, + String serviceName, + String entityType, + String entityFqn, + String eventType, + Long startTs, + Long endTs, + String searchTerm, + int limitParam, + String before, + String after, + boolean readsUserEmails, + UUID entityId) { return list( userName, actorType, @@ -506,7 +545,8 @@ public ResultList list( before, after, true, - readsUserEmails); + readsUserEmails, + entityId); } private ResultList list( @@ -523,7 +563,8 @@ private ResultList list( String before, String after, boolean countTotal, - boolean readsUserEmails) { + boolean readsUserEmails, + UUID entityId) { RestUtil.validateCursors(before, after); int limit = Math.max(1, limitParam); @@ -542,7 +583,8 @@ private ResultList list( eventType, startTs, endTs, - searchTerm); + searchTerm, + entityId); List records; boolean isBackward = beforeCursor != null; @@ -900,7 +942,8 @@ private String buildBaseCondition( String eventType, Long startTs, Long endTs, - String searchTerm) { + String searchTerm, + UUID entityId) { StringBuilder condition = new StringBuilder("WHERE 1 = 1"); appendEq(condition, userName, "user_name", "userName"); appendEq(condition, actorType, "actor_type", "actorType"); @@ -909,6 +952,7 @@ private String buildBaseCondition( // entity_fqn has no index; its hash does, and the write path always populates both together. appendEq(condition, entityFqnHash, "entity_fqn_hash", "entityFQNHASH"); appendEq(condition, eventType, "event_type", "eventType"); + appendEntityId(condition, entityId); if (startTs != null) { condition.append(" AND event_ts >= :startTs"); } @@ -927,6 +971,16 @@ private String buildBaseCondition( return condition.toString(); } + /** + * The id is a {@link UUID}, so the literal holds only hex digits and dashes. The row filter binds + * no parameter because the listing and its count take a fixed set of them. + */ + private void appendEntityId(StringBuilder condition, UUID entityId) { + if (entityId != null) { + condition.append(" AND entity_id = '").append(entityId).append("'"); + } + } + private void appendEq(StringBuilder condition, String value, String column, String param) { if (!nullOrEmpty(value)) { condition.append(" AND ").append(column).append(" = :").append(param); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java b/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java index 6d7f22b8986a..b720b637430f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java @@ -17,9 +17,11 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.io.UncheckedIOException; +import java.util.List; import java.util.Optional; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; @@ -28,7 +30,8 @@ /** * What a change event is stored as. The entity it carries leaves out every field its schema marks * {@code "mask": true}, such as bot tokens, password hashes and connection secrets, whichever code - * made the event and whether it holds the entity as an object or as a string of JSON. Every alert, + * made the event and whether it holds the entity as an object or as a string of JSON. Its recorded + * field changes of a field that is masked as a whole keep the name and leave out the values. Every alert, * the audit log and {@code GET /v1/events} read the stored event. */ public final class ChangeEventMasking { @@ -36,6 +39,11 @@ public final class ChangeEventMasking { private static final JsonFactory JSON_FACTORY = new JsonFactory(); private static final String ENTITY = "entity"; private static final String ENTITY_TYPE = "entityType"; + // The event records the change, and the entity it carries records the change that made it. + private static final List CHANGE_DESCRIPTIONS = + List.of("changeDescription", "incrementalChangeDescription"); + private static final List FIELD_CHANGE_LISTS = + List.of("fieldsAdded", "fieldsUpdated", "fieldsDeleted"); private ChangeEventMasking() {} @@ -43,12 +51,18 @@ public static String masked(final String changeEventJson) { return entityTypeOf(changeEventJson) .map(Entity::getEntityClassFromType) .filter(MaskedFields::anyIn) - .map(entityClass -> withMaskedEntity(changeEventJson, entityClass)) + .map(entityClass -> withMaskedEvent(changeEventJson, entityClass)) .orElse(changeEventJson); } - private static String withMaskedEntity(final String changeEventJson, final Class entityClass) { + private static String withMaskedEvent(final String changeEventJson, final Class entityClass) { final ObjectNode event = (ObjectNode) JsonUtils.readTree(changeEventJson); + final boolean isEntityMasked = maskEntity(event, entityClass); + final boolean isChangeStripped = stripMaskedFieldValues(event, entityClass); + return isEntityMasked || isChangeStripped ? JsonUtils.pojoToJson(event) : changeEventJson; + } + + private static boolean maskEntity(final ObjectNode event, final Class entityClass) { final JsonNode entity = event.path(ENTITY); final boolean isPresent = !entity.isMissingNode() && !entity.isNull(); if (isPresent) { @@ -56,9 +70,48 @@ private static String withMaskedEntity(final String changeEventJson, final Class entity.isTextual() ? JsonUtils.readValueLenient(entity.asText(), entityClass) : JsonUtils.convertValueLenient(entity, entityClass); - event.put(ENTITY, JsonUtils.pojoToMaskedJson(typed)); + final ObjectNode masked = (ObjectNode) JsonUtils.readTree(JsonUtils.pojoToMaskedJson(typed)); + stripMaskedFieldValues(masked, entityClass); + event.put(ENTITY, masked.toString()); + } + return isPresent; + } + + /** + * A recorded field change holds the old and the new value of a field, so a change of a field + * that is masked as a whole keeps its name and loses both values, in the event and in the entity + * it carries. The stored event still records that the field changed, so an alert or a workflow + * trigger that filters on a field name keeps matching, and nothing in it holds the values. + */ + private static boolean stripMaskedFieldValues( + final ObjectNode holder, final Class entityClass) { + final List masked = MaskedFields.wholeFieldsOf(entityClass); + boolean isStripped = false; + for (final String description : CHANGE_DESCRIPTIONS) { + for (final String kind : FIELD_CHANGE_LISTS) { + if (!masked.isEmpty() && holder.path(description).path(kind) instanceof ArrayNode changes) { + isStripped |= removeValuesOf(changes, masked); + } + } } - return isPresent ? JsonUtils.pojoToJson(event) : changeEventJson; + return isStripped; + } + + private static boolean removeValuesOf(final ArrayNode changes, final List masked) { + boolean isStripped = false; + for (final JsonNode change : changes) { + if (change instanceof ObjectNode fieldChange + && isChangeOf(masked, fieldChange.path("name").asText())) { + isStripped |= fieldChange.remove(List.of("oldValue", "newValue")).size() > 0; + } + } + return isStripped; + } + + // A change names a field or a path inside it, such as "authenticationMechanism.config". + private static boolean isChangeOf(final List maskedFields, final String changedField) { + return maskedFields.stream() + .anyMatch(field -> changedField.equals(field) || changedField.startsWith(field + ".")); } // entityType comes early in a stored event, so this reads a few tokens, not the whole event. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ApprovalGate.java b/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ApprovalGate.java index 9fa95552881c..b09d0bc00581 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ApprovalGate.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/governance/approval/ApprovalGate.java @@ -95,6 +95,7 @@ public final class ApprovalGate { Entity.ONTOLOGY_CONCEPT, Entity.ONTOLOGY_PROPERTY, Entity.ONTOLOGY_AXIOM, + Entity.ONTOLOGY_SHAPE, Entity.ONTOLOGY_RELEASE); private ApprovalGate() {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java index 62ef824af32c..cb3fcaccef07 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java @@ -393,32 +393,48 @@ private void postCreateOrUpdate(DataContract dataContract) { } // Create the ingestion pipeline only if needed if (testSuite != null && nullOrEmpty(testSuite.getPipelines())) { - IngestionPipeline pipeline = createIngestionPipeline(testSuite); - EntityReference pipelineRef = - Entity.getEntityReference( - new EntityReference().withId(pipeline.getId()).withType(Entity.INGESTION_PIPELINE), - Include.NON_DELETED); - testSuite.setPipelines(List.of(pipelineRef)); - TestSuiteRepository testSuiteRepository = - (TestSuiteRepository) Entity.getEntityRepository(Entity.TEST_SUITE); - testSuiteRepository.createOrUpdate(null, testSuite, ADMIN_USER_NAME); - if (!pipeline.getDeployed()) { - // Deploy is best-effort at creation time: a pipeline-service outage or misconfiguration - // must not block contract creation nor lose the reverse relationship written above. - // The user can re-deploy via /validate later. - try { - prepareAndDeployIngestionPipeline(pipeline, testSuite); - } catch (RuntimeException e) { - // Narrow to RuntimeException: deployPipeline throws - // IngestionPipelineDeploymentException (WebServiceException) on transport failures - // and NPE when the pipeline client is not wired (test harness). Both are recoverable - // at /validate time. Checked exceptions still propagate. - LOG.warn( - "Failed to deploy DQ pipeline for data contract {}: {}", - dataContract.getFullyQualifiedName(), - e.getMessage()); - } - } + attachPipeline(testSuite, new AirflowConfig(), dataContract.getFullyQualifiedName()); + } + } + } + + /** + * Gives a test suite that has no pipeline one that runs on {@code scheduleInterval}, a cron + * expression, and deploys it. Deploying is best-effort, as for a data contract, and this path + * runs in the repository, so the limits that a resource enforces on a request to create a + * pipeline do not apply to it. A suite that has a pipeline is left as it is. + */ + public void ensureScheduledPipeline(TestSuite testSuite, String scheduleInterval) { + if (nullOrEmpty(testSuite.getPipelines())) { + attachPipeline( + testSuite, + new AirflowConfig().withScheduleInterval(scheduleInterval), + testSuite.getFullyQualifiedName()); + } + } + + private void attachPipeline(TestSuite testSuite, AirflowConfig schedule, String owner) { + IngestionPipeline pipeline = createIngestionPipeline(testSuite, schedule); + EntityReference pipelineRef = + Entity.getEntityReference( + new EntityReference().withId(pipeline.getId()).withType(Entity.INGESTION_PIPELINE), + Include.NON_DELETED); + testSuite.setPipelines(List.of(pipelineRef)); + TestSuiteRepository testSuiteRepository = + (TestSuiteRepository) Entity.getEntityRepository(Entity.TEST_SUITE); + testSuiteRepository.createOrUpdate(null, testSuite, ADMIN_USER_NAME); + if (!pipeline.getDeployed()) { + // Deploy is best-effort at creation time: a pipeline-service outage or misconfiguration + // must not block the write that asked for the pipeline, nor lose the reverse relationship + // a data contract wrote before it. A data contract can re-deploy via /validate later. + try { + prepareAndDeployIngestionPipeline(pipeline, testSuite); + } catch (RuntimeException e) { + // Narrow to RuntimeException: deployPipeline throws + // IngestionPipelineDeploymentException (WebServiceException) on transport failures + // and NPE when the pipeline client is not wired (test harness). Both are recoverable + // at /validate time. Checked exceptions still propagate. + LOG.warn("Failed to deploy DQ pipeline for {}: {}", owner, e.getMessage()); } } } @@ -1030,8 +1046,18 @@ private Boolean contractHasTestSuite(DataContract dataContract) { return dataContract.getTestSuite() != null; } + /** A basic suite tests one entity, which its pipeline names. */ + private static TestSuitePipeline testSuitePipeline(TestSuite testSuite) { + TestSuitePipeline config = new TestSuitePipeline(); + if (Boolean.TRUE.equals(testSuite.getBasic()) && testSuite.getBasicEntityReference() != null) { + config.setEntityFullyQualifiedName( + testSuite.getBasicEntityReference().getFullyQualifiedName()); + } + return config; + } + // Prepare the Ingestion Pipeline from the test suite that will handle the execution - private IngestionPipeline createIngestionPipeline(TestSuite testSuite) { + private IngestionPipeline createIngestionPipeline(TestSuite testSuite, AirflowConfig schedule) { IngestionPipelineRepository pipelineRepository = (IngestionPipelineRepository) Entity.getEntityRepository(Entity.INGESTION_PIPELINE); @@ -1042,9 +1068,9 @@ private IngestionPipeline createIngestionPipeline(TestSuite testSuite) { .withPipelineType(PipelineType.TEST_SUITE) .withService( new EntityReference().withId(testSuite.getId()).withType(Entity.TEST_SUITE)) - .withSourceConfig(new SourceConfig().withConfig(new TestSuitePipeline())) + .withSourceConfig(new SourceConfig().withConfig(testSuitePipeline(testSuite))) .withLoggerLevel(LogLevels.INFO) - .withAirflowConfig(new AirflowConfig()); + .withAirflowConfig(schedule); IngestionPipeline pipeline = ingestionPipelineMapper.createToEntity(createPipeline, ADMIN_USER_NAME); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java index 845400159a9b..9779186defce 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java @@ -7375,6 +7375,15 @@ protected List getFieldsHiddenFromHistory() { return Collections.emptyList(); } + /** + * Fields its schema masks that its versions still hold. A mask keeps a field out of change + * events. A version is read through the entity's own endpoints, which decide who may read it, so + * an entity whose masked field is its content, such as the operations of a draft, keeps it there. + */ + protected List getMaskedFieldsShownInHistory() { + return Collections.emptyList(); + } + /** Stores each entity as the version it was before an update. The only writer of versions. */ protected final void storeVersions(final List originals) { storeVersions(versionRows(originals)); @@ -7424,6 +7433,7 @@ final String serializeForVersionHistory(final T entity) { */ private List fieldsHiddenFromHistory() { final List hidden = new ArrayList<>(MaskedFields.wholeFieldsOf(entityClass)); + hidden.removeAll(getMaskedFieldsShownInHistory()); hidden.addAll(getFieldsHiddenFromHistory()); return hidden; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java index c08984f794f7..f8df5ba93321 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/FeedDAOs.java @@ -144,6 +144,18 @@ default void insert(org.openmetadata.schema.EntityInterface entity, String fq insertTask(task.getId().toString(), JsonUtils.pojoToJson(task), task.getFullyQualifiedName()); } + /** + * The ids of the suggestion tasks that propose a test case, closed ones included. Reads the + * index on {@code testCaseClassId}, which is the class named by the proposal and is empty for + * every other task. + */ + @SqlQuery("SELECT id FROM task_entity WHERE testCaseClassId IS NOT NULL") + List findTestCaseSuggestionIds(); + + /** The ids of the suggestion tasks that propose a test case generated for the class. */ + @SqlQuery("SELECT id FROM task_entity WHERE testCaseClassId = :classId") + List findTestCaseSuggestionIdsOfClass(@Bind("classId") String classId); + @ConnectionAwareSqlUpdate( value = "UPDATE task_entity SET json = :json WHERE id = :id", connectionType = MYSQL) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GeneratedTestScope.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GeneratedTestScope.java new file mode 100644 index 000000000000..51e468130865 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/GeneratedTestScope.java @@ -0,0 +1,107 @@ +/* + * 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.jdbi3; + +import java.util.Objects; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.service.exception.BadRequestException; + +/** + * Marks the code that may write the {@code generatedBy} of a test case and the fields that + * {@code generatedBy} freezes: a suggestion that creates such a test and the reconcile that keeps + * it in step with its shape (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + * Any other write that sets {@code generatedBy}, or changes the test definition, the entity link or + * the parameter values of a test that has it, is a 400. + */ +public final class GeneratedTestScope { + static final String SET_BY_SERVER = + "generatedBy is set by the server when a suggestion creates a test from a shape, and cannot be sent or changed"; + static final String FROM_A_SHAPE = + "This test comes from a shape: its test definition, entity link and parameter values change" + + " only when the shape or the table bindings change. Its description, owners and tags" + + " can be edited, and it can be deleted"; + + private static final ThreadLocal ACTIVE = ThreadLocal.withInitial(() -> Boolean.FALSE); + + private GeneratedTestScope() {} + + /** True when the calling thread is inside the scope of a write that may set the fields. */ + public static boolean isActive() { + return Boolean.TRUE.equals(ACTIVE.get()); + } + + /** Enters the scope. Close the returned handle to restore the previous state. */ + public static Handle enter() { + final boolean previous = ACTIVE.get(); + ACTIVE.set(Boolean.TRUE); + return () -> ACTIVE.set(previous); + } + + @FunctionalInterface + public interface Handle extends AutoCloseable { + @Override + void close(); + } + + /** Refuses a create that carries {@code generatedBy} outside the scope. */ + static void requireUnsetOnCreate(final TestCase test) { + if (test.getGeneratedBy() != null && !isActive()) { + throw BadRequestException.of(SET_BY_SERVER); + } + } + + /** Refuses a change to {@code generatedBy} or to what it freezes outside the scope. */ + static void requireUnchanged(final TestCase original, final TestCase updated) { + if (isActive()) { + return; + } + if (!Objects.equals(original.getGeneratedBy(), updated.getGeneratedBy())) { + throw BadRequestException.of(SET_BY_SERVER); + } + requireFrozenFieldsUnchanged(original, updated); + } + + /** + * Refuses a change to what the stored test's {@code generatedBy} freezes. A PUT body cannot carry + * {@code generatedBy}, so the stored test says whether the test comes from a shape. + */ + static void requireFrozenFieldsUnchanged(final TestCase original, final TestCase updated) { + if (!isActive() + && original.getGeneratedBy() != null + && frozenFieldsChanged(original, updated)) { + throw BadRequestException.of(FROM_A_SHAPE); + } + } + + private static boolean frozenFieldsChanged(final TestCase original, final TestCase updated) { + return !Objects.equals(original.getEntityLink(), updated.getEntityLink()) + || !Objects.equals(original.getParameterValues(), updated.getParameterValues()) + || !sameDefinition(original, updated); + } + + private static boolean sameDefinition(final TestCase original, final TestCase updated) { + return original.getTestDefinition() == null + ? updated.getTestDefinition() == null + : updated.getTestDefinition() != null && sameReference(original, updated); + } + + /** A PUT names its definition by name until the write resolves it, so it has no id yet. */ + private static boolean sameReference(final TestCase original, final TestCase updated) { + final var stored = original.getTestDefinition(); + final var incoming = updated.getTestDefinition(); + return incoming.getId() == null + ? Objects.equals(stored.getFullyQualifiedName(), incoming.getFullyQualifiedName()) + : Objects.equals(stored.getId(), incoming.getId()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java index a82c29603e4d..79dac3fb6e6e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java @@ -56,6 +56,7 @@ public class ListFilter extends Filter { private static final String TASK_STATUS_GROUP_ACTIVE = "active"; private static final String TASK_STATUS_GROUP_CLOSED = "closed"; private static final String ONTOLOGY_AXIOM_TABLE = "ontology_axiom_entity"; + private static final String ONTOLOGY_SHAPE_TABLE = "ontology_shape_entity"; private static final String ONTOLOGY_CHANGE_SET_TABLE = "ontology_change_set_entity"; private static final String ONTOLOGY_CONCEPT_TABLE = "ontology_concept_entity"; private static final String ONTOLOGY_PROPERTY_TABLE = "ontology_property_entity"; @@ -173,6 +174,7 @@ public String getCondition(String tableName) { conditions.add(getAssignee()); conditions.add(getTaskReviewerOrAssigneeCondition()); conditions.add(getTaskOntologyReviewCondition(tableName)); + conditions.add(getTaskSuggestionTypeCondition(tableName)); conditions.add(getCreatedByCondition()); conditions.add(getUpdatedByCondition(tableName)); conditions.add(getAboutEntityCondition()); @@ -228,6 +230,7 @@ private String getOntologyIdCondition(final String tableName) { if (!nullOrEmpty(ontologyId) && (tableMatches(tableName, ONTOLOGY_CONCEPT_TABLE) || tableMatches(tableName, ONTOLOGY_AXIOM_TABLE) + || tableMatches(tableName, ONTOLOGY_SHAPE_TABLE) || tableMatches(tableName, ONTOLOGY_PROPERTY_TABLE) || tableMatches(tableName, ONTOLOGY_RELEASE_TABLE))) { queryParams.put("ontologyIdParam", ontologyId); @@ -497,6 +500,22 @@ private String getTaskReviewerOrAssigneeCondition() { Relationship.REVIEWS.ordinal()); } + private String getTaskSuggestionTypeCondition(String tableName) { + String suggestionTypes = queryParams.get("suggestionType"); + return nullOrEmpty(suggestionTypes) + ? "" + : suggestionTypeInCondition(tableName, suggestionTypes); + } + + private String suggestionTypeInCondition(String tableName, String suggestionTypes) { + String json = qualifyColumn(tableName, "json"); + String inCondition = buildIndexedBindParams("suggestionType", suggestionTypes); + return Boolean.TRUE.equals(DatasourceConfig.getInstance().isMySQL()) + ? String.format( + "JSON_UNQUOTE(JSON_EXTRACT(%s, '$.payload.suggestionType')) IN (%s)", json, inCondition) + : String.format("%s->'payload'->>'suggestionType' IN (%s)", json, inCondition); + } + private String getTaskOntologyReviewCondition(String tableName) { String ontologyId = queryParams.get("ontologyReviewOntologyId"); if (nullOrEmpty(ontologyId)) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyChangeSetRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyChangeSetRepository.java index 56366e0e2354..e8ca0d2d2abf 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyChangeSetRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyChangeSetRepository.java @@ -14,6 +14,7 @@ package org.openmetadata.service.jdbi3; import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.service.util.EntityUtil.objectMatch; import jakarta.ws.rs.BadRequestException; import jakarta.ws.rs.core.UriInfo; @@ -36,7 +37,10 @@ import org.openmetadata.schema.type.change.ChangeSource; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyChangeApplicationService; +import org.openmetadata.service.ontology.OntologyChangeEvidenceView; import org.openmetadata.service.ontology.OntologyChangeSetValidator; +import org.openmetadata.service.ontology.OntologyDraftNarrowing; import org.openmetadata.service.ontology.OntologyPackCatalog; import org.openmetadata.service.ontology.OntologyPackInstallations; import org.openmetadata.service.resources.ontology.OntologyChangeSetResource; @@ -46,6 +50,7 @@ @Repository public class OntologyChangeSetRepository extends EntityRepository { + private static final String OPERATIONS_FIELD = "operations"; private static final List> STORED_PARENT_REFERENCES = List.of( new StoredParentReference<>( @@ -91,6 +96,15 @@ protected void applyInheritance( } } + /** + * The schema masks {@code operations} so that no change event holds them. A version of the draft + * is its content, and the resource that serves it asks the draft read right. + */ + @Override + protected List getMaskedFieldsShownInHistory() { + return List.of(OPERATIONS_FIELD); + } + @Override public void setFields( final OntologyChangeSet entity, @@ -273,9 +287,16 @@ public PutResponse replaceOperations( final List operations, final int undoCursor) { final OntologyChangeSet updated = editableCopy(id); + final List stored = updated.getOperations(); updated.setOperations(operations); updated.setUndoCursor(undoCursor); - return persist(uriInfo, updated, user); + return persist( + uriInfo, + updated, + user, + () -> + OntologyDraftNarrowing.requireNoLostClasses( + updated, stored, OntologyChangeApplicationService::declaredConcepts)); } public PutResponse moveCursor( @@ -301,7 +322,17 @@ public PutResponse transition( private PutResponse persist( final UriInfo uriInfo, final OntologyChangeSet updated, final String user) { + return persist(uriInfo, updated, user, () -> {}); + } + + // The check runs once the replacement is validated, so a malformed set reports its own error. + private PutResponse persist( + final UriInfo uriInfo, + final OntologyChangeSet updated, + final String user, + final Runnable requirement) { prepareInternal(updated, true); + requirement.run(); return createOrUpdate(uriInfo, updated, user); } @@ -389,13 +420,33 @@ public void entitySpecificUpdate(final boolean consolidatingChanges) { Entity.CONTEXT_MEMORY); storeSourceMemoryRelationships(updated); } - recordChange("operations", original.getOperations(), updated.getOperations(), true); + recordOperations(); recordChange("undoCursor", original.getUndoCursor(), updated.getUndoCursor()); recordChange("state", original.getState(), updated.getState()); recordChange("reviewTask", original.getReviewTask(), updated.getReviewTask()); recordChange( "applicationResult", original.getApplicationResult(), updated.getApplicationResult()); } + + /** + * A recorded change is read with every version and travels in change events, and neither has a + * single reader to decide the tables of the evidence for. So it holds the operations without + * their evidence, and an edit that changes evidence alone is stored without a new version. + */ + private void recordOperations() { + recordChange( + OPERATIONS_FIELD, + OntologyChangeEvidenceView.withoutEvidence(original.getOperations()), + OntologyChangeEvidenceView.withoutEvidence(updated.getOperations()), + true); + recordChange( + OPERATIONS_FIELD, + original.getOperations(), + updated.getOperations(), + false, + objectMatch, + false); + } } @Override diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java index 3435bf582188..70a0c16616a3 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingDAO.java @@ -16,6 +16,7 @@ import static org.openmetadata.service.jdbi3.locator.ConnectionType.MYSQL; import static org.openmetadata.service.jdbi3.locator.ConnectionType.POSTGRES; +import com.fasterxml.jackson.core.type.TypeReference; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -29,31 +30,57 @@ import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.customizer.BindList; +import org.jdbi.v3.sqlobject.customizer.BindMethods; import org.jdbi.v3.sqlobject.customizer.Define; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyRowFilter; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlQuery; import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlUpdate; -import org.openmetadata.service.util.jdbi.BindJson; import org.openmetadata.service.util.jdbi.BindUUID; /** One row per native concept and bound catalog asset, ordered by asset id within a concept. */ public interface OntologyConceptBindingDAO { - String COLUMNS = "conceptId, assetId, assetType, assetFqnHash, columnBindings"; + String COLUMNS = + "conceptId, assetId, assetType, assetFqnHash, columnBindings, bindingRole, subjectKey, " + + "rowFilter"; + String BINDING_COLUMNS = + "binding.conceptId, binding.assetId, binding.assetType, binding.assetFqnHash, " + + "binding.columnBindings, binding.bindingRole, binding.subjectKey, binding.rowFilter"; + String IDENTITY_ROLE = "identity"; + String CONTRIBUTING_ROLE = "contributing"; String BOUND_CONCEPTS = "FROM ontology_concept_binding binding " + "JOIN ontology_concept_entity concept ON concept.id = binding.conceptId " + "WHERE concept.ontologyId = :ontologyId AND concept.deleted = FALSE"; + /** + * {@code role}, {@code subjectKey} and {@code rowFilter} are null on every asset that is not a + * table and on table rows nobody has assigned, which includes every row written before they + * existed. + */ record BindingRow( UUID conceptId, UUID assetId, OntologyBindingAssetType assetType, String assetFqnHash, - List columns) { + List columns, + OntologyBindingRole role, + List> subjectKey, + OntologyRowFilter rowFilter) { + public BindingRow( + final UUID conceptId, + final UUID assetId, + final OntologyBindingAssetType assetType, + final String assetFqnHash, + final List columns) { + this(conceptId, assetId, assetType, assetFqnHash, columns, null, null, null); + } + public static Map> assetIdsByType( final List rows) { final Map> ids = @@ -65,6 +92,17 @@ public static Map> assetIdsByType( } } + /** One row as the values its columns take, with each JSON column already serialized. */ + record StoredBinding( + String conceptId, + String assetId, + String assetType, + String assetFqnHash, + String columnBindings, + String bindingRole, + String subjectKey, + String rowFilter) {} + record ConceptAssetCount(UUID conceptId, long assetCount) {} record BindingPosition(UUID conceptId, UUID assetId) {} @@ -77,25 +115,26 @@ record BoundAsset(String assetType, String assetId) {} value = "INSERT INTO ontology_concept_binding(" + COLUMNS - + ") VALUES (:conceptId, :assetId, :assetType, :assetFqnHash, :columnBindings) " + + ") VALUES (:conceptId, :assetId, :assetType, :assetFqnHash, :columnBindings, " + + ":bindingRole, :subjectKey, :rowFilter) " + "ON DUPLICATE KEY UPDATE assetType = VALUES(assetType), " - + "assetFqnHash = VALUES(assetFqnHash), columnBindings = VALUES(columnBindings)", + + "assetFqnHash = VALUES(assetFqnHash), columnBindings = VALUES(columnBindings), " + + "bindingRole = VALUES(bindingRole), subjectKey = VALUES(subjectKey), " + + "rowFilter = VALUES(rowFilter)", connectionType = MYSQL) @ConnectionAwareSqlUpdate( value = "INSERT INTO ontology_concept_binding(" + COLUMNS + ") VALUES (:conceptId, :assetId, :assetType, :assetFqnHash, " - + "(:columnBindings :: jsonb)) " + + "(:columnBindings :: jsonb), :bindingRole, (:subjectKey :: jsonb), " + + "(:rowFilter :: jsonb)) " + "ON CONFLICT (conceptId, assetId) DO UPDATE SET assetType = EXCLUDED.assetType, " - + "assetFqnHash = EXCLUDED.assetFqnHash, columnBindings = EXCLUDED.columnBindings", + + "assetFqnHash = EXCLUDED.assetFqnHash, columnBindings = EXCLUDED.columnBindings, " + + "bindingRole = EXCLUDED.bindingRole, subjectKey = EXCLUDED.subjectKey, " + + "rowFilter = EXCLUDED.rowFilter", connectionType = POSTGRES) - void upsert( - @BindUUID("conceptId") UUID conceptId, - @BindUUID("assetId") UUID assetId, - @Bind("assetType") String assetType, - @Bind("assetFqnHash") String assetFqnHash, - @BindJson("columnBindings") String columnBindings); + void upsert(@BindMethods StoredBinding binding); @SqlUpdate( "DELETE FROM ontology_concept_binding WHERE conceptId = :conceptId AND assetId = :assetId") @@ -127,6 +166,19 @@ void deleteAssets( List listForAssetAfter( @BindUUID("assetId") UUID assetId, @Bind("after") String after, @Bind("limit") int limit); + /** The first {@code perAsset} rows of each asset in concept id order, in one statement. */ + @SqlQuery( + "SELECT " + + COLUMNS + + " FROM (SELECT " + + COLUMNS + + ", ROW_NUMBER() OVER (PARTITION BY assetId ORDER BY conceptId ASC) AS bindingOrder " + + "FROM ontology_concept_binding WHERE assetId IN ()) ranked " + + "WHERE bindingOrder <= :perAsset ORDER BY assetId ASC, conceptId ASC") + @RegisterRowMapper(BindingRowMapper.class) + List listFirstForAssets( + @BindList("assetIds") List assetIds, @Bind("perAsset") int perAsset); + @SqlQuery( "SELECT " + COLUMNS @@ -186,6 +238,93 @@ List listForConceptsAfter( List listFirstTablesForConcepts( @BindList("conceptIds") List conceptIds, @Bind("perConcept") int perConcept); + String IDENTITY_FIRST_RANKED = + " FROM (SELECT " + + COLUMNS + + ", ROW_NUMBER() OVER (PARTITION BY conceptId ORDER BY " + + "CASE WHEN bindingRole = '" + + IDENTITY_ROLE + + "' THEN 0 ELSE 1 END ASC, assetId ASC) AS bindingOrder " + + "FROM ontology_concept_binding WHERE conceptId IN () " + + "AND assetType = 'table'"; + String RANKED_PAGE = + ") ranked WHERE bindingOrder <= :perConcept " + + "ORDER BY conceptId ASC, assetId ASC LIMIT :limit"; + + /** + * For each concept, its identity table row first and then its other table rows in asset id + * order, up to {@code perConcept} rows, in one statement. The statement carries a limit of {@code + * perConcept} rows for each concept asked about, which it can never reach. + */ + @SqlQuery("SELECT " + COLUMNS + IDENTITY_FIRST_RANKED + RANKED_PAGE) + @RegisterRowMapper(BindingRowMapper.class) + List listIdentityFirstTablesForConcepts( + @BindList("conceptIds") List conceptIds, + @Bind("perConcept") int perConcept, + @Bind("limit") int limit); + + /** + * For each concept, its identity table row first and then its contributing table rows in asset + * id order, up to {@code perConcept} rows, in one statement: the rows that can hold a join. + * Unassigned rows are left out, so they never take a place from a contributing row. + */ + @SqlQuery( + "SELECT " + + COLUMNS + + IDENTITY_FIRST_RANKED + + " AND bindingRole IN ('" + + IDENTITY_ROLE + + "', '" + + CONTRIBUTING_ROLE + + "')" + + RANKED_PAGE) + @RegisterRowMapper(BindingRowMapper.class) + List listJoinHoldersForConcepts( + @BindList("conceptIds") List conceptIds, + @Bind("perConcept") int perConcept, + @Bind("limit") int limit); + + /** The identity table rows of these concepts. A concept holds at most one live identity table. */ + @SqlQuery( + "SELECT " + + COLUMNS + + " FROM ontology_concept_binding WHERE conceptId IN () " + + "AND bindingRole = '" + + IDENTITY_ROLE + + "' ORDER BY conceptId ASC, assetId ASC") + @RegisterRowMapper(BindingRowMapper.class) + List listIdentityRows(@BindList("conceptIds") List conceptIds); + + /** The first contributing table rows of one concept, in asset id order. */ + @SqlQuery( + "SELECT " + + COLUMNS + + " FROM ontology_concept_binding WHERE conceptId = :conceptId " + + "AND bindingRole = '" + + CONTRIBUTING_ROLE + + "' ORDER BY assetId ASC LIMIT :limit") + @RegisterRowMapper(BindingRowMapper.class) + List listContributingRows( + @BindUUID("conceptId") UUID conceptId, @Bind("limit") int limit); + + /** One page of the table rows of an ontology's live concepts, in concept then asset id order. */ + @SqlQuery( + "SELECT " + + BINDING_COLUMNS + + " " + + BOUND_CONCEPTS + + " AND binding.assetType = 'table' " + + "AND (:hasAfter = FALSE OR binding.conceptId > :afterConceptId " + + "OR (binding.conceptId = :afterConceptId AND binding.assetId > :afterAssetId)) " + + "ORDER BY binding.conceptId ASC, binding.assetId ASC LIMIT :limit") + @RegisterRowMapper(BindingRowMapper.class) + List listTablesForOntologyAfter( + @BindUUID("ontologyId") UUID ontologyId, + @Bind("hasAfter") boolean hasAfter, + @Bind("afterConceptId") String afterConceptId, + @Bind("afterAssetId") String afterAssetId, + @Bind("limit") int limit); + @SqlQuery( "SELECT binding.conceptId, COUNT(*) AS assetCount " + BOUND_CONCEPTS @@ -215,6 +354,8 @@ List listBoundConcepts( List findLiveAssets(@Define("table") String table, @BindList("ids") List ids); class BindingRowMapper implements RowMapper { + private static final TypeReference>> SUBJECT_KEY = new TypeReference<>() {}; + @Override public BindingRow map(final ResultSet rs, final StatementContext ctx) throws SQLException { return new BindingRow( @@ -222,7 +363,22 @@ public BindingRow map(final ResultSet rs, final StatementContext ctx) throws SQL UUID.fromString(rs.getString("assetId")), OntologyBindingAssetType.fromValue(rs.getString("assetType")), rs.getString("assetFqnHash"), - JsonUtils.readObjects(rs.getString("columnBindings"), OntologyColumnBinding.class)); + JsonUtils.readObjects(rs.getString("columnBindings"), OntologyColumnBinding.class), + role(rs.getString("bindingRole")), + subjectKey(rs.getString("subjectKey")), + rowFilter(rs.getString("rowFilter"))); + } + + private static OntologyBindingRole role(final String stored) { + return stored == null ? null : OntologyBindingRole.fromValue(stored); + } + + private static List> subjectKey(final String stored) { + return stored == null ? null : JsonUtils.readValue(stored, SUBJECT_KEY); + } + + private static OntologyRowFilter rowFilter(final String stored) { + return stored == null ? null : JsonUtils.readValue(stored, OntologyRowFilter.class); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java index 0b471948073b..6adac027986b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStore.java @@ -1,33 +1,44 @@ package org.openmetadata.service.jdbi3; import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import java.net.URI; +import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.function.Function; import org.apache.commons.codec.digest.DigestUtils; +import org.openmetadata.schema.OntologyDefinition; import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.OntologyAssetBinding; import org.openmetadata.schema.type.OntologyBindingAssetType; import org.openmetadata.schema.type.OntologyConceptBindings; +import org.openmetadata.schema.type.Relationship; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.CoreRelationshipDAOs.EntityRelationshipRecord; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingPosition; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.ConceptAssetCount; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.LiveAsset; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.StoredBinding; +import org.openmetadata.service.jdbi3.RdfInfraDAOs.OntologyMemberDAO; import org.openmetadata.service.ontology.OntologyClassHierarchy; import org.openmetadata.service.ontology.OntologyWriteClosureLimits; import org.openmetadata.service.util.FreshReadScope; +import org.openmetadata.service.util.JsonStorageUtils; /** * Operational catalog associations share the ontology lock without advancing semantic revisions. @@ -43,8 +54,13 @@ public final class OntologyConceptBindingStore { */ public static final int SCAN_PAGE_SIZE = 500; + /** How an ontology points at its mapping source database. */ + public static final Relationship MAPPING_SOURCE_RELATION = Relationship.MAPPED_TO; + private static final String SCHEMA = "ontologyConceptBindings"; private static final String FIRST_PAGE = ""; + // A deleted row and a live one can hold the same IRI, so more than one row per IRI is read. + private static final int WORKING_ROWS_PER_IRI = 8; private static final int MAX_ANCESTORS = OntologyWriteClosureLimits.BINDING_ANCESTORS; private final CollectionDAO dao; private final Function assetTables; @@ -104,6 +120,15 @@ public List forAssetAfter(final UUID assetId, final UUID after, fina .listForAssetAfter(assetId, after == null ? FIRST_PAGE : after.toString(), limit); } + /** The first {@code perAsset} bindings of each of these assets in concept id order. */ + public List firstForAssets(final Collection assetIds, final int perAsset) { + return assetIds.isEmpty() + ? List.of() + : EntityDAO.queryInChunks( + assetIds.stream().map(UUID::toString).distinct().toList(), + chunk -> dao.ontologyConceptBindingDAO().listFirstForAssets(chunk, perAsset)); + } + public List page(final UUID conceptId, final UUID after, final int limit) { return dao.ontologyConceptBindingDAO() .listAfter(conceptId, after == null ? FIRST_PAGE : after.toString(), limit); @@ -124,21 +149,146 @@ public List page( /** The live properties of one ontology declared with these IRIs, in one statement. */ public List liveProperties(final UUID ontologyId, final Collection iris) { - final var properties = dao.ontologyPropertyDAO(); + return declared(dao.ontologyPropertyDAO(), ontologyId, iris); + } + + /** The live concepts of one ontology declared with these IRIs, in one statement. */ + public List liveConcepts(final UUID ontologyId, final Collection iris) { + return declared(dao.ontologyConceptDAO(), ontologyId, iris); + } + + private static List declared( + final OntologyMemberDAO members, final UUID ontologyId, final Collection iris) { return iris.isEmpty() ? List.of() - : properties + : members .findDeclarations( - properties.getTableName(), + members.getTableName(), ontologyId, iris.stream().map(iri -> DigestUtils.md5Hex(iri.toString())).toList(), iris.size(), "") .stream() - .map(json -> JsonUtils.readValue(json, OntologyProperty.class)) + .map(json -> JsonUtils.readValue(json, members.getEntityClass())) + .toList(); + } + + /** The identity table rows of these concepts, whether or not their tables still exist. */ + public List identityRows(final Collection conceptIds) { + return conceptIds.isEmpty() + ? List.of() + : EntityDAO.queryInChunks( + conceptIds.stream().map(UUID::toString).distinct().toList(), + chunk -> dao.ontologyConceptBindingDAO().listIdentityRows(chunk)); + } + + /** The first {@code limit} contributing table rows of one concept, in asset id order. */ + public List contributingRows(final UUID conceptId, final int limit) { + return dao.ontologyConceptBindingDAO().listContributingRows(conceptId, limit); + } + + /** + * The working rows of one ontology declared with these IRIs, soft-deleted ones included, in one + * statement. A release answers for a class that was deleted from the draft after it was sealed. + */ + public List workingConcepts(final UUID ontologyId, final Collection iris) { + return working(dao.ontologyConceptDAO(), ontologyId, iris); + } + + /** The working property rows of one ontology, as {@link #workingConcepts} reads class rows. */ + public List workingProperties( + final UUID ontologyId, final Collection iris) { + return working(dao.ontologyPropertyDAO(), ontologyId, iris); + } + + private static List working( + final OntologyMemberDAO members, final UUID ontologyId, final Collection iris) { + return iris.isEmpty() + ? List.of() + : members + .findDeclarationsIncludingDeleted( + members.getTableName(), + ontologyId, + iris.stream().map(iri -> DigestUtils.md5Hex(iri.toString())).toList(), + WORKING_ROWS_PER_IRI * iris.size()) + .stream() + .map(json -> JsonUtils.readValue(json, members.getEntityClass())) .toList(); } + /** + * The live shapes of one ontology that name the class as their target or in a constraint, in + * name order, in one statement. + */ + public List shapesNamingClass( + final UUID ontologyId, final URI classIri, final int limit) { + return dao + .ontologyReferenceDAO() + .shapesNamingClass(ontologyId, DigestUtils.sha256Hex(classIri.toString()), limit) + .stream() + .map(json -> JsonUtils.readValue(json, OntologyShape.class)) + .toList(); + } + + /** The live properties with these ids, in one statement. */ + public List liveProperties(final Collection ids) { + return ids.isEmpty() + ? List.of() + : dao.ontologyPropertyDAO().findEntitiesByIds(List.copyOf(ids), Include.NON_DELETED); + } + + /** + * Every table row of these concepts, whether or not the table exists, in one statement for each + * chunk of ids. A concept's rows are never cut short. + */ + public List allTableRows(final Collection conceptIds) { + return conceptIds.isEmpty() + ? List.of() + : EntityDAO.queryInChunks( + conceptIds.stream().map(UUID::toString).distinct().toList(), + chunk -> + dao.ontologyConceptBindingDAO() + .listFirstTablesForConcepts(chunk, Integer.MAX_VALUE)); + } + + /** The live classes with these ids, in one statement. */ + public List liveConcepts(final Collection ids) { + return ids.isEmpty() + ? List.of() + : dao.ontologyConceptDAO().findEntitiesByIds(List.copyOf(ids), Include.NON_DELETED); + } + + /** One page of an ontology's table rows in concept then asset id order, after a position. */ + public List tableRows( + final UUID ontologyId, final BindingPosition after, final int limit) { + return dao.ontologyConceptBindingDAO() + .listTablesForOntologyAfter( + ontologyId, + after != null, + after == null ? FIRST_PAGE : after.conceptId().toString(), + after == null ? FIRST_PAGE : after.assetId().toString(), + limit); + } + + /** + * The database an ontology names as its mapping source, or null when it names none. A binding + * write reads it under the ontology lock that a change of the mapping source also takes. + */ + public UUID mappingSource(final UUID ontologyId) { + return mappingSource(dao, ontologyId); + } + + /** The stored mapping source of an ontology, read from its relationship row. */ + public static UUID mappingSource(final CollectionDAO dao, final UUID ontologyId) { + return dao + .relationshipDAO() + .findTo(ontologyId, Entity.ONTOLOGY, MAPPING_SOURCE_RELATION.ordinal(), Entity.DATABASE) + .stream() + .map(EntityRelationshipRecord::getId) + .findFirst() + .orElse(null); + } + public List firstTables(final Collection conceptIds, final int perConcept) { return conceptIds.isEmpty() ? List.of() @@ -147,6 +297,47 @@ public List firstTables(final Collection conceptIds, final int conceptIds.stream().map(UUID::toString).toList(), perConcept); } + /** + * The identity table row of each concept, when it has one, then its other table rows in asset id + * order, up to {@code perConcept} rows in all. One statement reads up to {@link + * #SCAN_PAGE_SIZE} rows, so the concepts go in groups that keep it there, and a page of + * concepts is one statement. + */ + public List identityFirstTables( + final Collection conceptIds, final int perConcept) { + return grouped( + conceptIds, + perConcept, + dao.ontologyConceptBindingDAO()::listIdentityFirstTablesForConcepts); + } + + /** + * The identity table row of each concept, when it has one, then its contributing table rows in + * asset id order, up to {@code perConcept} rows in all, grouped as {@link #identityFirstTables}. + */ + public List joinHolderTables( + final Collection conceptIds, final int perConcept) { + return grouped( + conceptIds, perConcept, dao.ontologyConceptBindingDAO()::listJoinHoldersForConcepts); + } + + @FunctionalInterface + private interface RankedRead { + List read(List conceptIds, int perConcept, int limit); + } + + private static List grouped( + final Collection conceptIds, final int perConcept, final RankedRead read) { + final List ids = conceptIds.stream().map(UUID::toString).distinct().toList(); + final int group = Math.max(1, SCAN_PAGE_SIZE / perConcept); + final List rows = new ArrayList<>(); + for (int from = 0; from < ids.size(); from += group) { + final List chunk = ids.subList(from, Math.min(ids.size(), from + group)); + rows.addAll(read.read(chunk, perConcept, chunk.size() * perConcept)); + } + return rows; + } + public List boundConcepts( final UUID ontologyId, final int limit, final int offset) { return dao.ontologyConceptBindingDAO().listBoundConcepts(ontologyId, limit, offset); @@ -202,11 +393,19 @@ private long updateLocked(final OntologyConcept concept, final Mutation mutation public void save(final UUID conceptId, final OntologyAssetBinding asset, final String fqnHash) { dao.ontologyConceptBindingDAO() .upsert( - conceptId, - asset.getAssetId(), - asset.getAssetType().value(), - fqnHash, - JsonUtils.pojoToJson(listOrEmpty(asset.getColumns()))); + new StoredBinding( + conceptId.toString(), + asset.getAssetId().toString(), + asset.getAssetType().value(), + fqnHash, + storedJson(listOrEmpty(asset.getColumns())), + asset.getRole() == null ? null : asset.getRole().value(), + nullOrEmpty(asset.getSubjectKey()) ? null : storedJson(asset.getSubjectKey()), + asset.getRowFilter() == null ? null : storedJson(asset.getRowFilter()))); + } + + private static String storedJson(final Object value) { + return JsonStorageUtils.sanitizeNulCharacters(JsonUtils.pojoToJson(value)); } public void remove(final UUID conceptId, final UUID assetId) { @@ -226,35 +425,59 @@ public void deleteConcept(final UUID conceptId) { } public Set ancestors(final OntologyConcept concept) { - final Set visited = new HashSet<>(); - Set pending = Set.of(concept.getIri().toString()); + final String start = concept.getIri().toString(); + final Set reached = + OntologyClassHierarchy.reachable( + namedParentsAbove(concept.getOntology().getId(), Set.of(start)), Set.of(start)); + requireBound(reached.size()); + return reached; + } + + /** + * The named parents of every class that a walk up from {@code starts} reaches, by the IRI of the + * class. One statement reads each level for the whole frontier, so the statements are one per + * level whatever the number of starts, except that a first level longer than one IN list is read + * in chunks, in the order of the starts. The walk is bound as a whole, chunks included, by the + * classes it finds above the starts and by the axioms it reads. The starts themselves are not + * counted. + */ + public Map> namedParentsAbove( + final UUID ontologyId, final Collection starts) { + final Map> parents = new HashMap<>(); + final Set visited = new LinkedHashSet<>(starts); + final int startCount = visited.size(); + Set pending = new LinkedHashSet<>(visited); int traversed = 0; while (!pending.isEmpty()) { - visited.addAll(pending); final var axioms = - dao.ontologyReferenceDAO() - .ancestors( - concept.getOntology().getId(), - pending.stream().map(DigestUtils::sha256Hex).toList(), - MAX_ANCESTORS + 1, - ""); + EntityDAO.queryInChunks( + pending.stream().map(DigestUtils::sha256Hex).toList(), + chunk -> + dao.ontologyReferenceDAO().ancestors(ontologyId, chunk, MAX_ANCESTORS + 1, "")); traversed += axioms.size(); - requireBound(Math.max(visited.size(), traversed)); - pending = parents(axioms, pending, visited); + requireBound(Math.max(visited.size() - startCount, traversed)); + pending = levelAbove(axioms, pending, visited, parents); + visited.addAll(pending); } - return Set.copyOf(visited); + return parents; } - private static Set parents( - final List rows, final Set pending, final Set visited) { + private static Set levelAbove( + final List rows, + final Set pending, + final Set visited, + final Map> parents) { final Set result = new HashSet<>(); for (final String json : rows) { final var axiom = JsonUtils.readValue(json, OntologyAxiom.class); - if (pending.contains(axiom.getSubjectIri().toString())) { - OntologyClassHierarchy.namedParents(axiom).stream() - .map(URI::toString) - .filter(iri -> !visited.contains(iri)) - .forEach(result::add); + final String subject = axiom.getSubjectIri().toString(); + if (pending.contains(subject)) { + for (final URI parent : OntologyClassHierarchy.namedParents(axiom)) { + parents.computeIfAbsent(subject, ignored -> new HashSet<>()).add(parent.toString()); + if (!visited.contains(parent.toString())) { + result.add(parent.toString()); + } + } requireBound(result.size()); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptRepository.java index c25bd4d3ba02..3a9ff5568a17 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyConceptRepository.java @@ -214,6 +214,7 @@ private OntologyDefinition loadSource(final String type, final UUID id) { case Entity.ONTOLOGY_AXIOM -> daoCollection.ontologyAxiomDAO().findEntityById(id); case Entity.ONTOLOGY_PROPERTY -> daoCollection.ontologyPropertyDAO().findEntityById(id); case Entity.ONTOLOGY_CONCEPT -> daoCollection.ontologyConceptDAO().findEntityById(id); + case Entity.ONTOLOGY_SHAPE -> daoCollection.ontologyShapeDAO().findEntityById(id); default -> throw new BadRequestException("Unsupported ontology reference source"); }; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyDeclinedDefinitionDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyDeclinedDefinitionDAO.java new file mode 100644 index 000000000000..1412b3e09a9e --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyDeclinedDefinitionDAO.java @@ -0,0 +1,125 @@ +/* + * 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.jdbi3; + +import static org.openmetadata.service.jdbi3.locator.ConnectionType.MYSQL; +import static org.openmetadata.service.jdbi3.locator.ConnectionType.POSTGRES; + +import java.net.URI; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.UUID; +import org.jdbi.v3.core.mapper.RowMapper; +import org.jdbi.v3.core.statement.StatementContext; +import org.jdbi.v3.sqlobject.config.RegisterRowMapper; +import org.jdbi.v3.sqlobject.customizer.Bind; +import org.jdbi.v3.sqlobject.customizer.BindList; +import org.jdbi.v3.sqlobject.customizer.BindMethods; +import org.jdbi.v3.sqlobject.statement.SqlQuery; +import org.jdbi.v3.sqlobject.statement.SqlUpdate; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyDeclinedDefinition; +import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlUpdate; + +/** Definitions declined for an ontology, one row per operation type, IRI and content digest. */ +public interface OntologyDeclinedDefinitionDAO { + String COLUMNS = + "ontologyId, operationType, iri, iriHash, payloadDigest, declinedBy, declinedAt, reason, " + + "changeSetId, operationId"; + + /** A row as the values its columns take. */ + record StoredDeclinedDefinition( + String ontologyId, + String operationType, + String iri, + String iriHash, + String payloadDigest, + String declinedBy, + long declinedAt, + String reason, + String changeSetId, + String operationId) {} + + /** Keeps the first decision of a definition: declining it again changes nothing. */ + @ConnectionAwareSqlUpdate( + value = + "INSERT INTO ontology_declined_definition(" + + COLUMNS + + ") VALUES (:ontologyId, :operationType, :iri, :iriHash, :payloadDigest, " + + ":declinedBy, :declinedAt, :reason, :changeSetId, :operationId) " + + "ON DUPLICATE KEY UPDATE ontologyId = ontologyId", + connectionType = MYSQL) + @ConnectionAwareSqlUpdate( + value = + "INSERT INTO ontology_declined_definition(" + + COLUMNS + + ") VALUES (:ontologyId, :operationType, :iri, :iriHash, :payloadDigest, " + + ":declinedBy, :declinedAt, :reason, :changeSetId, :operationId) " + + "ON CONFLICT DO NOTHING", + connectionType = POSTGRES) + void insertIfAbsent(@BindMethods StoredDeclinedDefinition row); + + /** Every record of the ontology whose IRI hashes to one of these, whatever its type or digest. */ + @SqlQuery( + "SELECT " + + COLUMNS + + " FROM ontology_declined_definition WHERE ontologyId = :ontologyId " + + "AND iriHash IN ()") + @RegisterRowMapper(DeclinedDefinitionMapper.class) + List findByIriHashes( + @Bind("ontologyId") String ontologyId, @BindList("iriHashes") List iriHashes); + + /** Records in the order they were declined, starting after the row the cursor names. */ + @SqlQuery( + "SELECT " + + COLUMNS + + " FROM ontology_declined_definition WHERE ontologyId = :ontologyId " + + "AND (:hasAfter = FALSE OR declinedAt > :afterAt " + + "OR (declinedAt = :afterAt AND (operationType > :afterType " + + "OR (operationType = :afterType AND (iriHash > :afterIriHash " + + "OR (iriHash = :afterIriHash AND payloadDigest > :afterDigest)))))) " + + "ORDER BY declinedAt ASC, operationType ASC, iriHash ASC, payloadDigest ASC " + + "LIMIT :limit") + @RegisterRowMapper(DeclinedDefinitionMapper.class) + List listAfter( + @Bind("ontologyId") String ontologyId, + @Bind("hasAfter") boolean hasAfter, + @Bind("afterAt") long afterAt, + @Bind("afterType") String afterType, + @Bind("afterIriHash") String afterIriHash, + @Bind("afterDigest") String afterDigest, + @Bind("limit") int limit); + + /** Removes every record of an ontology, as its permanent deletion does. */ + @SqlUpdate("DELETE FROM ontology_declined_definition WHERE ontologyId = :ontologyId") + void deleteByOntology(@Bind("ontologyId") String ontologyId); + + class DeclinedDefinitionMapper implements RowMapper { + @Override + public OntologyDeclinedDefinition map(final ResultSet rows, final StatementContext context) + throws SQLException { + return new OntologyDeclinedDefinition() + .withOntologyId(UUID.fromString(rows.getString("ontologyId"))) + .withOperationType(OntologyChangeOperationType.fromValue(rows.getString("operationType"))) + .withIri(URI.create(rows.getString("iri"))) + .withPayloadDigest(rows.getString("payloadDigest")) + .withDeclinedBy(rows.getString("declinedBy")) + .withDeclinedAt(rows.getLong("declinedAt")) + .withReason(rows.getString("reason")) + .withChangeSetId(UUID.fromString(rows.getString("changeSetId"))) + .withOperationId(UUID.fromString(rows.getString("operationId"))); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyPropertyRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyPropertyRepository.java index ad51211d32bf..d4ae435acbf7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyPropertyRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyPropertyRepository.java @@ -84,10 +84,19 @@ public OntologyPropertyRepository() { OntologyProperty.class, Entity.getCollectionDAO().ontologyPropertyDAO(), COLLECTION_PATH, - "ontology,iri,kind,domain,range,enumValues,unit,isIdentifier,inverse,characteristics,propertyChain,disjointWith,superProperties,deprecated,replacedBy"); + "ontology,iri,kind,domain,range,enumValues,unit,isIdentifier,isDisplayName,inverse,characteristics,propertyChain,disjointWith,superProperties,deprecated,replacedBy"); supportsSearch = true; } + /** Not being a display name has one stored form, an absent flag, so false never seals apart. */ + @Override + public void prepare(final OntologyProperty entity, final boolean update) { + if (Boolean.FALSE.equals(entity.getIsDisplayName())) { + entity.setIsDisplayName(null); + } + super.prepare(entity, update); + } + @Override protected void validateDefinition(final OntologyProperty entity) { final OntologyPropertyRules.Violation violation = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java index 95386b63eaa6..81a7f4ab6ecc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceDAO.java @@ -105,6 +105,75 @@ List referencingForUpdate( @BindList("iriHashes") List iriHashes, @Bind("limit") int limit); + String SIBLINGS_SELECT = "SELECT p.json "; + String SIBLINGS_FROM_PG = "FROM ontology_property_entity p JOIN ontology_reference r "; + String SIBLINGS_FROM_MYSQL = + "FROM ontology_reference r FORCE INDEX (ontology_reference_target_index) " + + "STRAIGHT_JOIN ontology_property_entity p "; + String SIBLINGS_JOIN_ON = + "ON r.sourceId = p.id AND r.ontologyId = p.ontologyId " + + "WHERE p.ontologyId = :ontologyId AND p.deleted = FALSE AND "; + String SIBLINGS_WHERE = + " AND r.sourceType = 'ontologyProperty' AND r.role = 'DOMAIN' AND r.iriHash IN () " + + "ORDER BY p.id LIMIT :limit FOR UPDATE"; + + /** + * The undeleted properties flagged as a display name whose domain includes one of the classes, + * in one read, whatever else references those classes. It is a join with {@code FOR UPDATE}, so + * on MySQL both tables are read as current reads and locked, not as the transaction's snapshot. + * A property with several matching domain classes comes back once per match, and the caller drops + * the repeats, because Postgres rejects {@code FOR UPDATE} with {@code DISTINCT}. + */ + // Two pins keep the locking read inside the ontology's rows. The index keeps the range on the + // reference target index, whose first column is the ontology. STRAIGHT_JOIN reads the reference + // table first, so that range decides which property rows are read. Without the order MySQL may + // start from the property table once the index is cached, and it then locks every property row + // of every ontology. Without the index it scans every ontology's references for a heavily + // referenced class and locks them all. + @ConnectionAwareSqlQuery( + value = + SIBLINGS_SELECT + + SIBLINGS_FROM_MYSQL + + SIBLINGS_JOIN_ON + + "JSON_UNQUOTE(JSON_EXTRACT(p.json, '$.isDisplayName')) = 'true'" + + SIBLINGS_WHERE, + connectionType = MYSQL) + @ConnectionAwareSqlQuery( + value = + SIBLINGS_SELECT + + SIBLINGS_FROM_PG + + SIBLINGS_JOIN_ON + + "p.json ->> 'isDisplayName' = 'true'" + + SIBLINGS_WHERE, + connectionType = POSTGRES) + List displayNameSiblings( + @BindUUID("ontologyId") UUID ontologyId, + @BindList("iriHashes") List iriHashes, + @Bind("limit") int limit); + + @SqlQuery( + "SELECT s.name FROM ontology_shape_entity s JOIN ontology_reference r " + + "ON r.sourceId = s.id AND r.ontologyId = s.ontologyId " + + "WHERE s.ontologyId = :ontologyId AND s.deleted = FALSE " + + "AND r.sourceType = 'ontologyShape' AND r.iriHash = :iriHash " + + "ORDER BY s.name, s.id LIMIT :limit ") + List shapesNaming( + @BindUUID("ontologyId") UUID ontologyId, + @Bind("iriHash") String iriHash, + @Bind("limit") int limit, + @Define("locking") String locking); + + @SqlQuery( + "SELECT s.json FROM ontology_shape_entity s JOIN ontology_reference r " + + "ON r.sourceId = s.id AND r.ontologyId = s.ontologyId " + + "WHERE s.ontologyId = :ontologyId AND s.deleted = FALSE " + + "AND r.sourceType = 'ontologyShape' AND r.role = 'CLASS_EXPRESSION' " + + "AND r.iriHash = :iriHash ORDER BY s.name, s.id LIMIT :limit") + List shapesNamingClass( + @BindUUID("ontologyId") UUID ontologyId, + @Bind("iriHash") String iriHash, + @Bind("limit") int limit); + @SqlQuery( "SELECT a.json FROM ontology_axiom_entity a JOIN ontology_reference r " + "ON r.sourceId = a.id AND r.ontologyId = a.ontologyId " diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceIndex.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceIndex.java index 9cf20d91a9f3..277550179f5d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceIndex.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReferenceIndex.java @@ -17,7 +17,11 @@ /** Maintains derived working references inside the definition writer's SQL transaction. */ final class OntologyReferenceIndex { private static final Set SOURCE_TYPES = - Set.of(Entity.ONTOLOGY_CONCEPT, Entity.ONTOLOGY_PROPERTY, Entity.ONTOLOGY_AXIOM); + Set.of( + Entity.ONTOLOGY_CONCEPT, + Entity.ONTOLOGY_PROPERTY, + Entity.ONTOLOGY_AXIOM, + Entity.ONTOLOGY_SHAPE); private final OntologyReferenceDAO dao; OntologyReferenceIndex(final CollectionDAO dao) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReleaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReleaseRepository.java index aade8996ee38..91780d01de1b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReleaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyReleaseRepository.java @@ -13,6 +13,7 @@ import java.util.UUID; import java.util.function.Predicate; import java.util.function.Supplier; +import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.Stream; import org.openmetadata.schema.EntityInterface; @@ -52,6 +53,7 @@ @Repository public final class OntologyReleaseRepository extends OntologyEntityRepository { + private static final int MEMBER_SCAN_BATCH = 1000; private static final String USER_APPROVAL_TASK = "userApprovalTask"; private static final String REVIEW_TASK_FIELDS = "assignees,reviewers,createdBy"; @@ -197,19 +199,40 @@ public OntologyReleaseMember getMember( return member; } - public ResultList listMembers( - final UUID releaseId, final MemberKind kind, final int limit, final String after) { + /** + * One page of the members the caller may view, and how many there are. The scan reads the kind + * in key order and keeps only viewable members, so neither the page, its cursor nor the total + * depends on a member the caller may not view. + */ + public ResultList listViewableMembers( + final UUID releaseId, + final MemberKind kind, + final int limit, + final String after, + final UnaryOperator> viewable) { final String cursor = after == null ? "" : UUID.fromString(RestUtil.decodeCursor(after)).toString(); - final List members = - daoCollection.ontologyReleaseDAO().listMembers(releaseId, kind.value(), cursor, limit + 1); - final List page = - List.copyOf(members.subList(0, Math.min(limit, members.size()))); + final List page = new ArrayList<>(); + int total = 0; + String scanned = ""; + List batch; + do { + batch = + daoCollection + .ontologyReleaseDAO() + .listMembers(releaseId, kind.value(), scanned, MEMBER_SCAN_BATCH); + for (final OntologyReleaseMember member : viewable.apply(batch)) { + total++; + if (page.size() <= limit && member.getMemberId().toString().compareTo(cursor) > 0) { + page.add(member); + } + } + scanned = batch.isEmpty() ? scanned : batch.getLast().getMemberId().toString(); + } while (batch.size() == MEMBER_SCAN_BATCH); + final List shown = + List.copyOf(page.subList(0, Math.min(limit, page.size()))); return new ResultList<>( - page, - null, - members.size() > limit ? page.getLast().getMemberId().toString() : null, - daoCollection.ontologyReleaseDAO().countMembers(releaseId, kind.value())); + shown, null, page.size() > limit ? shown.getLast().getMemberId().toString() : null, total); } @Override diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java index 84ce47b7ab9c..d0637bac776c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyRepository.java @@ -48,6 +48,7 @@ public class OntologyRepository extends OntologyEntityRepository { private static final String ARCHIVED_REVIEW_COMMENT = "Closed because the ontology was archived"; private static final String PUBLICATION_STATUS = "publicationStatus"; + private static final String MAPPING_SOURCE = "mappingSource"; private final OntologyPublicationStatusResolver publication; public OntologyRepository() { @@ -58,6 +59,9 @@ public OntologyRepository() { COLLECTION_PATH, "iri,namespace,layer,prefixes,approvalRule"); fieldFetchers.put(PUBLICATION_STATUS, this::fetchPublicationStatus); + fieldFetchers.put(MAPPING_SOURCE, this::fetchMappingSources); + getPatchFields().addField(allowedFields, MAPPING_SOURCE); + putFields.addField(allowedFields, MAPPING_SOURCE); publication = new OntologyPublicationStatusResolver(Entity.getCollectionDAO()); } @@ -83,6 +87,7 @@ private void refreshActiveTerms(UUID ontologyId) { public void setFields( final Ontology entity, final Fields fields, final RelationIncludes includes) { fetchPublicationStatus(List.of(entity), fields); + fetchMappingSources(List.of(entity), fields); } @Override @@ -90,6 +95,9 @@ public void clearFields(final Ontology entity, final Fields fields) { if (!fields.contains(PUBLICATION_STATUS)) { entity.setPublicationStatus(null); } + if (!fields.contains(MAPPING_SOURCE)) { + entity.setMappingSource(null); + } } @Override @@ -106,9 +114,10 @@ protected void validatePatch( } } + /** The mapping source is a relationship row, so a renamed or deleted database is never stale. */ @Override protected List getFieldsStrippedFromStorageJson() { - return List.of(PUBLICATION_STATUS); + return List.of(PUBLICATION_STATUS, MAPPING_SOURCE); } @Override @@ -123,6 +132,70 @@ private void fetchPublicationStatus(final List ontologies, final Field } } + private void fetchMappingSources(final List ontologies, final Fields fields) { + if (fields.contains(MAPPING_SOURCE)) { + ontologies.forEach( + ontology -> + ontology.setMappingSource( + getToEntityRef( + ontology.getId(), + OntologyConceptBindingStore.MAPPING_SOURCE_RELATION, + Entity.DATABASE, + false))); + } + } + + /** + * The mapping source names one database. Bindings written before it was set are never checked + * here. The mapping health read lists the ones that sit elsewhere. A deleted database is refused + * only where the mapping source is set, so it never blocks another edit of the ontology. + */ + private static void resolveMappingSource(final Ontology entity) { + final EntityReference source = entity.getMappingSource(); + if (source == null) { + return; + } + if (!Entity.DATABASE.equals(source.getType())) { + throw new BadRequestException("An ontology's mapping source must be a database"); + } + if (source.getId() == null) { + throw new BadRequestException("An ontology's mapping source needs mappingSource.id"); + } + entity.setMappingSource( + Entity.getEntityReferenceById(Entity.DATABASE, source.getId(), Include.ALL)); + } + + private static void requireLiveMappingSource(final EntityReference source) { + if (source != null && Boolean.TRUE.equals(source.getDeleted())) { + throw new BadRequestException("An ontology's mapping source must not be a deleted database"); + } + } + + private static UUID mappingSourceId(final Ontology ontology) { + return ontology.getMappingSource() == null ? null : ontology.getMappingSource().getId(); + } + + @Override + public void prepare(final Ontology entity, final boolean update) { + super.prepare(entity, update); + if (!update) { + requireLiveMappingSource(entity.getMappingSource()); + } + } + + @Override + public void storeRelationships(final Ontology entity) { + super.storeRelationships(entity); + if (entity.getMappingSource() != null) { + addRelationship( + entity.getId(), + entity.getMappingSource().getId(), + Entity.ONTOLOGY, + Entity.DATABASE, + OntologyConceptBindingStore.MAPPING_SOURCE_RELATION); + } + } + @Override protected OntologyUpdater newUpdater( final Ontology original, @@ -232,6 +305,38 @@ protected void entitySpecificUpdate(final boolean consolidatingChanges) { requireNoOpenReview(original.getId()); } super.entitySpecificUpdate(consolidatingChanges); + compareAndUpdate(MAPPING_SOURCE, this::updateMappingSource); + } + + /** + * The mapping source is operational metadata. A change writes its relationship row and records + * no field change, so the ontology keeps its version and a release digest, which binds that + * version, stays the same. A PUT that names no mapping source keeps the stored one, so a client + * that does not know the field cannot clear it. A PATCH removes it. The change runs under the + * ontology state lock that a binding write holds while it reads the mapping source. + */ + private void updateMappingSource() { + if (operation.isPut() && updated.getMappingSource() == null) { + updated.setMappingSource(original.getMappingSource()); + return; + } + final UUID requested = mappingSourceId(updated); + if (!Objects.equals(storedMappingSource(), requested)) { + requireLiveMappingSource(updated.getMappingSource()); + replaceMappingSource(requested); + } + } + + private void replaceMappingSource(final UUID requested) { + final Relationship relation = OntologyConceptBindingStore.MAPPING_SOURCE_RELATION; + deleteFrom(original.getId(), Entity.ONTOLOGY, relation, Entity.DATABASE); + if (requested != null) { + addRelationship(original.getId(), requested, Entity.ONTOLOGY, Entity.DATABASE, relation); + } + } + + private UUID storedMappingSource() { + return OntologyConceptBindingStore.mappingSource(daoCollection, original.getId()); } } @@ -240,6 +345,7 @@ protected void validateDefinition(final Ontology entity) { entity.setPublicationStatus(null); requireAbsoluteIri(entity.getNamespace(), "namespace"); OntologyLayerValidator.validatePrefixes(entity.getPrefixes()); + resolveMappingSource(entity); } @Override @@ -261,6 +367,7 @@ protected List prepareChildrenForHardDeleteCascade( @Override protected void entitySpecificCleanup(final Ontology entity) { requireNoRetainedReleases(entity.getId()); + daoCollection.ontologyDeclinedDefinitionDAO().deleteByOntology(entity.getId().toString()); } /** @@ -304,12 +411,28 @@ private void requireNoRetainedReleases(final UUID id) { public R applyWorkingChanges( final UUID id, final long expectedRevision, final Supplier work) { + return underWorkingLock(id, expectedRevision, work); + } + + /** + * Runs {@code work} in one transaction under the ontology's lock, so every write it makes is + * kept or none is, and no other writer interleaves. Unlike {@link #applyWorkingChanges}, it takes + * the draft as it finds it. + */ + public R writeWorkingDraft(final UUID id, final Supplier work) { + return underWorkingLock(id, null, work); + } + + private R underWorkingLock( + final UUID id, final Long expectedRevision, final Supplier work) { return executeInTransaction( () -> { try (var ignored = FreshReadScope.enter()) { final OntologyStateDAO states = daoCollection.ontologyStateDAO(); states.initialize(id); - if (states.lock(id).getWorkingRevision() != expectedRevision) { + final OntologyState state = states.lock(id); + if (expectedRevision != null + && state.getWorkingRevision() != expectedRevision.longValue()) { throw new PreconditionFailedException( "Ontology changed since this draft was created"); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyShapeRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyShapeRepository.java new file mode 100644 index 000000000000..c8b2fe37fca5 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyShapeRepository.java @@ -0,0 +1,45 @@ +/* + * 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.jdbi3; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.List; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyShapeRules; +import org.openmetadata.service.resources.ontology.OntologyShapeResource; + +@Repository +public class OntologyShapeRepository extends OntologyEntityRepository { + public OntologyShapeRepository() { + super( + Entity.ONTOLOGY_SHAPE, + OntologyShape.class, + Entity.getCollectionDAO().ontologyShapeDAO(), + OntologyShapeResource.COLLECTION_PATH, + "ontology,targetConcept,severity,constraints"); + } + + @Override + protected void validateDefinition(final OntologyShape entity) { + requireAbsoluteIri(entity.getTargetConcept(), "targetConcept"); + if (entity.getSeverity() == null) { + entity.setSeverity(OntologyShapeSeverity.VIOLATION); + } + entity.setConstraints(List.copyOf(listOrEmpty(entity.getConstraints()))); + OntologyShapeRules.requireValid(entity); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java index 95575117329f..1c16174be477 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/OntologyWorkingModel.java @@ -21,6 +21,7 @@ import org.openmetadata.schema.entity.data.Ontology; import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.OntologyAxiomType; import org.openmetadata.schema.utils.JsonUtils; @@ -45,6 +46,7 @@ final class OntologyWorkingModel { "kind", "domain", "range", + "isDisplayName", "inverse", "propertyChain", "disjointWith", @@ -60,6 +62,7 @@ final class OntologyWorkingModel { "literal"); private static final int LIMIT = OntologyWriteClosureLimits.WORKING_MODEL_CLOSURE; private static final int SUBJECTS_PER_RULE_QUERY = 20; + private static final int SHAPE_NAMES_SHOWN = 3; // A current read: on MySQL REPEATABLE READ a plain SELECT could miss a rule a concurrent writer // just committed. ADR:2026-10-14-ontology-definitions-have-independent-entity-storage private static final String FOR_UPDATE = "FOR UPDATE"; @@ -75,6 +78,9 @@ void requireValid(final UUID ontologyId, final List changes) { final var context = new Context(ontologyId, true, false); final List changedRules = new ArrayList<>(); for (final var change : changes) { + if (isShape(change)) { + continue; + } if (!structure(change.before()).equals(structure(change.after()))) { if (change.after() != null) { context.add(change.after(), true); @@ -83,11 +89,16 @@ void requireValid(final UUID ontologyId, final List changes) { && !Boolean.TRUE.equals(axiom.getDeleted())) { changedRules.add(axiom); } + if (change.after() instanceof OntologyProperty property + && Boolean.TRUE.equals(property.getIsDisplayName())) { + context.displayNameSiblings(property); + } if (change.before() instanceof OntologyEntityInterface declaration) { context.dependents(Set.of(declaration.getIri().toString())); } else if (change.after() instanceof OntologyEntityInterface declaration) { context.dependents(Set.of(declaration.getIri().toString())); } + requireNoShapeNamesWhatIsRemoved(ontologyId, change); } } requireDistinctRules(ontologyId, changedRules); @@ -185,6 +196,50 @@ private void requireNotADuplicate(final OntologyAxiom proposed) { requireNoDuplicate(rules, Set.of(proposed.getId())); } + /** + * A shape is saved without checking that what it names exists, so a shape is not validated with + * the definitions around it. Removing a class or property is where a shape would dangle, so that + * is refused here, naming the shapes. Declaring or editing a definition never looks at shapes. + * ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints + */ + private void requireNoShapeNamesWhatIsRemoved(final UUID ontologyId, final Change change) { + if (!(change.before() instanceof OntologyEntityInterface removed) + || change.before() instanceof Ontology + || Boolean.TRUE.equals(change.before().getDeleted()) + || !isRemoved(removed, change.after())) { + return; + } + final String iri = removed.getIri().toString(); + final List names = + dao.ontologyReferenceDAO() + .shapesNaming( + ontologyId, DigestUtils.sha256Hex(iri), SHAPE_NAMES_SHOWN + 1, FOR_UPDATE); + if (!names.isEmpty()) { + final String shown = + String.join("', '", names.subList(0, Math.min(names.size(), SHAPE_NAMES_SHOWN))); + throw new BadRequestException( + String.format( + "%s cannot be deleted while %s '%s'%s name it; delete or edit the shape first", + iri, + names.size() == 1 ? "the shape" : "the shapes", + shown, + names.size() > SHAPE_NAMES_SHOWN ? " and others" : "")); + } + } + + private static boolean isRemoved( + final OntologyEntityInterface before, final OntologyDefinition after) { + return after == null + || Boolean.TRUE.equals(after.getDeleted()) + || !(after instanceof OntologyEntityInterface kept) + || !kept.getIri().equals(before.getIri()); + } + + /** Shapes state what instances must look like; they add nothing the class model depends on. */ + private static boolean isShape(final Change change) { + return change.before() instanceof OntologyShape || change.after() instanceof OntologyShape; + } + private static ObjectNode structure(final OntologyDefinition value) { return value == null || value instanceof Ontology ? JsonUtils.getObjectMapper().createObjectNode() @@ -253,6 +308,10 @@ void dependents(final Set iris) { if (affected.contains(source.getId())) { continue; } + if (Entity.ONTOLOGY_SHAPE.equals(source.getType())) { + // Shapes are checked when a definition is removed, not when it is declared or edited. + continue; + } final EntityDAO entities = switch (source.getType()) { case Entity.ONTOLOGY_CONCEPT -> dao.ontologyConceptDAO(); @@ -274,6 +333,33 @@ void dependents(final Set iris) { } } + /** + * The stored display-name properties of the classes this one names, so the rule sees them. One + * read returns only those rows, so a heavily referenced class costs nothing extra and the + * write cannot fail on its reference count. The per-ontology lock every write takes before it + * validates serializes two writes that flag different properties of one class. The read is a join + * under {@code FOR UPDATE}, so on MySQL it sees what the first write committed in both the + * property table and the reference table, whatever the transaction's snapshot holds. + */ + void displayNameSiblings(final OntologyProperty property) { + final List domain = + listOrEmpty(property.getDomain()).stream() + .map(URI::toString) + .distinct() + .map(DigestUtils::sha256Hex) + .toList(); + if (domain.isEmpty()) { + return; + } + for (final String json : + dao.ontologyReferenceDAO().displayNameSiblings(ontologyId, domain, LIMIT)) { + final OntologyProperty sibling = JsonUtils.readValue(json, OntologyProperty.class); + if (!definitions.containsKey(sibling.getId())) { + add(sibling, false); + } + } + } + private void includeInversePartners(final Set iris, final Set next) { final var entities = dao.ontologyPropertyDAO(); final var rows = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java index cadcd1518de3..6a8d8476ebc5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/RdfInfraDAOs.java @@ -37,6 +37,7 @@ import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.entity.data.RelationshipType; import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlQuery; import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlUpdate; @@ -73,9 +74,15 @@ public interface RdfInfraDAOs { @CreateSqlObject OntologyAxiomDAO ontologyAxiomDAO(); + @CreateSqlObject + OntologyShapeDAO ontologyShapeDAO(); + @CreateSqlObject OntologyChangeSetDAO ontologyChangeSetDAO(); + @CreateSqlObject + OntologyDeclinedDefinitionDAO ontologyDeclinedDefinitionDAO(); + @CreateSqlObject OntologyAnnexDAO ontologyAnnexDAO(); @@ -154,6 +161,16 @@ List findDeclarations( @BindList("iriHashes") List iriHashes, @Bind("limit") int limit, @Define("locking") String locking); + + /** The rows that declare these IRIs, soft-deleted ones included. */ + @SqlQuery( + "SELECT json FROM

WHERE ontologyId = :ontologyId " + + "AND iriHash IN () ORDER BY name, id LIMIT :limit") + List findDeclarationsIncludingDeleted( + @Define("table") String table, + @BindUUID("ontologyId") UUID ontologyId, + @BindList("iriHashes") List iriHashes, + @Bind("limit") int limit); } interface OntologyConceptDAO extends OntologyMemberDAO { @@ -257,6 +274,23 @@ default String getNameHashColumn() { } } + interface OntologyShapeDAO extends OntologyMemberDAO { + @Override + default String getTableName() { + return "ontology_shape_entity"; + } + + @Override + default Class getEntityClass() { + return OntologyShape.class; + } + + @Override + default String getNameHashColumn() { + return "fqnHash"; + } + } + interface OntologyChangeSetDAO extends EntityDAO { @Override default String getTableName() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java index 540c1f388ae6..7fb4e57ae3e2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java @@ -2459,6 +2459,11 @@ private CustomMetric getCustomMetric(Table table, String extension) { CustomMetric.class); } + /** Validates constraints that no stored row holds yet, so each must refer to an existing column. */ + public void validateTableConstraints(Table table, Set columnsBeingRemoved) { + validateTableConstraints(table, columnsBeingRemoved, Collections.emptyList()); + } + private void validateTableConstraints( Table table, Set columnsBeingRemoved, List storedConstraints) { if (!nullOrEmpty(table.getTableConstraints())) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskFormSchemaRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskFormSchemaRepository.java index 1eb8d7cf1bcf..1c82779f900d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskFormSchemaRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskFormSchemaRepository.java @@ -371,6 +371,8 @@ private Optional mapSuggestionTypeToSchema(String suggestionType) { return switch (suggestionType.trim().toLowerCase(Locale.ROOT)) { case "description" -> Optional.of("DescriptionSuggestion"); case "tag" -> Optional.of("TagSuggestion"); + case "tableconstraint" -> Optional.of("TableConstraintSuggestion"); + case "testcase" -> Optional.of("TestCaseSuggestion"); default -> Optional.empty(); }; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java index 847bd8e156fa..fc4731ce47a0 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TaskRepository.java @@ -30,6 +30,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; +import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -39,6 +40,7 @@ import java.util.Set; import java.util.UUID; import java.util.function.Supplier; +import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.jdbi.v3.core.Jdbi; import org.openmetadata.schema.EntityInterface; @@ -79,6 +81,7 @@ import org.openmetadata.service.governance.workflows.WorkflowHandler; import org.openmetadata.service.governance.workflows.WorkflowInstanceTerminator; import org.openmetadata.service.governance.workflows.WorkflowInstanceTerminator.TaskCloseRequest; +import org.openmetadata.service.jdbi3.CoreRelationshipDAOs.EntityRelationshipObject; import org.openmetadata.service.jdbi3.CoreRelationshipDAOs.FieldRelationshipDAO.FieldRelationship; import org.openmetadata.service.resources.feeds.MessageParser; import org.openmetadata.service.resources.feeds.MessageParser.EntityLink; @@ -93,6 +96,7 @@ import org.openmetadata.service.security.policyevaluator.TaskResourceContext; import org.openmetadata.service.security.policyevaluator.TestCaseResourceContext; import org.openmetadata.service.tasks.IncidentWorkflowStages; +import org.openmetadata.service.tasks.TableConstraintSuggestion; import org.openmetadata.service.tasks.TaskFieldTarget; import org.openmetadata.service.tasks.TaskFieldValidator; import org.openmetadata.service.tasks.TaskFormExecutionResolver; @@ -102,6 +106,7 @@ import org.openmetadata.service.tasks.TaskWorkflowHandler; import org.openmetadata.service.tasks.TaskWorkflowLifecycleResolver; import org.openmetadata.service.tasks.TaskWorkflowLifecycleResolver.WorkflowStartVariables; +import org.openmetadata.service.tasks.TestCaseSuggestion; import org.openmetadata.service.util.EntityUtil; import org.openmetadata.service.util.EntityUtil.Fields; import org.openmetadata.service.util.EntityUtil.RelationIncludes; @@ -356,19 +361,107 @@ public void setFields(Task task, Fields fields, RelationIncludes relationInclude } @Override - public void setFieldsInBulk(Fields fields, java.util.List entities) { + public void setFieldsInBulk(Fields fields, List entities) { if (entities == null || entities.isEmpty()) { return; } - fetchAndSetFields(entities, fields); + fetchAndSetFields(entities, withoutBatched(fields)); + setDomainsAndReviewers(entities, fields); setInheritedFields(entities, fields); RelationIncludes defaultIncludes = RelationIncludes.fromInclude(NON_DELETED); + final Fields perTask = withoutBatched(fields); for (Task entity : entities) { - setFields(entity, fields, defaultIncludes); + setFields(entity, perTask, defaultIncludes); clearFieldsInternal(entity, fields); } } + /** + * Reads the domains and the reviewers of all the tasks in one statement, and gives each task what + * a GET of it gives. A GET returns reviewers that were soft deleted, which the batched read of + * the base class leaves out. + */ + private void setDomainsAndReviewers(final List tasks, final Fields fields) { + final boolean domains = fields.contains(FIELD_DOMAINS); + final boolean reviewers = fields.contains(FIELD_REVIEWERS); + if (!domains && !reviewers) { + return; + } + final List relations = new ArrayList<>(); + if (domains) { + relations.add(Relationship.HAS.ordinal()); + } + if (reviewers) { + relations.add(Relationship.REVIEWS.ordinal()); + } + final List records = + daoCollection + .relationshipDAO() + .findFromBatchWithRelations( + entityListToStrings(tasks), Entity.TASK, relations, Include.ALL) + .stream() + .filter( + record -> + record.getRelation() == Relationship.REVIEWS.ordinal() + || DOMAIN.equals(record.getFromEntity())) + .toList(); + final Map references = referencesOf(records); + final Map> domainsOf = new HashMap<>(); + final Map> reviewersOf = new HashMap<>(); + for (EntityRelationshipObject record : records) { + final EntityReference source = references.get(UUID.fromString(record.getFromId())); + if (source == null) { + continue; + } + final UUID taskId = UUID.fromString(record.getToId()); + if (record.getRelation() == Relationship.REVIEWS.ordinal()) { + reviewersOf.computeIfAbsent(taskId, id -> new ArrayList<>()).add(source); + } else if (DOMAIN.equals(record.getFromEntity())) { + domainsOf.computeIfAbsent(taskId, id -> new ArrayList<>()).add(source); + } + } + for (Task task : tasks) { + if (domains) { + task.setDomains( + domainsOf.getOrDefault(task.getId(), List.of()).stream() + .sorted(EntityUtil.compareEntityReference) + .collect(Collectors.toList())); + } + if (reviewers) { + task.setReviewers( + reviewersOf.getOrDefault(task.getId(), List.of()).stream() + .sorted(EntityUtil.compareEntityReference) + .collect(Collectors.toList())); + } + } + } + + /** A domain is looked up as the base class does, a reviewer as a GET does: deleted included. */ + private static Map referencesOf( + final List records) { + final Map> idsByType = new LinkedHashMap<>(); + for (EntityRelationshipObject record : records) { + idsByType + .computeIfAbsent(record.getFromEntity(), type -> new ArrayList<>()) + .add(UUID.fromString(record.getFromId())); + } + final Map references = new HashMap<>(); + idsByType.forEach( + (type, ids) -> + Entity.getEntityReferencesByIds( + type, ids, DOMAIN.equals(type) ? NON_DELETED : Include.ALL) + .forEach(reference -> references.put(reference.getId(), reference))); + return references; + } + + /** The fields that {@link #setDomainsAndReviewers} sets for the whole list in one read. */ + private static Fields withoutBatched(final Fields fields) { + final Set rest = new HashSet<>(fields.getFieldList()); + rest.remove(Entity.FIELD_DOMAINS); + rest.remove(Entity.FIELD_REVIEWERS); + return new Fields(rest); + } + @Override public void clearFields(Task task, Fields fields) { task.setAssignees(fields.contains(FIELD_ASSIGNEES) ? task.getAssignees() : null); @@ -423,6 +516,8 @@ public void prepare(Task task, boolean update) { TaskFieldValidator.validateDataAccessRequestExpiry(task); TaskFieldTarget.fillDefault(task); TaskFieldTarget.require(task); + TableConstraintSuggestion.require(task); + TestCaseSuggestion.require(task); } validateNoDuplicateActiveDataAccessRequest(task); @@ -1511,6 +1606,15 @@ private MetadataOperation getOperationForTask(Task task) { return null; } + // No task form lowers the right to add a table constraint: whatever form the task's category + // matches, approving needs EditAll on the table. + if (TableConstraintSuggestion.isTableConstraint(task)) { + return MetadataOperation.EDIT_ALL; + } + if (TestCaseSuggestion.isTestCase(task)) { + return MetadataOperation.CREATE_TESTS; + } + MetadataOperation schemaBoundOperation = TaskFormExecutionResolver.resolve(task).permissionOperation(); if (schemaBoundOperation != null) { @@ -1561,6 +1665,9 @@ private MetadataOperation getOperationForSuggestion(Task task) { case TIER -> MetadataOperation.EDIT_TIER; case DOMAIN -> MetadataOperation.EDIT_ALL; case CUSTOM_PROPERTY -> MetadataOperation.EDIT_CUSTOM_FIELDS; + // No narrower operation covers tableConstraints: a PATCH of that field needs EditAll. + case TABLE_CONSTRAINT -> MetadataOperation.EDIT_ALL; + case TEST_CASE -> MetadataOperation.CREATE_TESTS; }; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java index bdd9de8743b9..c73ec0fd1733 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java @@ -66,6 +66,7 @@ import org.openmetadata.schema.api.tests.CreateTestSuite; import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestCaseGeneratedBy; import org.openmetadata.schema.tests.TestCaseParameter; import org.openmetadata.schema.tests.TestCaseParameterValidationRule; import org.openmetadata.schema.tests.TestCaseParameterValue; @@ -875,6 +876,14 @@ public void setFullyQualifiedName(TestCase test) { @Override public void prepare(TestCase test, boolean update) { + if (!update) { + GeneratedTestScope.requireUnsetOnCreate(test); + } else if (test.getGeneratedBy() != null) { + // Before the parameter checks, so a change to what the shape freezes says where the test + // comes from instead of which parameter it breaks. + GeneratedTestScope.requireUnchanged( + get(null, test.getId(), getFields(TEST_DEFINITION), ALL, false), test); + } Table table = validateForWrite(test, update); // Create/resolve the basic test suite only after all validations pass. // This avoids creating side entities when request validation fails early. @@ -883,11 +892,41 @@ public void prepare(TestCase test, boolean update) { test.setTestSuite(getOrCreateTestSuite(test, table)); } + /** + * Prepares a PUT, given the test the PUT finds by name, or null when it creates one. A stored + * test that comes from a shape is checked before the parameters, so a change to what the shape + * freezes says where the test comes from. + */ + public void prepareInternal(TestCase test, TestCase stored) { + requireGeneratedScope(test, stored); + prepareInternal(test, stored != null); + } + + /** + * A stored test that comes from a shape keeps what the shape freezes. The real import and its + * dry run run this same check, so the dry run reports a row that changes what the shape freezes. + */ + private void requireGeneratedScope(TestCase test, TestCase stored) { + if (stored != null && stored.getGeneratedBy() != null) { + GeneratedTestScope.requireFrozenFieldsUnchanged( + new TestCase() + .withGeneratedBy(stored.getGeneratedBy()) + .withEntityLink(stored.getEntityLink()) + .withParameterValues(stored.getParameterValues()) + .withTestDefinition(getTestDefinition(stored)), + test); + } + } + /** * Runs the checks {@link #prepareInternal} runs for a test case, minus the basic test suite, so a - * CSV dry run reports the rows the real import would and creates nothing. + * CSV dry run creates nothing. The dry run and the real import run the same check of what a + * shape freezes, so the dry run reports a row that changes it. It takes the stored test the row + * names, or null when the row creates one. */ - void checkForImport(TestCase test, boolean isUpdate) { + void checkForImport(TestCase test, TestCase stored) { + final boolean isUpdate = stored != null; + requireGeneratedScope(test, stored); validateTags(test); validateForWrite(test, isUpdate); validateExtension(test, isUpdate); @@ -2052,6 +2091,32 @@ public TestCase addInspectionQuery(UriInfo uri, UUID testCaseId, String sql) { return updated; } + /** + * Rewrites what a test generated from a shape check holds, in place, so the test keeps its id and + * its results. Only the reconcile that keeps such tests in step with their shapes calls it. + */ + public TestCase updateGenerated( + UUID testCaseId, + String entityLink, + List parameterValues, + String inspectionQuery, + TestCaseGeneratedBy generatedBy, + String user) { + TestCase original = get(null, testCaseId, getFields("*")); + TestCase updated = + JsonUtils.readValue(JsonUtils.pojoToJson(original), TestCase.class) + .withEntityLink(entityLink) + .withParameterValues(parameterValues) + .withInspectionQuery(inspectionQuery) + .withGeneratedBy(generatedBy) + .withUpdatedBy(user) + .withUpdatedAt(System.currentTimeMillis()); + try (GeneratedTestScope.Handle ignored = GeneratedTestScope.enter()) { + getUpdater(original, updated, Operation.PATCH, null).update(); + } + return updated; + } + @Transaction public RestUtil.DeleteResponse deleteTestCaseFailedRowsSample(UUID id) { daoCollection.entityExtensionDAO().delete(id, FAILED_ROWS_SAMPLE_EXTENSION); @@ -2136,6 +2201,11 @@ protected boolean shouldCompare(String fieldName) { @Transaction @Override public void entitySpecificUpdate(boolean consolidatingChanges) { + if (operation == Operation.PUT && updated.getGeneratedBy() == null) { + // A request body cannot carry generatedBy, so a PUT keeps the stored one. + updated.setGeneratedBy(original.getGeneratedBy()); + } + GeneratedTestScope.requireUnchanged(original, updated); validateChangedConformance(); compareAndUpdate( "entity", @@ -2177,6 +2247,9 @@ public void entitySpecificUpdate(boolean consolidatingChanges) { () -> recordChange( "inspectionQuery", original.getInspectionQuery(), updated.getInspectionQuery())); + compareAndUpdate( + "generatedBy", + () -> recordChange("generatedBy", original.getGeneratedBy(), updated.getGeneratedBy())); compareAndUpdate( "computePassedFailedRowCount", () -> @@ -2695,7 +2768,8 @@ protected void createEntity(CSVPrinter printer, List csvRecords) thro parsedLink.getFullyQualifiedFieldValue(), EntityInterfaceUtil.quoteName(name)); testCase.setFullyQualifiedName(testCaseFqn); testCase.setEntityFQN(parsedLink.getFullyQualifiedFieldValue()); - boolean isUpdate = repository.findByNameOrNull(testCaseFqn, Include.ALL) != null; + TestCase stored = repository.findByNameOrNull(testCaseFqn, Include.ALL); + boolean isUpdate = stored != null; // A row can name any table, so it is checked as the matching REST write, before anything // is created for it (e.g. the table's test suite) @@ -2714,10 +2788,10 @@ protected void createEntity(CSVPrinter printer, List csvRecords) thro } if (importResult.getDryRun()) { - repository.checkForImport(testCase, isUpdate); + repository.checkForImport(testCase, stored); importSuccess(printer, csvRecord, isUpdate ? ENTITY_UPDATED : ENTITY_CREATED); } else { - repository.prepareInternal(testCase, isUpdate); + repository.prepareInternal(testCase, stored); importedTestSuiteIds.putIfAbsent( testCase.getTestSuite().getFullyQualifiedName(), testCase.getTestSuite().getId()); if (testCase.getId() == null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java index 091d99c328a5..dc334bc71f2b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TimeSeriesDAOs.java @@ -842,6 +842,17 @@ int countOfTestCases( List findIdsByEntityFQN( @Bind("entityFQN") String entityFQN, @Bind("entityFQNPrefix") String entityFQNPrefix); + /** + * The ids of the test cases that a shape generated, deleted ones included. Reads the index on + * {@code generatedByClassId}, the class that generated the test, which no other test case has. + */ + @SqlQuery("SELECT id FROM test_case WHERE generatedByClassId IS NOT NULL") + List findGeneratedIds(); + + /** The ids of the test cases that a shape generated for one class, deleted ones included. */ + @SqlQuery("SELECT id FROM test_case WHERE generatedByClassId = :classId") + List findGeneratedIdsOfClass(@Bind("classId") String classId); + class TestCaseRecord { @Getter String json; @Getter Integer rank; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v220/Migration.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v220/Migration.java index 763a34a52705..6c0523b99fc1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v220/Migration.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/mysql/v220/Migration.java @@ -19,6 +19,7 @@ import org.openmetadata.service.migration.api.MigrationProcessImpl; import org.openmetadata.service.migration.utils.MigrationFile; import org.openmetadata.service.migration.utils.v220.FileColumnSearchSettingsMigration; +import org.openmetadata.service.migration.utils.v220.OntologyShapePolicyRules; import org.openmetadata.service.migration.utils.v220.PersonalDateRecognizerMigration; public class Migration extends MigrationProcessImpl { @@ -39,5 +40,12 @@ public void runDataMigration() { getVersion(), FileColumnSearchSettingsMigration.STEP_NAME, () -> FileColumnSearchSettingsMigration.migrate(handle, MYSQL)); + // Seeded policies are created only when missing, so the ontology author and reviewer policies + // of an installed catalog gain the shape resource here. Idempotent. + runOnce( + migrationDAO, + getVersion(), + OntologyShapePolicyRules.STEP_NAME, + () -> OntologyShapePolicyRules.addShapeResource(handle, MYSQL)); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v220/Migration.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v220/Migration.java index 08592178510f..779e74eb0f3f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v220/Migration.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/postgres/v220/Migration.java @@ -19,6 +19,7 @@ import org.openmetadata.service.migration.api.MigrationProcessImpl; import org.openmetadata.service.migration.utils.MigrationFile; import org.openmetadata.service.migration.utils.v220.FileColumnSearchSettingsMigration; +import org.openmetadata.service.migration.utils.v220.OntologyShapePolicyRules; import org.openmetadata.service.migration.utils.v220.PersonalDateRecognizerMigration; public class Migration extends MigrationProcessImpl { @@ -39,5 +40,12 @@ public void runDataMigration() { getVersion(), FileColumnSearchSettingsMigration.STEP_NAME, () -> FileColumnSearchSettingsMigration.migrate(handle, POSTGRES)); + // Seeded policies are created only when missing, so the ontology author and reviewer policies + // of an installed catalog gain the shape resource here. Idempotent. + runOnce( + migrationDAO, + getVersion(), + OntologyShapePolicyRules.STEP_NAME, + () -> OntologyShapePolicyRules.addShapeResource(handle, POSTGRES)); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v1114/MigrationUtil.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v1114/MigrationUtil.java index 61b3d3552f60..85c0ae6b2b16 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v1114/MigrationUtil.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v1114/MigrationUtil.java @@ -207,6 +207,10 @@ public static void restoreBotRelationshipsIfMissing( * Restores bot user role relationships that were deleted by the Flyway migration issue. The v004 * migration deletes entity_relationship records where toEntity='role', which includes bot user * role assignments. + * + *

The data loss leaves a bot user with no role at all, so only a bot user that holds no role + * gets its default role back. A bot user that holds any role was not affected by the loss, and its + * roles may have been changed on purpose, so it is left as it is. */ public static void restoreBotUserRolesIfMissing(Handle handle, ConnectionType connectionType) { try { @@ -231,8 +235,8 @@ public static void restoreBotUserRolesIfMissing(Handle handle, ConnectionType co continue; } - if (hasUserRoleRelationship(handle, userId, roleId)) { - LOG.debug("Bot user {} already has role {}", bot.getName(), roleName); + if (hasAnyUserRoleRelationship(handle, userId)) { + LOG.debug("Bot user {} already has a role, skipping", bot.getName()); continue; } @@ -381,18 +385,17 @@ private static String findRoleId(Handle handle, ConnectionType connectionType, S return results.isEmpty() ? null : results.get(0).get("id").toString(); } - private static boolean hasUserRoleRelationship(Handle handle, String userId, String roleId) { + private static boolean hasAnyUserRoleRelationship(Handle handle, String userId) { String query = """ SELECT COUNT(*) as cnt FROM entity_relationship - WHERE fromId = :userId AND toId = :roleId + WHERE fromId = :userId AND fromEntity = 'user' AND toEntity = 'role' AND relation = :relation """; Integer count = handle .createQuery(query) .bind("userId", userId) - .bind("roleId", roleId) .bind("relation", HAS_RELATIONSHIP) .mapTo(Integer.class) .one(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v220/OntologyShapePolicyRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v220/OntologyShapePolicyRules.java new file mode 100644 index 000000000000..1911c7094dc9 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v220/OntologyShapePolicyRules.java @@ -0,0 +1,135 @@ +/* + * 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.v220; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.List; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.jdbi.v3.core.Handle; +import org.openmetadata.service.jdbi3.locator.ConnectionType; + +/** + * Adds the {@code ontologyShape} resource to the rules of the seeded ontology author and reviewer + * policies on an installed catalog. + * + *

A seeded policy is created only when it is missing, so a policy created by an earlier release + * never picks up a resource added to its seed. The step changes one rule of each policy, and only + * when that rule exists and does not list the resource yet, so a second run changes nothing and an + * administrator's other edits are left as they are. A policy that does not exist yet is not + * created: seeding creates it with the new list. + */ +@Slf4j +public final class OntologyShapePolicyRules { + + /** Run once per version through {@code DataMigrationStep}. */ + public static final String STEP_NAME = "ontology-shape-policy-rules"; + + static final String RESOURCE = "ontologyShape"; + + /** Seeded policy name to the name of the rule that lists the ontology resources. */ + static final Map RULES = + Map.of( + "OntologyAuthorPolicy", "OntologyAuthorPolicy-AuthorRule", + "OntologyReviewerPolicy", "OntologyReviewerPolicy-ViewRule"); + + private static final String POLICY_TABLE = "policy_entity"; + private static final String RULES_FIELD = "rules"; + private static final String NAME_FIELD = "name"; + private static final String RESOURCES_FIELD = "resources"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private OntologyShapePolicyRules() {} + + public static void addShapeResource(final Handle handle, final ConnectionType connectionType) { + RULES.forEach((policy, rule) -> addToRule(handle, connectionType, policy, rule)); + } + + private static void addToRule( + final Handle handle, + final ConnectionType connectionType, + final String policyName, + final String ruleName) { + final List> rows = + handle + .createQuery("SELECT id, json FROM " + POLICY_TABLE + " WHERE name = :name") + .bind("name", policyName) + .mapToMap() + .list(); + for (final Map row : rows) { + final JsonNode policy = parse(row.get("json")); + if (policy instanceof ObjectNode && listResource((ObjectNode) policy, ruleName)) { + store(handle, connectionType, String.valueOf(row.get("id")), policy); + LOG.info("Added {} to rule {} of {}", RESOURCE, ruleName, policyName); + } + } + } + + /** Returns true when the rule exists, lists its resources and the resource was added to them. */ + private static boolean listResource(final ObjectNode policy, final String ruleName) { + final JsonNode rules = policy.get(RULES_FIELD); + if (rules == null || !rules.isArray()) { + return false; + } + for (final JsonNode rule : rules) { + if (ruleName.equals(rule.path(NAME_FIELD).asText()) && rule.get(RESOURCES_FIELD) != null) { + return append(rule.get(RESOURCES_FIELD)); + } + } + return false; + } + + private static boolean append(final JsonNode resources) { + if (!resources.isArray() || contains(resources)) { + return false; + } + ((ArrayNode) resources).add(RESOURCE); + return true; + } + + private static boolean contains(final JsonNode resources) { + for (final JsonNode resource : resources) { + if (RESOURCE.equals(resource.asText())) { + return true; + } + } + return false; + } + + private static JsonNode parse(final Object json) { + try { + return MAPPER.readTree(String.valueOf(json)); + } catch (com.fasterxml.jackson.core.JsonProcessingException exception) { + throw new IllegalStateException("A stored policy is not valid JSON", exception); + } + } + + private static void store( + final Handle handle, + final ConnectionType connectionType, + final String id, + final JsonNode policy) { + final String sql = + switch (connectionType) { + case MYSQL -> "UPDATE " + POLICY_TABLE + " SET json = :json WHERE id = :id"; + case POSTGRES -> "UPDATE " + + POLICY_TABLE + + " SET json = CAST(:json AS jsonb) WHERE id = :id"; + }; + handle.createUpdate(sql).bind("json", policy.toString()).bind("id", id).execute(); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChangeExecutor.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChangeExecutor.java index bbf288c47e3b..a04c52deb94f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChangeExecutor.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChangeExecutor.java @@ -9,6 +9,7 @@ import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.Relationship; @@ -23,18 +24,23 @@ public final class NativeOntologyChangeExecutor { private final OntologyEntityRepository concepts; private final OntologyEntityRepository properties; private final OntologyEntityRepository axioms; + private final OntologyEntityRepository shapes; private final Clock clock; + /** The repository of each kind of definition a draft writes. */ + public record Definitions( + OntologyEntityRepository concepts, + OntologyEntityRepository properties, + OntologyEntityRepository axioms, + OntologyEntityRepository shapes) {} + public NativeOntologyChangeExecutor( - final OntologyRepository ontologies, - final OntologyEntityRepository concepts, - final OntologyEntityRepository properties, - final OntologyEntityRepository axioms, - final Clock clock) { + final OntologyRepository ontologies, final Definitions definitions, final Clock clock) { this.ontologies = ontologies; - this.concepts = concepts; - this.properties = properties; - this.axioms = axioms; + this.concepts = definitions.concepts(); + this.properties = definitions.properties(); + this.axioms = definitions.axioms(); + this.shapes = definitions.shapes(); this.clock = clock; } @@ -49,6 +55,7 @@ public OperationOutcome execute( case UPSERT_CONCEPT -> upsert(concepts, operation, uriInfo, user); case UPSERT_PROPERTY -> upsert(properties, operation, uriInfo, user); case UPSERT_AXIOM -> upsert(axioms, operation, uriInfo, user); + case UPSERT_SHAPE -> upsert(shapes, operation, uriInfo, user); case DELETE_CONCEPT -> outcome( concepts.delete(user, operation.getTargetId(), false, false).entity()); case DELETE_PROPERTY -> outcome( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChanges.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChanges.java index 8bad9f81674b..9b0a69cf1aae 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChanges.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyChanges.java @@ -4,13 +4,17 @@ import jakarta.ws.rs.BadRequestException; import java.util.HashSet; +import java.util.List; import java.util.Objects; import java.util.Set; import java.util.UUID; import org.openmetadata.schema.OntologyDefinition; import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeOperationState; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyProfileViolation; import org.openmetadata.service.Entity; /** Typed operations share the memory draft lifecycle, but never the glossary model. */ @@ -22,6 +26,7 @@ public static String entityType(final OntologyChangeOperation operation) { case UPSERT_CONCEPT, DELETE_CONCEPT -> Entity.ONTOLOGY_CONCEPT; case UPSERT_PROPERTY, DELETE_PROPERTY -> Entity.ONTOLOGY_PROPERTY; case UPSERT_AXIOM, DELETE_AXIOM -> Entity.ONTOLOGY_AXIOM; + case UPSERT_SHAPE -> Entity.ONTOLOGY_SHAPE; default -> throw new BadRequestException( "Native ontology drafts require definition operations"); }; @@ -39,6 +44,7 @@ public static OntologyDefinition definition(final OntologyChangeOperation operat case UPSERT_CONCEPT -> operation.getConcept(); case UPSERT_PROPERTY -> operation.getProperty(); case UPSERT_AXIOM -> operation.getAxiom(); + case UPSERT_SHAPE -> operation.getShape(); default -> null; }; } @@ -57,7 +63,7 @@ static void validate(final OntologyChangeSet changeSet, final int cursor) { throw new BadRequestException("A native draft accepts at most 1000 operations"); } final Set operationIds = new HashSet<>(); - final Set definitionIds = new HashSet<>(); + final Written written = new Written(new HashSet<>(), new HashSet<>()); for (int index = 0; index < operations.size(); index++) { final OntologyChangeOperation operation = operations.get(index); if (operation == null @@ -66,12 +72,10 @@ static void validate(final OntologyChangeSet changeSet, final int cursor) { || !operationIds.add(operation.getId())) { throw new BadRequestException("Every ontology operation requires a unique id and type"); } - entityType(operation); - validatePayload(changeSet, operation); - final UUID id = - operation.getTargetId() == null ? definition(operation).getId() : operation.getTargetId(); - if (!definitionIds.add(id)) { - throw new BadRequestException("A native draft may change each definition only once"); + if (OntologyBindingChanges.isBinding(operation)) { + validateBinding(operation, written); + } else { + validateDefinition(changeSet, operation, written); } operation.setState( index < cursor @@ -80,6 +84,49 @@ static void validate(final OntologyChangeSet changeSet, final int cursor) { } } + /** What a draft has written so far: each definition and each binding at most once. */ + private record Written(Set definitions, Set bindings) {} + + private static void validateBinding( + final OntologyChangeOperation operation, final Written written) { + OntologyBindingChanges.validate(operation); + if (!written.bindings().add(OntologyBindingChanges.Target.of(operation.getBinding()))) { + throw new BadRequestException("A native draft may write each binding only once"); + } + } + + private static void validateDefinition( + final OntologyChangeSet changeSet, + final OntologyChangeOperation operation, + final Written written) { + entityType(operation); + validatePayload(changeSet, operation); + final UUID id = + operation.getTargetId() == null ? definition(operation).getId() : operation.getTargetId(); + if (!written.definitions().add(id)) { + throw new BadRequestException("A native draft may change each definition only once"); + } + if (operation.getOperationType() == OntologyChangeOperationType.UPSERT_SHAPE) { + requireValidShape(operation); + } + } + + /** The rules a shape passes on its own, so a draft never stores one its apply would refuse. */ + private static void requireValidShape(final OntologyChangeOperation operation) { + final OntologyShape shape = operation.getShape(); + final String relative = + OntologyPropertyRules.relativeIriMessage(shape.getTargetConcept(), "targetConcept"); + if (relative != null) { + throw OntologyChangeSetValidator.invalid(operation, relative); + } + final List findings = OntologyShapeRules.validate(shape); + if (!findings.isEmpty()) { + final OntologyProfileViolation first = findings.getFirst(); + throw OntologyChangeSetValidator.invalid( + operation, first.getPath() + ": " + first.getMessage()); + } + } + private static void validatePayload( final OntologyChangeSet changeSet, final OntologyChangeOperation operation) { final OntologyDefinition definition = definition(operation); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPager.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPager.java index e8657688595c..cd2581c0364f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPager.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPager.java @@ -80,6 +80,10 @@ public NativeOntologyDataGraphPage page( .withLoaded(scope.loaded()) .withContextFull(scope.loaded().size() >= MAX_CONCEPTS) .withTopology(topology(scope, concepts, cursor)); + graph.addCounts( + scope.access(), + response.getClusters() == null ? List.of() : response.getClusters(), + response.getTopology().getEdges()); requireRevisions(scope.loaded()); return response; } @@ -114,6 +118,7 @@ private Map clusters( final var revisions = store.revisions(ranked.stream().map(ConceptAssetCount::conceptId).toList()); final var clusters = unloaded(graph.clusters(scope.access(), ranked, 4), scope.loaded()); + graph.addProfileFacts(scope.access(), clusters); final var added = load(clusters, revisions, scope.loaded()); response .withClusters(clusters.stream().map(Cluster::response).toList()) @@ -166,6 +171,7 @@ private void bindings( if (!Objects.equals(page.getRevision(), prefix.getBindingRevision())) { throw changedBindings(); } + graph.addProfileFacts(scope.access(), page); prefix.withThroughAssetId( through( prefix.getThroughAssetId(), diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java index bdc887514eab..b6f67fdf5398 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/NativeOntologyDataGraphService.java @@ -27,6 +27,8 @@ import java.util.Map; import java.util.Set; import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.codec.digest.DigestUtils; import org.openmetadata.schema.api.data.NativeOntologyAssetCluster; @@ -37,15 +39,20 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.type.Edge; +import org.openmetadata.schema.type.EntityProfile; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.OntologyAxiomType; +import org.openmetadata.schema.type.OntologyConceptBindingsResponse; import org.openmetadata.schema.type.OntologyExpression; import org.openmetadata.schema.type.Paging; import org.openmetadata.schema.type.Relationship; +import org.openmetadata.schema.type.TableProfile; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingPosition; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.ConceptAssetCount; @@ -54,10 +61,12 @@ import org.openmetadata.service.jdbi3.OntologyConceptRepository; import org.openmetadata.service.jdbi3.OntologyReferenceDAO.AxiomPosition; import org.openmetadata.service.jdbi3.OntologyReferenceDAO.EdgeAxiomRow; +import org.openmetadata.service.jdbi3.TimeSeriesDAOs.ProfilerDataTimeSeriesDAO; import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.DefaultAuthorizer; import org.openmetadata.service.security.ViewPermissionFilter; +import org.openmetadata.service.util.FullyQualifiedName; import org.openmetadata.service.util.RestUtil; /** @@ -83,18 +92,26 @@ public interface ReferenceLookup { private final OntologyConceptRepository concepts; private final ViewPermissionFilter visibility; private final ReferenceLookup references; + private final OntologyCountReader counts; public NativeOntologyDataGraphService( final CollectionDAO dao, final OntologyConceptBindingStore store, final OntologyConceptRepository concepts, final Authorizer authorizer, - final ReferenceLookup references) { + final ReferenceLookup references, + final Function> repositories) { this.dao = dao; this.store = store; this.concepts = concepts; this.visibility = new ViewPermissionFilter(authorizer); this.references = references; + this.counts = + new OntologyCountReader( + dao, + store, + new OntologyBindingAccess(authorizer, repositories), + (access, refs, operation) -> viewableIds(access, refs, operation)); } /** The caller's right to view the ontology itself is checked by the resource. */ @@ -105,9 +122,13 @@ public NativeOntologyDataGraph graph( access, store.boundConcepts(ontologyId, query.limit(), query.offset()), query.assetsPerConcept()); + addProfileFacts(access, clusters); + final var responses = clusters.stream().map(Cluster::response).toList(); + final var edges = edges(access, ontologyId, clusters, query.edgeLimit()); + addCounts(access, responses, edges); return new NativeOntologyDataGraph() - .withClusters(clusters.stream().map(Cluster::response).toList()) - .withEdges(edges(access, ontologyId, clusters, query.edgeLimit())) + .withClusters(responses) + .withEdges(edges) .withLineageEdges(lineage(clusters, query.lineageEdgeLimit())) .withPaging( new Paging() @@ -140,6 +161,122 @@ List clusters( return List.copyOf(clusters); } + /** + * Tables the caller may view the data profile of gain the facts of their latest stored profile, + * read for all tables of the page with one query. A table without a profile, or one the caller + * may not profile-view, is left as it is. + */ + void addProfileFacts(final Access access, final List clusters) { + fillProfileFacts( + access, + clusters.stream() + .flatMap(cluster -> cluster.response().getAssets().stream()) + .map( + asset -> + new FactSlot( + asset.getAsset(), + facts -> + asset + .withRowCount(facts.rowCount()) + .withProfiledAt(facts.profiledAt()) + .withSampled(facts.sampled()))) + .toList()); + } + + /** + * Gives each cluster the records of its class and each edge the links of its relation, as the + * stored profiles of identity tables state them. The edges' classes are read whether or not they + * have a cluster in this response. All of it is read once for the response, whatever its size. + */ + void addCounts( + final Access access, + final List clusters, + final List edges) { + final var relations = edges.stream().map(NativeOntologyDataGraphService::relation).toList(); + final var read = + counts.read( + access, + clusters.stream().map(cluster -> cluster.getConcept().getId()).toList(), + relations); + clusters.forEach( + cluster -> cluster.withRecords(read.records().get(cluster.getConcept().getId()))); + for (int index = 0; index < edges.size(); index++) { + edges.get(index).withLinks(read.links().get(relations.get(index))); + } + } + + private static OntologyCountRules.Relation relation(final NativeOntologyConceptEdge edge) { + return new OntologyCountRules.Relation( + edge.getFromConceptId(), + edge.getToConceptId(), + edge.getProperty() == null ? null : edge.getProperty().getId()); + } + + /** The same facts, under the same rules, for the tables of one page of a concept's bindings. */ + void addProfileFacts(final Access access, final OntologyConceptBindingsResponse page) { + fillProfileFacts( + access, + page.getAssets().stream() + .map( + asset -> + new FactSlot( + asset.getAsset(), + facts -> + asset + .withRowCount(facts.rowCount()) + .withProfiledAt(facts.profiledAt()) + .withSampled(facts.sampled()))) + .toList()); + } + + private void fillProfileFacts(final Access access, final List slots) { + final Map> tables = new LinkedHashMap<>(); + for (final var slot : slots) { + final var reference = slot.reference(); + if (Entity.TABLE.equals(reference.getType()) + && !nullOrEmpty(reference.getFullyQualifiedName())) { + tables + .computeIfAbsent( + FullyQualifiedName.buildHash(reference.getFullyQualifiedName()), + hash -> new ArrayList<>()) + .add(slot); + } + } + final var permitted = + viewableIds( + access, + tables.values().stream().map(group -> group.getFirst().reference()).toList(), + MetadataOperation.VIEW_DATA_PROFILE); + final var fqns = + tables.values().stream() + .map(List::getFirst) + .filter(slot -> permitted.contains(slot.reference().getId())) + .map(slot -> slot.reference().getFullyQualifiedName()) + .toList(); + if (!fqns.isEmpty()) { + latestProfileFacts(fqns) + .forEach((hash, facts) -> tables.get(hash).forEach(slot -> slot.sink().accept(facts))); + } + } + + private Map latestProfileFacts(final List fqns) { + final Map facts = new HashMap<>(); + for (final var record : + dao.profilerDataTimeSeriesDao() + .getLatestExtensionsBatch(fqns, ProfilerDataTimeSeriesDAO.TABLE_PROFILE_EXTENSION)) { + final var profile = JsonUtils.readValue(record.json(), EntityProfile.class); + final var data = + profile == null || profile.getProfileData() == null + ? null + : TableProfileFacts.from( + JsonUtils.convertValue(profile.getProfileData(), TableProfile.class)); + if (data != null) { + facts.merge(record.entityFQNHash(), data, TableProfileFacts::latest); + } + } + return facts; + } + private Map visibleBindings( final Access access, final Set conceptIds, final int previewSize) { final Map summaries = new LinkedHashMap<>(); @@ -190,13 +327,20 @@ Map visibleAssets(final Access access, final List r } Set viewableIds(final Access access, final List references) { + return viewableIds(access, references, MetadataOperation.VIEW_BASIC); + } + + Set viewableIds( + final Access access, + final List references, + final MetadataOperation operation) { if (references.isEmpty()) { return Set.of(); } if (DefaultAuthorizer.getSubjectContext(access.securityContext()).isAdmin()) { return references.stream().map(EntityReference::getId).collect(Collectors.toSet()); } - return visibility.viewableIds(access.securityContext(), references); + return visibility.viewableIds(access.securityContext(), operation, references); } private Map previewReferences(final Map summaries) { @@ -477,5 +621,8 @@ NativeOntologyAssetCluster resolve( } } + /** A table reference on a page, and where its profile facts go once they are read. */ + private record FactSlot(EntityReference reference, Consumer sink) {} + record Cluster(OntologyConcept concept, NativeOntologyAssetCluster response) {} } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java new file mode 100644 index 000000000000..ab6941f56fae --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingAccess.java @@ -0,0 +1,329 @@ +package org.openmetadata.service.ontology; + +import jakarta.ws.rs.core.SecurityContext; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.BulkFieldHydrator; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; +import org.openmetadata.service.security.policyevaluator.ResourceContextInterface; +import org.openmetadata.service.util.EntityUtil.Fields; + +/** + * Loads the catalog entities a binding names through their canonical repositories and applies the + * caller's current policies to each one. + */ +@Slf4j +final class OntologyBindingAccess { + private static final Set TABLE_COUNT_FIELDS = + Set.of("tableConstraints", "tablePartition", "tableProfilerConfig"); + private final Authorizer authorizer; + private final Function> repositories; + private final boolean unrestricted; + + OntologyBindingAccess( + final Authorizer authorizer, final Function> repositories) { + this(authorizer, repositories, false); + } + + private OntologyBindingAccess( + final Authorizer authorizer, + final Function> repositories, + final boolean unrestricted) { + this.authorizer = authorizer; + this.repositories = repositories; + this.unrestricted = unrestricted; + } + + /** + * An access that sees every definition and table, for work the server does for no caller. What + * it reads is the same for everyone, and each person's rights apply where a result is shown or + * acted on. + */ + static OntologyBindingAccess unrestricted( + final Function> repositories) { + return new OntologyBindingAccess(null, repositories, true); + } + + private void permit( + final SecurityContext securityContext, + final OperationContext operation, + final ResourceContextInterface resource) { + if (!unrestricted) { + authorizer.authorize(securityContext, operation, resource); + } + } + + /** The live entity, or an authorization or not-found failure for the caller. */ + EntityInterface authorized( + final Access access, final String type, final UUID id, final MetadataOperation operation) { + return authorized(access, repositories.apply(type), id, operation, Include.NON_DELETED); + } + + /** The working row of {@code id}, deleted or not, after the caller's right to it is checked. */ + EntityInterface authorizedWorking( + final Access access, final String type, final UUID id, final MetadataOperation operation) { + return authorized(access, repositories.apply(type), id, operation, Include.ALL); + } + + /** The working row of {@code id}, deleted or not, with no check of the caller's rights. */ + EntityInterface working(final Access access, final String type, final UUID id) { + final EntityRepository repository = repositories.apply(type); + return repository.get(access.uriInfo(), id, fields(repository), Include.ALL, false); + } + + /** + * A released definition, after the caller's right to it is checked with the policy inputs the + * catalog holds now for its id (owners, tags and domains), hydrated as a read of a release + * does. Nothing here reads the working row, which a later delete may have removed. + */ + EntityInterface authorized( + final Access access, + final String type, + final OntologyDefinition released, + final MetadataOperation operation) { + return hydratedAndAuthorized(access, repositories.apply(type), released, operation); + } + + /** The live entity when the caller may view it, and empty when it is hidden or gone. */ + Optional> readable(final Access access, final String type, final UUID id) { + try { + return Optional.of(authorized(access, type, id, MetadataOperation.VIEW_BASIC)); + } catch (final AuthorizationException | EntityNotFoundException unavailable) { + LOG.debug("A binding target of type {} is unavailable to the current reader", type); + return Optional.empty(); + } + } + + /** As above, and a deleted entity counts when the caller may view it. */ + boolean viewableEvenIfDeleted(final Access access, final String type, final UUID id) { + try { + authorizedWorking(access, type, id, MetadataOperation.VIEW_BASIC); + return true; + } catch (final AuthorizationException | EntityNotFoundException unavailable) { + LOG.debug("A binding target of type {} is unavailable to the current reader", type); + return false; + } + } + + /** Applies one more operation to an entity of {@code type} already loaded for the caller. */ + void require( + final Access access, + final String type, + final EntityInterface entity, + final MetadataOperation operation) { + require(access, repositories.apply(type), entity, operation); + } + + /** The live entities of one type that the caller may view, by id, read in one statement. */ + Map> viewable( + final Access access, final String type, final Collection ids) { + return viewable(access, type, ids, Set.of()); + } + + /** As above, with the fields in {@code extra} loaded as well. */ + Map> viewable( + final Access access, final String type, final Collection ids, final Set extra) { + final Map> viewable = new HashMap<>(); + final EntityRepository repository = repositories.apply(type); + loadViewable( + access, repository, ids.stream().distinct().toList(), viewable, fields(repository, extra)); + return viewable; + } + + /** + * The live tables that the caller may view, by id, read in one statement with the columns, the + * declared constraints, the partition and the profiler configuration that a count reads. + */ + Map viewableTables(final Access access, final Collection ids) { + final EntityRepository repository = repositories.apply(Entity.TABLE); + final Map> viewable = new HashMap<>(); + loadViewable( + access, + repository, + ids.stream().distinct().toList(), + viewable, + fields(repository, TABLE_COUNT_FIELDS)); + final Map tables = new HashMap<>(); + viewable.forEach((id, table) -> tables.put(id, (Table) table)); + return tables; + } + + /** + * The live tables among {@code ids}, whoever asks, with what the caller may view. + * + * @param live every table that exists, by id, with its columns and declared constraints + * @param viewable the ids of the tables the caller may view + */ + record TableViews(Map live, Set viewable) {} + + /** + * The live tables among {@code ids}, read in one statement whoever asks, and the ids of those + * the caller may view. An answer that must be the same for every caller is built from all of + * them, and what the caller may not view is masked afterwards. + */ + TableViews tableViews(final Access access, final Collection ids) { + return tableViews(access, repositories.apply(Entity.TABLE), ids.stream().distinct().toList()); + } + + private > TableViews tableViews( + final Access access, final EntityRepository repository, final List ids) { + if (ids.isEmpty()) { + return new TableViews(Map.of(), Set.of()); + } + final List tables = + repository.get( + access.uriInfo(), ids, fields(repository, TABLE_COUNT_FIELDS), Include.NON_DELETED); + final Map live = new HashMap<>(); + tables.forEach(table -> live.put(table.getId(), (Table) table)); + final Set viewable = new HashSet<>(); + viewableAmong(access, repository, tables).forEach(table -> viewable.add(table.getId())); + return new TableViews(live, viewable); + } + + /** The released definitions of one type that the caller may view, by id. */ + Map> viewable( + final Access access, final String type, final List released) { + return authorizedBatch(access, repositories.apply(type), released); + } + + private > T hydratedAndAuthorized( + final Access access, + final EntityRepository repository, + final OntologyDefinition released, + final MetadataOperation operation) { + final T entity = repository.getEntityClass().cast(released); + repository.setFieldsInBulk(ResourceContext.authorizationFields(repository), List.of(entity)); + permit( + access.securityContext(), + new OperationContext(repository.getEntityType(), operation), + new ResourceContext<>(repository.getEntityType(), entity, repository)); + return entity; + } + + private > Map> authorizedBatch( + final Access access, + final EntityRepository repository, + final List released) { + final List batch = released.stream().map(repository.getEntityClass()::cast).toList(); + // Every attribute a condition reads; setFieldsInBulk clears the fields it is not asked for. + repository.setFieldsInBulk(ResourceContext.authorizationFields(repository), batch); + final Map> viewable = new HashMap<>(); + int hidden = 0; + for (final T entity : batch) { + try { + permit( + access.securityContext(), + new OperationContext(repository.getEntityType(), MetadataOperation.VIEW_BASIC), + new ResourceContext<>(repository.getEntityType(), entity, repository)); + viewable.put(entity.getId(), entity); + } catch (final AuthorizationException denied) { + hidden++; + } + } + logHidden("Released", repository.getEntityType(), hidden, batch.size()); + return viewable; + } + + private > void loadViewable( + final Access access, + final EntityRepository repository, + final List ids, + final Map> viewable, + final Fields fields) { + if (ids.isEmpty()) { + return; + } + final List entities = repository.get(access.uriInfo(), ids, fields, Include.NON_DELETED); + viewableAmong(access, repository, entities) + .forEach(entity -> viewable.put(entity.getId(), entity)); + } + + /** The entities of one batch that the caller may view. */ + private > List viewableAmong( + final Access access, final EntityRepository repository, final List entities) { + final var tags = BulkFieldHydrator.forTags(repository, entities); + final List viewable = new ArrayList<>(); + int hidden = 0; + for (final T entity : entities) { + try { + permit( + access.securityContext(), + new OperationContext(repository.getEntityType(), MetadataOperation.VIEW_BASIC), + new ResourceContext<>(repository.getEntityType(), entity, repository, tags)); + viewable.add(entity); + } catch (final AuthorizationException denied) { + hidden++; + } + } + logHidden("Binding target", repository.getEntityType(), hidden, entities.size()); + return viewable; + } + + private static void logHidden( + final String what, final String type, final int hidden, final int total) { + if (hidden > 0) { + LOG.debug("{} of type {}: {} of {} are hidden from the reader", what, type, hidden, total); + } + } + + private > T authorized( + final Access access, + final EntityRepository repository, + final UUID id, + final MetadataOperation operation, + final Include include) { + final T entity = repository.get(access.uriInfo(), id, fields(repository), include, false); + permit( + access.securityContext(), + new OperationContext(repository.getEntityType(), operation), + new ResourceContext<>(repository.getEntityType(), entity, repository)); + return entity; + } + + private > void require( + final Access access, + final EntityRepository repository, + final EntityInterface entity, + final MetadataOperation operation) { + permit( + access.securityContext(), + new OperationContext(repository.getEntityType(), operation), + new ResourceContext<>( + repository.getEntityType(), repository.getEntityClass().cast(entity), repository)); + } + + private static Fields fields(final EntityRepository repository) { + return fields(repository, Set.of()); + } + + private static Fields fields(final EntityRepository repository, final Set extra) { + final var fieldNames = + new HashSet<>(ResourceContext.authorizationFields(repository).getFieldList()); + fieldNames.addAll(extra); + if (Entity.TABLE.equals(repository.getEntityType())) { + fieldNames.add(Entity.FIELD_COLUMNS); + } + return new Fields(fieldNames); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutor.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutor.java new file mode 100644 index 000000000000..6e07aeb6cea4 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutor.java @@ -0,0 +1,171 @@ +/* + * 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.ontology; + +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.PreconditionFailedException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyChangeOperationExecutor.OperationOutcome; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyConceptBindingService.RevisionGuard; +import org.openmetadata.service.security.Authorizer; + +/** + * Applies the binding operations of a change set. Each one goes through the write path of the + * bindings API as the caller who applies the set, inside the transaction and under the ontology + * lock that the apply already holds, so it can name a class and properties that earlier operations + * of the same set created. A refusal leaves that transaction as the bindings API would answer it. + */ +public final class OntologyBindingChangeExecutor { + private final OntologyConceptBindingService bindings; + private final OntologyConceptBindingStore store; + + public OntologyBindingChangeExecutor( + final OntologyConceptBindingService bindings, final OntologyConceptBindingStore store) { + this.bindings = bindings; + this.store = store; + } + + /** The write path the bindings API uses, deciding rights with the given authorizer. */ + public static OntologyBindingChangeExecutor production(final Authorizer authorizer) { + final OntologyConceptBindingStore store = + new OntologyConceptBindingStore( + Entity.getCollectionDAO(), OntologyConceptBindingStore.registeredAssetTables()); + return new OntologyBindingChangeExecutor( + new OntologyConceptBindingService(store, authorizer, Entity::getEntityRepository), store); + } + + /** + * Starts the binding writes of one attempt to apply a set as {@code caller}. A set is built + * against the bindings it read, so the attempt keeps the binding revision each class had before + * it wrote to that class and judges every operation on the class against that revision. The + * set's own earlier writes to a class therefore never make its later ones stale. + */ + public Function attempt( + final Access caller, final OntologyChangeSet changeSet) { + final Attempt attempt = new Attempt(caller, changeSet, new HashMap<>()); + return operation -> execute(attempt, operation); + } + + /** A binding operation is only ever part of a set that an ontology scopes. */ + private record Attempt( + Access caller, OntologyChangeSet changeSet, Map revisionsBefore) { + private UUID ontologyId() { + return changeSet.getOntology().getId(); + } + } + + private OperationOutcome execute(final Attempt attempt, final OntologyChangeOperation operation) { + final OntologyBindingChange change = operation.getBinding(); + final OntologyConcept concept = requireClass(attempt.ontologyId(), operation); + final Function propertyIds = requireProperties(attempt.ontologyId(), operation); + bindings.replace( + attempt.caller(), + concept.getId(), + OntologyBindingChanges.assetBinding(change, propertyIds), + revisionGuard(operation, concept.getId(), attempt.revisionsBefore())); + return new OperationOutcome(concept.getEntityReference(), null); + } + + private OntologyConcept requireClass( + final UUID ontologyId, final OntologyChangeOperation operation) { + final URI iri = operation.getBinding().getClassIri(); + return store.liveConcepts(ontologyId, List.of(iri)).stream() + .filter(concept -> iri.toString().equals(concept.getIri().toString())) + .findFirst() + .orElseThrow(() -> undeclared(operation, "class", iri)); + } + + private Function requireProperties( + final UUID ontologyId, final OntologyChangeOperation operation) { + final List iris = OntologyBindingChanges.propertyIris(operation.getBinding()); + final Map declared = + store.liveProperties(ontologyId, iris).stream() + .collect( + Collectors.toMap( + property -> property.getIri().toString(), + OntologyProperty::getId, + (first, second) -> first)); + iris.stream() + .filter(iri -> !declared.containsKey(iri.toString())) + .findFirst() + .ifPresent( + iri -> { + throw undeclared(operation, "property", iri); + }); + return iri -> declared.get(iri.toString()); + } + + private static BadRequestException undeclared( + final OntologyChangeOperation operation, final String kind, final URI iri) { + return new BadRequestException( + "Ontology operation '" + + operation.getId() + + "' needs the " + + kind + + " " + + iri + + ", which the ontology does not declare"); + } + + /** + * An operation that carries a revision was built against that revision of the class. One that + * carries none was built when the table was not yet bound to the class. Either way a class whose + * bindings another writer has changed since answers 412 and names the binding, so a client can + * rebuild that one operation. The first changed write of an attempt to a class records the + * revision the class had before the attempt in {@code revisionsBefore}. + */ + static RevisionGuard revisionGuard( + final OntologyChangeOperation operation, + final UUID conceptId, + final Map revisionsBefore) { + final Long built = OntologyBindingChanges.builtAgainst(operation); + return (current, existing) -> { + final long before = revisionsBefore.computeIfAbsent(conceptId, ignored -> current); + final boolean stale = built == null ? existing != null : built != before; + if (stale) { + throw new PreconditionFailedException(staleMessage(operation, built, before)); + } + return OntologyBindingRules.nextRevision(current, current); + }; + } + + private static String staleMessage( + final OntologyChangeOperation operation, final Long built, final long before) { + final OntologyBindingChange change = operation.getBinding(); + return "The binding of class " + + change.getClassIri() + + " to table " + + change.getTableId() + + " changed since operation '" + + operation.getId() + + "' was built: the operation carries " + + (built == null ? "no binding revision" : "binding revision " + built) + + " and the class is at binding revision " + + before; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChanges.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChanges.java new file mode 100644 index 000000000000..b7228d277e68 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingChanges.java @@ -0,0 +1,172 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import java.util.function.Function; +import org.openmetadata.schema.type.OntologyAssetBinding; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnBindingChange; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinChange; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.sdk.exception.WebServiceException; + +/** + * A table binding as a change set operation carries it: what the operation must look like before + * anything is read, and the binding it writes once its property IRIs have ids. + */ +public final class OntologyBindingChanges { + private OntologyBindingChanges() {} + + /** One table bound to one class. A draft writes each at most once. */ + record Target(String classIri, UUID tableId) { + static Target of(final OntologyBindingChange change) { + return new Target(change.getClassIri().toString(), change.getTableId()); + } + } + + public static boolean isBinding(final OntologyChangeOperation operation) { + return operation.getOperationType() == OntologyChangeOperationType.UPSERT_BINDING; + } + + /** The checks that read nothing: the payload, its IRIs and the binding rules on its fields. */ + static void validate(final OntologyChangeOperation operation) { + final OntologyBindingChange change = requirePayload(operation); + requireAbsolute(operation, change.getClassIri(), "classIri"); + listOrEmpty(change.getColumns()) + .forEach(column -> requireAbsolute(operation, propertyIri(column), "propertyIri")); + requireWholeRevision(operation); + requireBindingRules(operation, change); + } + + private static OntologyBindingChange requirePayload(final OntologyChangeOperation operation) { + final OntologyBindingChange change = operation.getBinding(); + if (change == null || OntologyChangeSetValidator.payloadCount(operation) != 1) { + throw invalid(operation, "operation UPSERT_BINDING requires exactly one binding"); + } + if (operation.getTargetId() != null) { + throw invalid( + operation, "a binding operation names its table in its payload, not in targetId"); + } + if (change.getTableId() == null) { + throw invalid(operation, "a binding requires a tableId"); + } + return change; + } + + /** + * The binding the operation writes, with each property IRI turned into the id {@code propertyIds} + * gives it. Every join is {@code inferred}, because only a person confirms one. + */ + static OntologyAssetBinding assetBinding( + final OntologyBindingChange change, final Function propertyIds) { + return new OntologyAssetBinding() + .withAssetType(OntologyBindingAssetType.TABLE) + .withAssetId(change.getTableId()) + .withRole(change.getRole()) + .withSubjectKey(change.getSubjectKey()) + .withRowFilter(change.getRowFilter()) + .withColumns( + listOrEmpty(change.getColumns()).stream() + .map(column -> columnBinding(column, propertyIds)) + .toList()); + } + + /** The binding revision the operation was built against, or null when it carries none. */ + static Long builtAgainst(final OntologyChangeOperation operation) { + final Double version = operation.getBaseVersion(); + return version == null ? null : version.longValue(); + } + + /** Every IRI the columns of a binding name, in the order they appear. */ + static List propertyIris(final OntologyBindingChange change) { + return listOrEmpty(change.getColumns()).stream() + .map(OntologyColumnBindingChange::getPropertyIri) + .distinct() + .toList(); + } + + private static OntologyColumnBinding columnBinding( + final OntologyColumnBindingChange column, final Function propertyIds) { + return new OntologyColumnBinding() + .withPropertyId(propertyIds.apply(column.getPropertyIri())) + .withColumnPath(column.getColumnPath()) + .withJoin(column.getJoin() == null ? null : inferredJoin(column.getJoin())); + } + + private static OntologyColumnJoin inferredJoin(final OntologyJoinChange join) { + return new OntologyColumnJoin() + .withTargetAssetId(join.getTargetAssetId()) + .withStatus(OntologyJoinStatus.INFERRED) + .withOn(join.getOn()); + } + + private static URI propertyIri(final OntologyColumnBindingChange column) { + return column == null ? null : column.getPropertyIri(); + } + + private static void requireAbsolute( + final OntologyChangeOperation operation, final URI iri, final String field) { + final String message = OntologyPropertyRules.relativeIriMessage(iri, field); + if (message != null) { + throw invalid(operation, message); + } + } + + private static void requireWholeRevision(final OntologyChangeOperation operation) { + final Double version = operation.getBaseVersion(); + final boolean whole = + version == null + || (version >= 0 + && version == Math.rint(version) + && version <= OntologyBindingRules.MAX_REVISION); + if (!whole) { + throw invalid( + operation, "baseVersion is the whole binding revision the operation was built against"); + } + } + + /** + * The rules the bindings API applies to the fields of a binding. They compare properties by id, + * so each IRI stands in as an id derived from its text. + */ + private static void requireBindingRules( + final OntologyChangeOperation operation, final OntologyBindingChange change) { + try { + OntologyBindingRules.validate(assetBinding(change, OntologyBindingChanges::standInId)); + } catch (final WebServiceException refused) { + throw invalid(operation, refused.getMessage()); + } + } + + private static UUID standInId(final URI propertyIri) { + return UUID.nameUUIDFromBytes(propertyIri.toString().getBytes(StandardCharsets.UTF_8)); + } + + private static BadRequestException invalid( + final OntologyChangeOperation operation, final String message) { + return OntologyChangeSetValidator.invalid(operation, message); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java index 29cc839ae1c5..28ebb3038627 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBindingRules.java @@ -4,9 +4,12 @@ import jakarta.ws.rs.ClientErrorException; import jakarta.ws.rs.core.Response; +import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.Set; +import java.util.UUID; import org.openmetadata.schema.FieldInterface; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; @@ -14,18 +17,28 @@ import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.OntologyAssetBinding; import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.sql.TypedValues; import org.openmetadata.service.util.ChildFieldResolver; public final class OntologyBindingRules { public static final int MAX_ASSET_COLUMNS = 100; public static final int MAX_CONCEPT_COLUMNS = 500; + public static final int MAX_KEY_COLUMNS = 16; + public static final int MAX_JOIN_PAIRS = 16; + public static final int MAX_FILTER_VALUES = TypedValues.MAX_LIST_VALUES; + public static final int MAX_FILTER_TEXT_LENGTH = TypedValues.MAX_TEXT_LENGTH; private static final int MAX_PATH_DEPTH = 32; private static final int MAX_SEGMENT_LENGTH = 256; - private static final long MAX_REVISION = 9_007_199_254_740_991L; + static final long MAX_REVISION = 9_007_199_254_740_991L; private static final Set BINDABLE_KINDS = Set.of(OntologyPropertyKind.DATA, OntologyPropertyKind.OBJECT); @@ -49,16 +62,114 @@ public static void validate(final OntologyAssetBinding asset) { "Only tables support column bindings, with at most 100 per asset"); } columns.forEach(OntologyBindingRules::validateColumn); - if (new HashSet<>(columns).size() != columns.size()) { + if (columns.stream().map(ColumnKey::of).distinct().count() != columns.size()) { throw new BadRequestException("Duplicate property and column bindings are not allowed"); } + validateRecordMapping(asset); + } + + /** One property bound to one column. Two bindings of the pair differ at most in their join. */ + private record ColumnKey(UUID propertyId, List columnPath) { + private static ColumnKey of(final OntologyColumnBinding binding) { + return new ColumnKey(binding.getPropertyId(), binding.getColumnPath()); + } } private static void validateColumn(final OntologyColumnBinding binding) { if (binding == null || binding.getPropertyId() == null) { throw new BadRequestException("A column binding requires a property UUID"); } - final var path = listOrEmpty(binding.getColumnPath()); + requireColumnPath(binding.getColumnPath()); + if (binding.getJoin() != null) { + validateJoin(binding.getJoin()); + } + } + + private static void validateJoin(final OntologyColumnJoin join) { + final var pairs = listOrEmpty(join.getOn()); + if (join.getTargetAssetId() == null + || join.getStatus() == null + || pairs.isEmpty() + || pairs.size() > MAX_JOIN_PAIRS + || pairs.stream().anyMatch(Objects::isNull) + || new HashSet<>(pairs).size() != pairs.size()) { + throw new BadRequestException( + "A join requires a target table, a status and 1 to 16 distinct column pairs"); + } + pairs.forEach(OntologyBindingRules::validatePair); + } + + private static void validatePair(final OntologyJoinColumnPair pair) { + requireColumnPath(pair.getChild()); + requireColumnPath(pair.getParent()); + } + + private static void validateRecordMapping(final OntologyAssetBinding asset) { + final var key = listOrEmpty(asset.getSubjectKey()); + final boolean mapped = + asset.getRole() != null || !key.isEmpty() || asset.getRowFilter() != null; + if (mapped && asset.getAssetType() != OntologyBindingAssetType.TABLE) { + throw new BadRequestException( + "Only table bindings take a role, a subject key or a row filter"); + } + validateSubjectKey(asset.getRole(), key); + if (asset.getRowFilter() != null) { + validateRowFilter(asset.getRowFilter()); + } + } + + private static void validateSubjectKey( + final OntologyBindingRole role, final List> key) { + if ((role == null) != key.isEmpty()) { + throw new BadRequestException( + "A role and a subject key are set together. A binding with a role names its key columns, and a binding without a role names none"); + } + if (key.size() > MAX_KEY_COLUMNS || new HashSet<>(key).size() != key.size()) { + throw new BadRequestException("A subject key takes 1 to 16 distinct columns"); + } + key.forEach(OntologyBindingRules::requireColumnPath); + } + + private static void validateRowFilter(final OntologyRowFilter filter) { + if (filter.getOperator() == null) { + throw new BadRequestException("A row filter requires a column and a supported operator"); + } + requireColumnPath(filter.getColumn()); + final Object value = filter.getValue(); + final boolean valid = + switch (filter.getOperator()) { + case IS_NULL, IS_NOT_NULL -> value == null; + case IN -> isFilterList(value); + case EQUALS, + NOT_EQUALS, + LESS_THAN, + LESS_THAN_OR_EQUALS, + GREATER_THAN, + GREATER_THAN_OR_EQUALS -> isFilterScalar(value); + }; + if (!valid) { + throw new BadRequestException( + "A row filter compares with a string of at most 1024 characters, a number or a boolean. `in` takes a list of 1 to 100 of them, and `isNull` and `isNotNull` take no value"); + } + } + + private static boolean isFilterList(final Object value) { + return value instanceof List values + && !values.isEmpty() + && values.size() <= MAX_FILTER_VALUES + && values.stream().allMatch(OntologyBindingRules::isFilterScalar); + } + + private static boolean isFilterScalar(final Object value) { + return value instanceof Number + || value instanceof Boolean + || (value instanceof String text + && text.length() <= MAX_FILTER_TEXT_LENGTH + && text.indexOf('\u0000') < 0); + } + + private static void requireColumnPath(final List columnPath) { + final var path = listOrEmpty(columnPath); if (path.isEmpty() || path.size() > MAX_PATH_DEPTH || path.stream().anyMatch(OntologyBindingRules::invalidSegment)) { @@ -80,6 +191,18 @@ public static boolean sameColumns( return new HashSet<>(listOrEmpty(stored)).equals(new HashSet<>(listOrEmpty(requested))); } + /** + * Whether a write would leave the stored binding as it is. Such a write is a no-op. It commits no + * revision and is checked against no rule. + */ + public static boolean sameBinding(final BindingRow stored, final OntologyAssetBinding requested) { + return stored.assetType() == requested.getAssetType() + && sameColumns(stored.columns(), requested.getColumns()) + && stored.role() == requested.getRole() + && listOrEmpty(stored.subjectKey()).equals(listOrEmpty(requested.getSubjectKey())) + && Objects.equals(stored.rowFilter(), requested.getRowFilter()); + } + /** The revision a changed write commits, or 409 when the writer did not see the current one. */ public static long nextRevision(final long current, final long expected) { if (current != expected || current == MAX_REVISION) { @@ -96,17 +219,46 @@ public static void requireColumnCapacity(final int boundColumns) { } public static Column resolveColumn(final Table table, final List path) { + final List resolved = resolveColumnPath(table, path); + return resolved.isEmpty() ? null : resolved.getLast(); + } + + /** + * The columns from a top-level column down to the one {@code path} names, one for each segment, + * or an empty list when a segment names no column. + */ + public static List resolveColumnPath(final Table table, final List path) { + final List resolved = new ArrayList<>(); List candidates = ChildFieldResolver.childrenOf(table, Entity.TABLE); - FieldInterface selected = null; for (final String segment : path) { - selected = + final FieldInterface selected = candidates.stream() .filter(column -> segment.equals(column.getName())) .findFirst() .orElse(null); - candidates = selected == null ? List.of() : listOrEmpty(selected.getChildren()); + if (!(selected instanceof Column column)) { + return List.of(); + } + resolved.add(column); + candidates = listOrEmpty(column.getChildren()); + } + return resolved; + } + + /** + * A column bound to an OBJECT property says where its related records live, so it carries a join. + * A column bound to a DATA property holds the values themselves and carries none. + */ + public static void requireJoinFor( + final OntologyProperty property, final OntologyColumnBinding binding) { + final boolean relation = property.getKind() == OntologyPropertyKind.OBJECT; + if (relation && binding.getJoin() == null) { + throw new BadRequestException( + "A column bound to an OBJECT property requires a join to the table that holds the related records"); + } + if (!relation && binding.getJoin() != null) { + throw new BadRequestException("Only a column bound to an OBJECT property takes a join"); } - return selected instanceof Column column ? column : null; } /** diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBoundTables.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBoundTables.java new file mode 100644 index 000000000000..31ed359aa447 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyBoundTables.java @@ -0,0 +1,88 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.BoundTable; + +/** Turns a stored table binding into the bound table that the search-around hop rules read. */ +final class OntologyBoundTables { + private OntologyBoundTables() {} + + /** + * The table as one concept binds it. A column binding whose property is not in {@code properties} + * or whose column left the table is left out. + */ + static BoundTable of( + final Table table, final BindingRow row, final Map properties) { + final List resolved = + row.columns().stream() + .filter(binding -> properties.containsKey(binding.getPropertyId())) + .filter( + binding -> + OntologyBindingRules.resolveColumn(table, binding.getColumnPath()) != null) + .toList(); + return new BoundTable( + table.getFullyQualifiedName(), + table.getServiceType() == null ? null : table.getServiceType().value(), + resolved.stream().map(OntologyColumnBinding::getColumnPath).toList(), + objectColumns(resolved, properties), + identifierColumn(resolved, properties), + listOrEmpty(table.getTableConstraints()), + () -> OntologyTableBindingChecks.storedRowFilter(table, row.rowFilter())); + } + + /** The column each object property is bound to, the first binding winning. */ + private static Map> objectColumns( + final List resolved, final Map properties) { + return resolved.stream() + .filter(binding -> kindOf(properties, binding) == OntologyPropertyKind.OBJECT) + .collect( + Collectors.toMap( + OntologyColumnBinding::getPropertyId, + OntologyColumnBinding::getColumnPath, + (first, ignored) -> first, + LinkedHashMap::new)); + } + + private static List identifierColumn( + final List resolved, final Map properties) { + return resolved.stream() + .filter(binding -> isIdentifier(properties.get(binding.getPropertyId()))) + .findFirst() + .map(OntologyColumnBinding::getColumnPath) + .orElse(List.of()); + } + + private static OntologyPropertyKind kindOf( + final Map properties, final OntologyColumnBinding binding) { + return properties.get(binding.getPropertyId()).getKind(); + } + + private static boolean isIdentifier(final OntologyProperty property) { + return property.getKind() == OntologyPropertyKind.DATA + && Boolean.TRUE.equals(property.getIsIdentifier()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeApplicationService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeApplicationService.java index 84b4571591fc..995488a950cf 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeApplicationService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeApplicationService.java @@ -26,6 +26,7 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.function.Function; import java.util.function.Supplier; import org.apache.commons.codec.digest.DigestUtils; import org.openmetadata.schema.entity.data.OntologyChangeSet; @@ -49,7 +50,9 @@ import org.openmetadata.service.jdbi3.OntologyConceptRepository; import org.openmetadata.service.jdbi3.OntologyPropertyRepository; import org.openmetadata.service.jdbi3.OntologyRepository; +import org.openmetadata.service.jdbi3.OntologyShapeRepository; import org.openmetadata.service.ontology.OntologyChangeOperationExecutor.OperationOutcome; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.ontology.OntologyPackInstallations.PreparedPackInstall; import org.openmetadata.service.util.RestUtil.PutResponse; @@ -76,13 +79,33 @@ public final class OntologyChangeApplicationService { private final OntologyWorkingSnapshot workingSnapshot; private final PackInstallWriter installWriter; private final OntologyPackInstallations.PlanLedger planLedger; + private final BindingWriter bindings; private final Clock clock; + /** For a job, which applies with no caller and so writes no binding. */ public OntologyChangeApplicationService( final OntologyChangeSetRepository changeSetRepository, final GlossaryTermRepository termRepository, final Clock clock) { - this(changeSetRepository, productionDependencies(termRepository, clock), clock); + this( + changeSetRepository, + productionDependencies( + termRepository, + clock, + (caller, changeSet) -> OntologyChangeApplicationService::withoutCaller), + clock); + } + + /** For the change set API, where a caller applies and each binding is written as that caller. */ + public OntologyChangeApplicationService( + final OntologyChangeSetRepository changeSetRepository, + final GlossaryTermRepository termRepository, + final Clock clock, + final OntologyBindingChangeExecutor bindings) { + this( + changeSetRepository, + productionDependencies(termRepository, clock, bindings::attempt), + clock); } OntologyChangeApplicationService( @@ -99,22 +122,56 @@ public OntologyChangeApplicationService( this.workingSnapshot = dependencies.workingSnapshot(); this.installWriter = dependencies.installWriter(); this.planLedger = dependencies.planLedger(); + this.bindings = dependencies.bindings(); this.clock = clock; } + /** Applies with no caller at hand, as a job does. A binding operation is refused. */ public PutResponse apply( final UriInfo uriInfo, final UUID changeSetId, final String user) { + return apply( + requireApplicable(changeSetId), + uriInfo, + user, + () -> OntologyChangeApplicationService::withoutCaller); + } + + /** + * Applies as the caller. Each binding operation is written with the rights this caller holds when + * the set is applied, whoever built the set. + */ + public PutResponse apply(final Access caller, final UUID changeSetId) { final OntologyChangeSet changeSet = requireApplicable(changeSetId); + return apply( + changeSet, + caller.uriInfo(), + caller.securityContext().getUserPrincipal().getName(), + () -> bindings.attempt(caller, changeSet)); + } + + private PutResponse apply( + final OntologyChangeSet changeSet, + final UriInfo uriInfo, + final String user, + final Supplier> bindingAttempt) { final List operations = activeOperations(changeSet); preflight.validate(changeSet, operations); final ApplicationExecution execution = - new ApplicationExecution(uriInfo, changeSetId, user, new ArrayList<>()); + new ApplicationExecution( + uriInfo, changeSet.getId(), user, new ArrayList<>(), bindingAttempt); final PutResponse response = applyOperations(execution, changeSet, operations); publishApplied(response.getEntity(), user); return response; } + private static OperationOutcome withoutCaller(final OntologyChangeOperation operation) { + throw new BadRequestException( + "Ontology operation '" + + operation.getId() + + "' writes a binding, which only a caller of the change set API can apply"); + } + private PutResponse applyOperations( final ApplicationExecution execution, final OntologyChangeSet changeSet, @@ -192,14 +249,33 @@ private PutResponse applyAtomically( return transition(execution, OntologyChangeSetState.APPLIED, result); } + /** The transaction can run this more than once, so each run starts its own binding writes. */ private void executeOperations( final ApplicationExecution execution, final List operations) { + final Function bindingWrite = + execution.bindingAttempt().get(); for (final OntologyChangeOperation operation : operations) { - executeOperation(execution, operation); + executeOperation(execution, bindingWrite, operation); } } + /** + * A binding operation is checked as a request to the bindings API is. A refusal leaves the + * transaction and answers the apply with its own status, so nothing is written and the set keeps + * its state. Any other operation that fails records a failed application. + */ private void executeOperation( + final ApplicationExecution execution, + final Function bindingWrite, + final OntologyChangeOperation operation) { + if (OntologyBindingChanges.isBinding(operation)) { + execution.results().add(appliedResult(operation, bindingWrite.apply(operation))); + } else { + executeDefinition(execution, operation); + } + } + + private void executeDefinition( final ApplicationExecution execution, final OntologyChangeOperation operation) { try { final OperationOutcome outcome = @@ -350,7 +426,9 @@ private static OntologyChangeOperationResult result( } private static Dependencies productionDependencies( - final GlossaryTermRepository termRepository, final Clock clock) { + final GlossaryTermRepository termRepository, + final Clock clock, + final BindingWriter bindings) { return new Dependencies( productionPreflight(), new OntologyChangeOperationExecutor( @@ -359,9 +437,12 @@ private static Dependencies productionDependencies( clock, new NativeOntologyChangeExecutor( (OntologyRepository) Entity.getEntityRepository(Entity.ONTOLOGY), - (OntologyConceptRepository) Entity.getEntityRepository(Entity.ONTOLOGY_CONCEPT), - (OntologyPropertyRepository) Entity.getEntityRepository(Entity.ONTOLOGY_PROPERTY), - (OntologyAxiomRepository) Entity.getEntityRepository(Entity.ONTOLOGY_AXIOM), + new NativeOntologyChangeExecutor.Definitions( + (OntologyConceptRepository) Entity.getEntityRepository(Entity.ONTOLOGY_CONCEPT), + (OntologyPropertyRepository) + Entity.getEntityRepository(Entity.ONTOLOGY_PROPERTY), + (OntologyAxiomRepository) Entity.getEntityRepository(Entity.ONTOLOGY_AXIOM), + (OntologyShapeRepository) Entity.getEntityRepository(Entity.ONTOLOGY_SHAPE)), clock)), new OntologyChangeEventPublisher(), work -> termRepository.executeInTransaction(work), @@ -372,7 +453,8 @@ private static Dependencies productionDependencies( ((OntologyRepository) Entity.getEntityRepository(Entity.ONTOLOGY)) .recordPackInstallation( install.ontologyId(), install.installation(), install.moduleOrder(), user), - OntologyPackInstallJobManager.ledger(Entity.getJobDAO())); + OntologyPackInstallJobManager.ledger(Entity.getJobDAO()), + bindings); } private static void invalidateEntityCache(final EntityReference entity) { @@ -386,7 +468,7 @@ private static OntologyChangePreflight productionPreflight() { OntologyChangeApplicationService::declaredConcepts); } - private static Set declaredConcepts(final UUID ontologyId, final Set iris) { + public static Set declaredConcepts(final UUID ontologyId, final Set iris) { final var concepts = Entity.getCollectionDAO().ontologyConceptDAO(); final Set declared = new HashSet<>(); Lists.partition(new ArrayList<>(iris), DECLARATION_BATCH) @@ -417,7 +499,15 @@ record Dependencies( OntologyPackCatalog packs, OntologyWorkingSnapshot workingSnapshot, PackInstallWriter installWriter, - OntologyPackInstallations.PlanLedger planLedger) {} + OntologyPackInstallations.PlanLedger planLedger, + BindingWriter bindings) {} + + /** Starts the binding writes of one attempt to apply a set, as the caller who applies it. */ + @FunctionalInterface + interface BindingWriter { + Function attempt( + Access caller, OntologyChangeSet changeSet); + } @FunctionalInterface interface PackInstallWriter { @@ -438,7 +528,8 @@ private record ApplicationExecution( UriInfo uriInfo, UUID changeSetId, String user, - List results) {} + List results, + Supplier> bindingAttempt) {} private static final class OperationApplicationException extends RuntimeException { private OperationApplicationException(final RuntimeException cause) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeEvidenceView.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeEvidenceView.java new file mode 100644 index 000000000000..0c4bea2dfdac --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeEvidenceView.java @@ -0,0 +1,221 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.type.OntologyChangeEvidence; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.PreconditionFailedException; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.security.Authorizer; + +/** + * The evidence of change set operations as one reader may see it and may write it. A read keeps + * the entries whose table the reader may view and sets, on each operation that stores evidence, how + * many it left out. A save stores the entries the reader sends about tables it may view, beside the + * stored entries it was not shown. One view serves one request, so a table is decided once however + * many operations, rows and versions name it. + * + *

A recorded change and a change event have no single reader. They hold the operations {@link + * #withoutEvidence}, so this view has only the operations of a change set to mask. + */ +public final class OntologyChangeEvidenceView implements UnaryOperator { + /** The most entries an operation stores, as the operation schema bounds its evidence. */ + static final int MAX_ENTRIES = 20; + + private static final int TABLE_BATCH = 500; + + private final ViewableTables tables; + private final Map decided = new HashMap<>(); + + /** The subset of these tables that the reader may view. A table that is gone is not in it. */ + @FunctionalInterface + public interface ViewableTables { + Set among(List tableIds); + } + + public OntologyChangeEvidenceView(final ViewableTables tables) { + this.tables = tables; + } + + /** The view of one caller, who may view a table when the caller's policies allow ViewBasic. */ + public static OntologyChangeEvidenceView of(final Authorizer authorizer, final Access reader) { + final OntologyBindingAccess catalog = + new OntologyBindingAccess(authorizer, Entity::getEntityRepository); + return new OntologyChangeEvidenceView( + ids -> catalog.viewable(reader, Entity.TABLE, ids).keySet()); + } + + /** The operations with no evidence, as a recorded change holds them for every reader alike. */ + public static List withoutEvidence( + final List operations) { + return listOrEmpty(operations).stream() + .map( + operation -> + listOrEmpty(operation.getEvidence()).isEmpty() + ? operation + : JsonUtils.deepCopy(operation, OntologyChangeOperation.class) + .withEvidence(null)) + .toList(); + } + + /** Masks the operations of one change set in place. */ + @Override + public OntologyChangeSet apply(final OntologyChangeSet changeSet) { + applyAll(List.of(changeSet)); + return changeSet; + } + + /** Masks every change set in place, deciding the tables of all of them in one read. */ + public void applyAll(final Collection changeSets) { + final List operations = + changeSets.stream() + .flatMap(changeSet -> listOrEmpty(changeSet.getOperations()).stream()) + .toList(); + decide(operations.stream()); + operations.forEach(this::mask); + } + + /** + * The operations to store when the reader saves {@code incoming} over the {@code stored} + * operations of a draft, or over none when the reader creates the draft. Evidence passes through + * the reader's view in this direction too. An entry the reader sends about a table it may not + * view is not stored. Storing it would repeat a withheld entry, and merging the repeat would tell + * the reader what is withheld. Each stored entry the reader was not shown stays where the draft + * stores it. + */ + public List savedByReader( + final List stored, final List incoming) { + return savedByReader(stored, incoming, Map.of()); + } + + /** As above, refusing the save when an operation's sight changed since the writer read it. */ + public List savedByReader( + final List stored, + final List incoming, + final Map readWithheldCounts) { + final Map> storedEvidence = + stored.stream() + .collect( + Collectors.toMap( + OntologyChangeOperation::getId, + operation -> listOrEmpty(operation.getEvidence()), + (first, second) -> first)); + decide(Stream.concat(stored.stream(), incoming.stream())); + for (final OntologyChangeOperation operation : incoming) { + final List kept = storedEvidence.get(operation.getId()); + requireSameSight(operation, kept, readWithheldCounts.get(operation.getId())); + if (!listOrEmpty(kept).isEmpty() || !listOrEmpty(operation.getEvidence()).isEmpty()) { + save(operation, listOrEmpty(kept)); + } + } + return incoming; + } + + /** + * A writer sends back how many entries its read withheld. When the stored operation withholds a + * different number from this writer now, a table came into or went out of its sight after the + * read, and the entries it sends no longer say what it read. The one change it cannot see is a + * table that becomes visible while another becomes hidden, which leaves the number equal. + */ + private void requireSameSight( + final OntologyChangeOperation operation, + final List stored, + final Integer readWithheld) { + if (stored != null && readWithheld != null) { + final long withheldNow = stored.stream().filter(entry -> !mayView(entry)).count(); + if (readWithheld.longValue() != withheldNow) { + throw new PreconditionFailedException( + "The evidence of operation '" + + operation.getId() + + "' changed for you since you read this change set. Read the change set again," + + " then save."); + } + } + } + + /** + * Walks the stored entries in order. A withheld one keeps its place, and the place of a shown one + * goes to the next entry the reader sent about a table it may view. + */ + private void save( + final OntologyChangeOperation operation, final List stored) { + final Iterator sent = + listOrEmpty(operation.getEvidence()).stream().filter(this::mayView).iterator(); + final List kept = new ArrayList<>(); + int withheld = 0; + for (final OntologyChangeEvidence entry : stored) { + if (!mayView(entry)) { + kept.add(entry); + withheld++; + } else if (sent.hasNext()) { + kept.add(sent.next()); + } + } + sent.forEachRemaining(kept::add); + if (kept.size() > MAX_ENTRIES) { + throw OntologyChangeSetValidator.invalid( + operation, + "evidence holds at most " + + MAX_ENTRIES + + " entries, counting the " + + withheld + + " that a read withheld"); + } + operation.setEvidence(kept); + } + + private void decide(final Stream operations) { + final List undecided = + operations + .flatMap(operation -> listOrEmpty(operation.getEvidence()).stream()) + .map(OntologyChangeEvidence::getTableId) + .filter(tableId -> !decided.containsKey(tableId)) + .distinct() + .toList(); + for (final List batch : Lists.partition(undecided, TABLE_BATCH)) { + final Set viewable = tables.among(batch); + batch.forEach(tableId -> decided.put(tableId, viewable.contains(tableId))); + } + } + + private void mask(final OntologyChangeOperation operation) { + final List stored = listOrEmpty(operation.getEvidence()); + if (!stored.isEmpty()) { + final List shown = stored.stream().filter(this::mayView).toList(); + operation.setEvidence(shown); + operation.setWithheldEvidenceCount(stored.size() - shown.size()); + } + } + + private boolean mayView(final OntologyChangeEvidence entry) { + return Boolean.TRUE.equals(decided.get(entry.getTableId())); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeOperationExecutor.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeOperationExecutor.java index 2b0d702de141..b17ef264f96c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeOperationExecutor.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeOperationExecutor.java @@ -93,7 +93,10 @@ public OperationOutcome execute( UPSERT_PROPERTY, DELETE_PROPERTY, UPSERT_AXIOM, - DELETE_AXIOM -> nativeExecutor().execute(uriInfo, user, operation); + DELETE_AXIOM, + UPSERT_SHAPE -> nativeExecutor().execute(uriInfo, user, operation); + case UPSERT_BINDING -> throw new BadRequestException( + "A binding operation is written through the bindings of its class, as a caller"); }; return outcome; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangePreflight.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangePreflight.java index e3214c96aed3..35f2dacf1fec 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangePreflight.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangePreflight.java @@ -90,26 +90,12 @@ public void validate( */ private void requireReferencedConcepts( final UUID ontologyId, final List operations) { - final Set created = - operations.stream() - .filter( - operation -> - operation.getOperationType() == OntologyChangeOperationType.UPSERT_CONCEPT - && operation.getConcept() != null) - .map(operation -> operation.getConcept().getIri().toString()) - .collect(Collectors.toSet()); + final Set created = createdConceptIris(operations); final Predicate isDataProperty = dataProperties(operations); final Map> unresolved = new LinkedHashMap<>(); for (final OntologyChangeOperation operation : operations) { - final Set missing = new TreeSet<>(classPositions(operation, isDataProperty)); - if (operation.getRequiresConceptIris() != null) { - operation.getRequiresConceptIris().forEach(iri -> missing.add(iri.toString())); - } - missing.removeIf( - iri -> - created.contains(iri) - || OntologyClassHierarchy.isVocabularyClass(iri) - || OwlEntityDeclarations.isDatatype(iri)); + final Set missing = neededClassIris(operation, isDataProperty); + missing.removeIf(created::contains); if (!missing.isEmpty()) { unresolved.put(operation, missing); } @@ -135,6 +121,33 @@ private void requireReferencedConcepts( }); } + /** The IRIs of the concepts these operations create. */ + public static Set createdConceptIris(final List operations) { + return operations.stream() + .filter( + operation -> + operation.getOperationType() == OntologyChangeOperationType.UPSERT_CONCEPT + && operation.getConcept() != null) + .map(operation -> operation.getConcept().getIri().toString()) + .collect(Collectors.toSet()); + } + + /** + * The class IRIs the operation needs, in sorted order and as a set the caller may shrink: + * vocabulary classes and datatypes are never needed from the ontology. + */ + public static Set neededClassIris( + final OntologyChangeOperation operation, final Predicate isDataProperty) { + final Set needed = new TreeSet<>(classPositions(operation, isDataProperty)); + if (operation.getRequiresConceptIris() != null) { + operation.getRequiresConceptIris().forEach(iri -> needed.add(iri.toString())); + } + needed.removeIf( + iri -> + OntologyClassHierarchy.isVocabularyClass(iri) || OwlEntityDeclarations.isDatatype(iri)); + return needed; + } + private static Set classPositions( final OntologyChangeOperation operation, final Predicate isDataProperty) { final List positions = @@ -149,6 +162,12 @@ private static Set classPositions( + "' has a class expression with more than 10000 steps"); }); case UPSERT_PROPERTY -> OntologyClassHierarchy.classPositions(operation.getProperty()); + case UPSERT_BINDING -> List.of( + new OntologyClassHierarchy.ClassPosition( + "/binding/classIri", operation.getBinding().getClassIri())); + case UPSERT_SHAPE -> List.of( + new OntologyClassHierarchy.ClassPosition( + "/shape/targetConcept", operation.getShape().getTargetConcept())); default -> List.of(); }; return positions.stream() @@ -158,7 +177,8 @@ private static Set classPositions( .collect(Collectors.toSet()); } - private static Predicate dataProperties(final List operations) { + /** Whether an IRI is a data property, by the properties these operations declare. */ + public static Predicate dataProperties(final List operations) { final Map inSet = new HashMap<>(); operations.stream() .filter( @@ -232,6 +252,8 @@ private void validateScope( UPSERT_AXIOM, DELETE_AXIOM -> throw new BadRequestException( "Axioms must be authored in an ontology, not a glossary change set"); + case UPSERT_BINDING, UPSERT_SHAPE -> throw new BadRequestException( + "Bindings and shapes must be authored in an ontology, not a glossary change set"); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java new file mode 100644 index 000000000000..048c27768ba1 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccess.java @@ -0,0 +1,132 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import jakarta.ws.rs.core.SecurityContext; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; +import java.util.function.Supplier; +import org.openmetadata.schema.entity.data.Glossary; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.CreateResourceContext; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; + +/** + * The right that reads the operations of a change set, whatever the path that returns them. A + * change set holds operations that no release has published, so it is read with the right that + * edits its scope: edit on the ontology it targets, or edit on each glossary it targets. Every + * response that carries the operations asks for this, so a user who may only view change sets + * learns nothing a draft read would not show. + */ +public final class OntologyChangeSetReadAccess { + /** The fields a check needs to find the scope of a stored change set. */ + public static final String SCOPE_FIELDS = "operations"; + + private OntologyChangeSetReadAccess() {} + + /** Throws the authorizer's refusal unless the caller may read the operations of this change set. */ + public static void requireRead( + final Authorizer authorizer, + final SecurityContext securityContext, + final OntologyChangeSet changeSet) { + if (changeSet.getOntology() != null) { + authorizer.authorize( + securityContext, + new OperationContext(Entity.ONTOLOGY, MetadataOperation.EDIT_ALL), + new ResourceContext<>(Entity.ONTOLOGY, changeSet.getOntology().getId(), null)); + return; + } + for (final EntityReference glossary : listOrEmpty(changeSet.getGlossaries())) { + requireGlossaryRead( + authorizer, securityContext, glossary, plannedGlossary(changeSet, glossary)); + } + } + + /** + * Whether the caller may read the change set the loader returns. A refusal answers false, and so + * does a change set that cannot be loaded or whose scope no longer exists: nothing decides the + * right for it, so nothing is shown. + */ + public static boolean mayRead( + final Authorizer authorizer, + final SecurityContext securityContext, + final Supplier loader) { + try { + requireRead(authorizer, securityContext, loader.get()); + return true; + } catch (AuthorizationException | EntityNotFoundException unreadable) { + return false; + } + } + + /** + * The snapshots of the change sets the caller may read. The right is asked once for each change + * set, whatever the number of its snapshots, and a snapshot of a change set the caller may not + * read, or that cannot be decided, is dropped. + */ + public static List readable( + final Authorizer authorizer, + final SecurityContext securityContext, + final List snapshots, + final Function loader) { + final Map decided = new HashMap<>(); + return snapshots.stream() + .filter( + snapshot -> + decided.computeIfAbsent( + snapshot.getId(), + id -> mayRead(authorizer, securityContext, () -> loader.apply(id)))) + .toList(); + } + + private static void requireGlossaryRead( + final Authorizer authorizer, + final SecurityContext securityContext, + final EntityReference glossary, + final Glossary planned) { + if (planned != null) { + authorizer.authorize( + securityContext, + new OperationContext(Entity.GLOSSARY, MetadataOperation.CREATE), + new CreateResourceContext<>(Entity.GLOSSARY, planned)); + return; + } + authorizer.authorize( + securityContext, + new OperationContext(Entity.GLOSSARY, MetadataOperation.EDIT_ALL), + new ResourceContext<>(Entity.GLOSSARY, glossary.getId(), null)); + } + + private static Glossary plannedGlossary( + final OntologyChangeSet changeSet, final EntityReference glossary) { + return listOrEmpty(changeSet.getOperations()).stream() + .filter(change -> change.getGlossary() != null) + .map(change -> change.getGlossary()) + .filter(candidate -> candidate.getId().equals(glossary.getId())) + .findFirst() + .orElse(null); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetValidator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetValidator.java index 1d8fa2a8cf73..ad837b0cbfa7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetValidator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyChangeSetValidator.java @@ -42,10 +42,35 @@ public static void normalizeAndValidate(final OntologyChangeSet changeSet) { } else { validateOperations(operations, cursor, plannedTermIds(operations)); } + operations.forEach(OntologyChangeSetValidator::normalizeSupport); changeSet.setOperations(operations); changeSet.setUndoCursor(cursor); } + /** + * What an operation may carry beside its payload. A basis says where a shape comes from, so only + * a shape operation takes one. The count of withheld evidence belongs to a read and is dropped, + * so it is never stored. An empty evidence list is stored as no evidence, so the two never + * differ in a recorded change. + */ + private static void normalizeSupport(final OntologyChangeOperation operation) { + if (operation.getBasis() != null + && operation.getOperationType() != OntologyChangeOperationType.UPSERT_SHAPE) { + throw invalid(operation, "only a shape operation carries a basis"); + } + final boolean incomplete = + listOrEmpty(operation.getEvidence()).stream() + .anyMatch( + entry -> entry == null || entry.getTableId() == null || entry.getKind() == null); + if (incomplete) { + throw invalid(operation, "every evidence entry names a table and a kind"); + } + if (listOrEmpty(operation.getEvidence()).isEmpty()) { + operation.setEvidence(null); + } + operation.setWithheldEvidenceCount(null); + } + private static void validateOperations( final List operations, final int cursor, @@ -162,6 +187,8 @@ static int payloadCount(final OntologyChangeOperation operation) { count += operation.getAxiom() == null ? 0 : 1; count += operation.getConcept() == null ? 0 : 1; count += operation.getProperty() == null ? 0 : 1; + count += operation.getBinding() == null ? 0 : 1; + count += operation.getShape() == null ? 0 : 1; return count; } @@ -299,11 +326,13 @@ private static PayloadKind payloadKind(final OntologyChangeOperationType operati UPSERT_AXIOM, DELETE_AXIOM -> throw new BadRequestException( "Axioms must be authored in an ontology, not a glossary change set"); + case UPSERT_BINDING, UPSERT_SHAPE -> throw new BadRequestException( + "Bindings and shapes must be authored in an ontology, not a glossary change set"); }; return payloadKind; } - private static BadRequestException invalid( + static BadRequestException invalid( final OntologyChangeOperation operation, final String message) { return new BadRequestException( "Ontology operation '" + operation.getId() + "' is invalid: " + message); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckGates.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckGates.java new file mode 100644 index 000000000000..6ab972820896 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckGates.java @@ -0,0 +1,215 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; +import static org.openmetadata.service.ontology.OntologySettled.of; +import static org.openmetadata.service.ontology.OntologySettled.refused; +import static org.openmetadata.service.ontology.OntologySettled.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.IntStream; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyCheckProbe.Reach; +import org.openmetadata.service.ontology.OntologyCheckProbe.ReadTable; +import org.openmetadata.service.ontology.OntologyPartOutcome.Check; +import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; +import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Subject; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.ontology.sql.TypedRowFilter; + +/** + * What every rule of the shape check compile asks of a mapping before it answers: each is a value, + * or the reason the mapping gives no exact test. A binding is read as it is stored, and the table + * it names may have changed since, so a column that left or a filter that no longer parses is an + * answer here and never an error. + */ +final class OntologyCheckGates { + private OntologyCheckGates() {} + + /** The records of a class: its identity table as a statement reads it. */ + record Records(ReadTable identity) {} + + /** + * How a statement gets from the records of a class to the table that holds a property. + * + * @param holder the contributing table, or null when the identity table holds the property + */ + record Route(ReadTable identity, ReadTable holder, List keyPairs) {} + + static boolean isRelation(final OntologyProperty property) { + return property.getKind() == OntologyPropertyKind.OBJECT; + } + + static OntologySettled records(final Subject subject) { + return subject + .identity() + .map(identity -> readTable(identity).map(Records::new)) + .orElseGet(() -> refused(OntologyShapeCheckReason.NO_IDENTITY_TABLE)); + } + + /** The table, when its subject key still resolves and its row filter still parses. */ + static OntologySettled readTable(final MappedTable table) { + final List> key = table.keyPaths(); + if (key.isEmpty() || !key.stream().allMatch(table::holds)) { + return refused(OntologyShapeCheckReason.COLUMN_MISSING); + } + return filter(table).map(filter -> new ReadTable(table, filter.orElse(null))); + } + + private static OntologySettled> filter(final MappedTable table) { + final OntologyRowFilter stored = table.row().rowFilter(); + if (stored == null) { + return of(Optional.empty()); + } + if (!table.holds(stored.getColumn())) { + return refused(OntologyShapeCheckReason.COLUMN_MISSING); + } + try { + return of(Optional.of(OntologyTableBindingChecks.typedRowFilter(table.table(), stored))); + } catch (final BadRequestException unparsed) { + // The filter parsed when it was saved, and the column has another data type now. + return refused(OntologyShapeCheckReason.VALUE_DOES_NOT_FIT_COLUMN); + } + } + + /** The column a data property is bound to at a place. */ + static OntologySettled column(final Place place) { + final Column column = + OntologyBindingRules.resolveColumn(place.holder().table(), place.binding().getColumnPath()); + return column == null ? refused(OntologyShapeCheckReason.COLUMN_MISSING) : of(column); + } + + /** + * The columns whose values are the values of the property at a place: the bound column of a + * data property, and the columns of the confirmed join of a relation. + */ + static OntologySettled>> values( + final OntologyProperty property, final Place place) { + if (!isRelation(property)) { + return held(place.holder(), List.of(place.binding().getColumnPath())); + } + return join(place) + .then( + join -> + held( + place.holder(), + join.getOn().stream().map(OntologyJoinColumnPair::getChild).toList())); + } + + /** The join of a relation at a place, when a person has confirmed it. */ + static OntologySettled join(final Place place) { + final OntologyColumnJoin join = place.binding().getJoin(); + if (join == null || nullOrEmpty(join.getOn())) { + return refused(OntologyShapeCheckReason.NO_JOIN); + } + return when( + join.getStatus() == OntologyJoinStatus.CONFIRMED, + join, + OntologyShapeCheckReason.JOIN_NOT_CONFIRMED); + } + + static OntologySettled>> held( + final MappedTable table, final List> paths) { + return when( + paths.stream().allMatch(table::holds), paths, OntologyShapeCheckReason.COLUMN_MISSING); + } + + /** The way from the records to the table of a place, which is no way at all on its own table. */ + static OntologySettled route(final Records records, final Place place) { + final ReadTable identity = records.identity(); + if (place.onIdentity()) { + return of(new Route(identity, null, List.of())); + } + return joined(identity, place.holder()) + .then( + holder -> + keyPairs(identity.table(), holder.table()) + .map(pairs -> new Route(identity, holder, pairs))); + } + + /** Another table as a statement that starts from the identity table joins it. */ + static OntologySettled joined(final ReadTable identity, final MappedTable other) { + if (!identity.table().database().equals(other.database())) { + return refused(OntologyShapeCheckReason.OTHER_DATABASE); + } + return readTable(other); + } + + /** A contributing table pairs its subject key with the key of the identity table by position. */ + private static OntologySettled> keyPairs( + final MappedTable identity, final MappedTable holder) { + final List> key = identity.keyPaths(); + final List> paired = holder.keyPaths(); + return when( + key.size() == paired.size(), + IntStream.range(0, Math.min(key.size(), paired.size())) + .mapToObj(part -> new JoinPair(key.get(part), paired.get(part))) + .toList(), + OntologyShapeCheckReason.COLUMN_MISSING); + } + + /** The route on an engine that statements are written for. */ + static OntologySettled reach(final Route route) { + return SqlEngineFamily.forServiceType(route.identity().table().serviceType()) + .map(family -> of(new Reach(family, route.identity(), route.holder(), route.keyPairs()))) + .orElseGet(() -> refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED)); + } + + /** + * A statement that keeps the rows with no match on the other side of a join. ClickHouse fills + * the columns of a missing row with the default of their type unless a setting says otherwise, + * so a test for null finds no missing row there. + */ + static OntologySettled withOuterJoin(final Reach reach) { + return when( + reach.family() != SqlEngineFamily.CLICKHOUSE, + reach, + OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED); + } + + /** + * One test on the table of a place, with every binding row it was built from: the tables its + * statement reads to reach its values, then each of {@code others}. + */ + static OntologyPartOutcome check( + final Place place, + final List> columns, + final OntologyCheckProbe probe, + final MappedTable... others) { + final Reach reach = probe.reach(); + final List rows = new ArrayList<>(List.of(reach.identity().table().row())); + if (reach.joinsHolder()) { + rows.add(reach.holder().table().row()); + } + for (final MappedTable other : others) { + rows.add(other.row()); + } + return new Check(List.of(new TableCheck(place, columns, probe, List.copyOf(rows)))); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProbe.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProbe.java new file mode 100644 index 000000000000..b84e961dc9ab --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProbe.java @@ -0,0 +1,89 @@ +/* + * 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.ontology; + +import java.util.List; +import java.util.Optional; +import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.ontology.sql.TypedRowFilter; +import org.openmetadata.service.ontology.sql.TypedValue; + +/** + * Which records of a class a test counts. The compile makes one only from a mapping it + * has checked: every column a probe names is in its table, every filter and value is parsed, and + * every table is in one database on an engine that statements are written for. {@link + * OntologyShapeCheckSql} writes the statement and can refuse nothing. + */ +sealed interface OntologyCheckProbe { + Reach reach(); + + /** + * A table as a statement reads it. + * + * @param filter the row filter of its binding with its values parsed, or null when it has none + */ + record ReadTable(MappedTable table, TypedRowFilter filter) {} + + /** + * How a statement gets from the records of the class to the values of a property. + * + * @param holder the contributing table that holds the property, or null when the identity table + * holds it + * @param keyPairs each column of the subject key of the identity table with the column of the + * holder's subject key that it equals, or no pair when the identity table holds the property + */ + record Reach( + SqlEngineFamily family, ReadTable identity, ReadTable holder, List keyPairs) { + boolean joinsHolder() { + return holder != null; + } + } + + /** Records with fewer than {@code count} distinct values in {@code columns}. */ + record FewerValues(Reach reach, List> columns, int count) + implements OntologyCheckProbe {} + + /** Records with more than {@code count} distinct values in {@code columns}. */ + record MoreValues(Reach reach, List> columns, int count) + implements OntologyCheckProbe {} + + /** Records with a value in {@code column} that is none of {@code allowed}. */ + record OutsideList(Reach reach, List column, List allowed) + implements OntologyCheckProbe {} + + /** Records with a value in {@code column} below {@code min} or above {@code max}. */ + record OutsideRange( + Reach reach, List column, Optional min, Optional max) + implements OntologyCheckProbe {} + + /** + * Records with a value in {@code column} that {@code pattern} does not match. The compile makes + * one for the Postgres service type only, and the statement is written in its syntax. + * + * @param pattern the regular expression as Postgres reads it, a text value of the column + */ + record Unmatched(Reach reach, List column, TypedValue pattern) + implements OntologyCheckProbe {} + + /** + * Records with a value of a relation that is no record of the class the relation must reach. + * + * @param on each column of the join in the table that holds the relation, with the column of + * {@code target} that it equals + * @param target the identity table of the class the values must be records of + */ + record NoRecord(Reach reach, List on, ReadTable target) implements OntologyCheckProbe {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java new file mode 100644 index 000000000000..b88cbb59a517 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckProposals.java @@ -0,0 +1,201 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposal; +import org.openmetadata.schema.api.data.OntologyShapeCheckProposalState; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestCaseGeneratedBy; +import org.openmetadata.schema.tests.type.TestCaseResult; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.TaskEntityStatus; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.TaskRepository; +import org.openmetadata.service.jdbi3.TestCaseRepository; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.tasks.TestCaseSuggestion; +import org.openmetadata.service.util.EntityUtil.Fields; + +/** + * Sets how each check of a class stands as a test on its table: accepted when a test generated from + * it exists, proposed while a suggestion is open, rejected when the latest one was, else none. A + * reference is left out when the caller may not view the task or the test case, so the state alone + * never reveals what the caller cannot see (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + */ +final class OntologyCheckProposals { + private static final int ID_CHUNK = 500; + private static final Fields WITH_RESULT = new Fields(Set.of(Entity.TEST_CASE_RESULT)); + + private final CollectionDAO dao; + private final OntologyBindingAccess catalog; + + OntologyCheckProposals(final CollectionDAO dao, final OntologyBindingAccess catalog) { + this.dao = dao; + this.catalog = catalog; + } + + /** What exists for the checks of one class, keyed by check identity, and what the caller sees. */ + private record Held( + Map tests, + Map tasks, + Set viewableTests, + Set viewableTasks) {} + + void mark(final Access access, final UUID classId, final List shapes) { + final Held held = held(access, classId); + for (final OntologyCheckedShape shape : shapes) { + for (final OntologyCheckedConstraint constraint : listOrEmpty(shape.getConstraints())) { + for (final OntologyCheckedPart part : listOrEmpty(constraint.getParts())) { + for (final OntologyShapeCheck check : listOrEmpty(part.getChecks())) { + check.setProposal(proposal(held, check.getIdentity())); + } + } + } + } + } + + /** + * Reads the tests and the tasks of the class by id list, one call each, and the latest results + * with the tests, so the statements do not grow with the checks. + */ + private Held held(final Access access, final UUID classId) { + final TestCaseRepository tests = + (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); + final Map liveTests = new HashMap<>(); + final List testIds = + dao.testCaseDAO().findGeneratedIdsOfClass(classId.toString()).stream() + .map(UUID::fromString) + .toList(); + for (final List chunk : chunks(testIds)) { + for (final TestCase test : tests.get(null, chunk, WITH_RESULT, Include.ALL)) { + final TestCaseGeneratedBy by = test.getGeneratedBy(); + if (by != null + && classId.equals(by.getClass_().getId()) + && !Boolean.TRUE.equals(test.getDeleted())) { + liveTests.put(by.getIdentity(), test); + } + } + } + final Map byIdentity = new HashMap<>(); + final List taskIds = + dao.taskDAO().findTestCaseSuggestionIdsOfClass(classId.toString()).stream() + .map(UUID::fromString) + .toList(); + for (final List chunk : chunks(taskIds)) { + for (final Task task : tasks.get(null, chunk, Fields.EMPTY_FIELDS, Include.ALL)) { + final TestCaseGeneratedBy by = + TestCaseSuggestion.proposalOf(JsonUtils.valueToTree(task.getPayload())) + .getGeneratedBy(); + if (classId.equals(by.getClass_().getId())) { + byIdentity.merge(by.getIdentity(), task, OntologyCheckProposals::stronger); + } + } + } + return new Held( + liveTests, + byIdentity, + viewable(access, Entity.TEST_CASE, liveTests.values().stream().map(TestCase::getId)), + viewable(access, Entity.TASK, byIdentity.values().stream().map(Task::getId))); + } + + /** The ids among {@code ids} that the caller may view, one read for all of them. */ + private Set viewable( + final Access access, final String type, final java.util.stream.Stream ids) { + final Set viewable = new HashSet<>(); + for (final List chunk : chunks(ids.distinct().toList())) { + viewable.addAll(catalog.viewable(access, type, chunk).keySet()); + } + return viewable; + } + + private static List> chunks(final List all) { + final List> chunks = new ArrayList<>(); + for (int from = 0; from < all.size(); from += ID_CHUNK) { + chunks.add(all.subList(from, Math.min(all.size(), from + ID_CHUNK))); + } + return chunks; + } + + /** An open task outranks a closed one, and a later one an earlier one. */ + private static Task stronger(final Task left, final Task right) { + final boolean leftOpen = open(left); + final boolean rightOpen = open(right); + if (leftOpen != rightOpen) { + return leftOpen ? left : right; + } + return left.getUpdatedAt() >= right.getUpdatedAt() ? left : right; + } + + private static boolean open(final Task task) { + return task.getStatus() == TaskEntityStatus.Open + || task.getStatus() == TaskEntityStatus.InProgress + || task.getStatus() == TaskEntityStatus.Pending; + } + + private OntologyShapeCheckProposal proposal(final Held held, final String identity) { + final TestCase test = held.tests().get(identity); + if (test != null) { + return accepted(held, test); + } + final Task task = held.tasks().get(identity); + if (task != null && open(task)) { + return withTask(held, task, OntologyShapeCheckProposalState.PROPOSED); + } + if (task != null && task.getStatus() == TaskEntityStatus.Rejected) { + return withTask(held, task, OntologyShapeCheckProposalState.REJECTED); + } + return new OntologyShapeCheckProposal().withState(OntologyShapeCheckProposalState.NONE); + } + + private static OntologyShapeCheckProposal withTask( + final Held held, final Task task, final OntologyShapeCheckProposalState state) { + final OntologyShapeCheckProposal proposal = new OntologyShapeCheckProposal().withState(state); + if (held.viewableTasks().contains(task.getId())) { + proposal.setTask(task.getEntityReference()); + } + return proposal; + } + + private static OntologyShapeCheckProposal accepted(final Held held, final TestCase test) { + final OntologyShapeCheckProposal proposal = + new OntologyShapeCheckProposal().withState(OntologyShapeCheckProposalState.ACCEPTED); + if (!held.viewableTests().contains(test.getId())) { + return proposal; + } + proposal.setTestCase(test.getEntityReference()); + final TestCaseResult latest = test.getTestCaseResult(); + if (latest != null) { + proposal.setLatestResultStatus(latest.getTestCaseStatus()); + proposal.setLatestResultTimestamp(latest.getTimestamp()); + } + return proposal; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconcileQueue.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconcileQueue.java new file mode 100644 index 000000000000..d65299da7456 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconcileQueue.java @@ -0,0 +1,150 @@ +/* + * 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.ontology; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.service.Entity; +import org.openmetadata.service.ontology.OntologyCheckReconciler.Outcome; +import org.openmetadata.service.ontology.OntologyCheckReconciler.Scope; + +/** + * Runs the reconcile of shape checks after the commit that asked for it, one job at a time for each + * ontology (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). A request that + * arrives while a job of its ontology runs is merged with the others that wait and runs after that + * job, so a write that lands during a run is always read by a later one. The queue is in memory: + * a request lost with the server is made good by the next one for the ontology, because every run + * derives its writes from the state it reads. + */ +@Slf4j +public final class OntologyCheckReconcileQueue { + private static final int THREADS = 2; + private static volatile OntologyCheckReconcileQueue instance; + + private final OntologyCheckReconciler reconciler; + private final ExecutorService executor; + private final Map pending = new HashMap<>(); + private final Set running = new HashSet<>(); + private final Map totals = new HashMap<>(); + + private record Pending(Scope scope, String user) { + Pending merge(final Pending later) { + return new Pending(scope.merge(later.scope), later.user); + } + } + + OntologyCheckReconcileQueue(final OntologyCheckReconciler reconciler) { + this.reconciler = reconciler; + this.executor = + Executors.newFixedThreadPool( + THREADS, + task -> { + final Thread thread = new Thread(task, "ontology-check-reconcile"); + thread.setDaemon(true); + return thread; + }); + } + + /** The queue of this server. */ + public static OntologyCheckReconcileQueue instance() { + OntologyCheckReconcileQueue current = instance; + if (current == null) { + synchronized (OntologyCheckReconcileQueue.class) { + if (instance == null) { + instance = + new OntologyCheckReconcileQueue( + new OntologyCheckReconciler(Entity.getCollectionDAO(), Entity.getAuthorizer())); + } + current = instance; + } + } + return current; + } + + /** A release was activated, an older one included: every class of the ontology is looked at. */ + public void afterActivation(final UUID ontologyId, final String user) { + submit(ontologyId, new Pending(Scope.everything(), user)); + } + + /** A write moved the binding revision of a class. */ + public void afterBindingWrite(final UUID ontologyId, final UUID conceptId, final String user) { + submit(ontologyId, new Pending(Scope.of(Set.of(conceptId)), user)); + } + + private synchronized void submit(final UUID ontologyId, final Pending request) { + pending.merge(ontologyId, request, Pending::merge); + if (running.add(ontologyId)) { + executor.execute(() -> drain(ontologyId)); + } + } + + private void drain(final UUID ontologyId) { + while (true) { + final Pending next; + synchronized (this) { + next = pending.remove(ontologyId); + if (next == null) { + running.remove(ontologyId); + notifyAll(); + return; + } + } + run(ontologyId, next); + } + } + + private void run(final UUID ontologyId, final Pending request) { + try { + final Outcome outcome = reconciler.run(ontologyId, request.scope(), request.user()); + synchronized (this) { + totals.merge(ontologyId, outcome, Outcome::plus); + } + LOG.info("[OntologyChecks] Reconciled ontology {}: {}", ontologyId, outcome); + } catch (final RuntimeException failed) { + LOG.warn("[OntologyChecks] The reconcile of ontology {} failed", ontologyId, failed); + } + } + + /** The writes that the jobs of an ontology have made on this server so far, by kind. */ + public synchronized Outcome outcomeSoFar(final UUID ontologyId) { + return totals.getOrDefault(ontologyId, Outcome.NONE); + } + + /** How many writes the jobs of an ontology have made on this server so far. */ + public int writesMade(final UUID ontologyId) { + return outcomeSoFar(ontologyId).writes(); + } + + /** Waits until no job runs or waits, and says whether that happened within the time. */ + public boolean awaitIdle(final long timeout, final TimeUnit unit) throws InterruptedException { + final long deadline = System.nanoTime() + unit.toNanos(timeout); + synchronized (this) { + while (!running.isEmpty()) { + final long left = deadline - System.nanoTime(); + if (left <= 0) { + return false; + } + TimeUnit.NANOSECONDS.timedWait(this, left); + } + return true; + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java new file mode 100644 index 000000000000..7de975216093 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciler.java @@ -0,0 +1,704 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import jakarta.ws.rs.WebApplicationException; +import java.net.URI; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.tests.CreateTestCase; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.entity.teams.Team; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestCaseGeneratedBy; +import org.openmetadata.schema.tests.TestCaseGeneratedByBinding; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; +import org.openmetadata.schema.type.SuggestionPayload; +import org.openmetadata.schema.type.TaskCategory; +import org.openmetadata.schema.type.TaskEntityStatus; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.type.TestCaseProposal; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.governance.workflows.WorkflowEventConsumer; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.jdbi3.TaskRepository; +import org.openmetadata.service.jdbi3.TestCaseRepository; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Binding; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.CancelTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Checks; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Compiled; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.CreateTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.DeleteTest; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Held; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Proposed; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Refused; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.ReplaceTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.RestoreTest; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.TaskState; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.TestState; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.UpdateTest; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Wanted; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Write; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyShapeCheckAnswer.Generated; +import org.openmetadata.service.ontology.OntologyShapeCheckReader.Asked; +import org.openmetadata.service.ontology.OntologyShapeCheckReader.Read; +import org.openmetadata.service.ontology.OntologyVersion.Release; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.ChangeActor; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; +import org.openmetadata.service.tasks.TestCaseSuggestion; +import org.openmetadata.service.util.EntityUtil.Fields; +import org.openmetadata.service.util.FreshReadScope; + +/** + * Brings the tests of shape checks, and the suggestions that propose them, in line with the active + * release and the table bindings (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + * + *

It compiles the checks of each class in scope once, for no caller: the compile is the same for + * everyone, so it reads every shape, property and table and masks nothing. {@link + * OntologyCheckReconciliation} turns what it found, the test cases that carry {@code generatedBy} + * and the suggestion tasks of type {@code TestCase} into the writes, and this class makes them. A + * class whose compile refuses is left as it is. + */ +@Slf4j +public final class OntologyCheckReconciler { + private static final String REASONING = + "The records of the class break a constraint of a shape that targets it"; + private static final int ID_CHUNK = 500; + private static final Access NO_CALLER = new Access(null, null); + private static final String NAME_PREFIX = "shapeCheck_"; + private static final int NAME_IDENTITY_LENGTH = 16; + private static final int NAME_SUFFIX_LENGTH = 8; + private static final String DELETE_AS = WorkflowEventConsumer.GOVERNANCE_BOT; + + private final CollectionDAO dao; + private final OntologyConceptBindingStore store; + private final OntologyBindingAccess catalog; + private final OntologyShapeCheckReader reader; + private final Authorizer authorizer; + + public OntologyCheckReconciler(final CollectionDAO dao, final Authorizer authorizer) { + this.dao = dao; + this.store = + new OntologyConceptBindingStore(dao, OntologyConceptBindingStore.registeredAssetTables()); + this.catalog = OntologyBindingAccess.unrestricted(Entity::getEntityRepository); + this.reader = new OntologyShapeCheckReader(store, catalog); + this.authorizer = authorizer; + } + + /** + * What a run covers: every class of the ontology that a shape targets or that has a generated + * test or an open proposal, or the named classes with every class whose checks list a binding of + * one of them. + */ + record Scope(boolean all, Set classes) { + static Scope everything() { + return new Scope(true, Set.of()); + } + + static Scope of(final Set classes) { + return new Scope(false, Set.copyOf(classes)); + } + + Scope merge(final Scope other) { + if (all || other.all) { + return everything(); + } + final Set merged = new LinkedHashSet<>(classes); + merged.addAll(other.classes); + return of(merged); + } + } + + /** The writes a run made, by kind, and the failures it counted as refused. */ + public record Outcome( + int created, + int replaced, + int cancelled, + int updated, + int restored, + int deleted, + int refused) { + static final Outcome NONE = new Outcome(0, 0, 0, 0, 0, 0, 0); + + public int writes() { + return created + replaced + cancelled + updated + restored + deleted; + } + + Outcome plus(final Outcome other) { + return new Outcome( + created + other.created, + replaced + other.replaced, + cancelled + other.cancelled, + updated + other.updated, + restored + other.restored, + deleted + other.deleted, + refused + other.refused); + } + + /** What the writes that were made add up to, by kind. */ + static Outcome tally(final List made, final int refused) { + return made.stream() + .map(Outcome::one) + .reduce(new Outcome(0, 0, 0, 0, 0, 0, refused), Outcome::plus); + } + + private static Outcome one(final Write write) { + return switch (write) { + case CreateTask ignored -> new Outcome(1, 0, 0, 0, 0, 0, 0); + case ReplaceTask ignored -> new Outcome(0, 1, 0, 0, 0, 0, 0); + case CancelTask ignored -> new Outcome(0, 0, 1, 0, 0, 0, 0); + case UpdateTest ignored -> new Outcome(0, 0, 0, 1, 0, 0, 0); + case RestoreTest ignored -> new Outcome(0, 0, 0, 0, 1, 0, 0); + case DeleteTest ignored -> new Outcome(0, 0, 0, 0, 0, 1, 0); + }; + } + } + + /** What one class compiled to, with what a task or a test needs to be written from it. */ + record Planned( + Wanted wanted, + Generated generated, + EntityReference classReference, + EntityReference shapeReference, + URI classIri) {} + + record Found(Compiled decision, Map byIdentity) {} + + Outcome run(final UUID ontologyId, final Scope scope, final String user) { + try (FreshReadScope.Handle ignored = FreshReadScope.enter()) { + final Optional active = activeRelease(ontologyId); + if (active.isEmpty()) { + return Outcome.NONE; + } + final Map tests = generatedTests(); + final Map tasks = suggestions(); + final Set classes = classesOf(ontologyId, active.get(), scope, tests, tasks); + final Map found = new LinkedHashMap<>(); + classes.forEach(id -> found.put(id, compile(ontologyId, active.get(), id))); + final Map decisions = new LinkedHashMap<>(); + found.forEach((id, one) -> decisions.put(id, one.decision())); + final List writes = + OntologyCheckReconciliation.decide( + decisions, List.copyOf(tests.values()), List.copyOf(tasks.values())); + return execute(ontologyId, user, writes, found, tests, tasks); + } + } + + private Optional activeRelease(final UUID ontologyId) { + final var state = dao.ontologyStateDAO().get(ontologyId); + if (state == null || state.getActiveReleaseId() == null) { + return Optional.empty(); + } + final var ontology = dao.ontologyEntityDAO().findEntityById(ontologyId); + if (Boolean.TRUE.equals(ontology.getDeleted())) { + return Optional.empty(); + } + return Optional.of((Release) OntologyVersion.release(dao, ontology.getEntityReference())); + } + + // ---- what exists ------------------------------------------------------------------------- + + private Map generatedTests() { + final TestCaseRepository repository = + (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + final List ids = + dao.testCaseDAO().findGeneratedIds().stream().map(UUID::fromString).toList(); + final Map held = new LinkedHashMap<>(); + for (final List chunk : chunks(ids)) { + for (final TestCase test : repository.get(null, chunk, Fields.EMPTY_FIELDS, Include.ALL)) { + final TestCaseGeneratedBy by = test.getGeneratedBy(); + held.put( + test.getId(), + new Held( + test.getId(), + by.getClass_().getId(), + test.getName(), + by.getIdentity(), + by.getContentDigest(), + bindings(by.getReadBindings()), + testState(test))); + } + } + return held; + } + + /** The reconcile deletes as the governance bot, so a delete by anyone else is a person's. */ + private static TestState testState(final TestCase test) { + if (!Boolean.TRUE.equals(test.getDeleted())) { + return TestState.LIVE; + } + return DELETE_AS.equals(test.getUpdatedBy()) + ? TestState.DELETED_BY_RECONCILE + : TestState.DELETED_BY_PERSON; + } + + private Map suggestions() { + final TaskRepository repository = (TaskRepository) Entity.getEntityRepository(Entity.TASK); + final List ids = + dao.taskDAO().findTestCaseSuggestionIds().stream().map(UUID::fromString).toList(); + final Map proposed = new LinkedHashMap<>(); + for (final List chunk : chunks(ids)) { + for (final Task task : repository.get(null, chunk, Fields.EMPTY_FIELDS, Include.ALL)) { + proposalOf(task) + .ifPresent( + proposal -> { + final TestCaseGeneratedBy by = proposal.getGeneratedBy(); + proposed.put( + task.getId(), + new Proposed( + task.getId(), + by.getClass_().getId(), + by.getIdentity(), + by.getContentDigest(), + bindings(by.getReadBindings()), + stateOf(task), + proposal.getTestCase().getName())); + }); + } + } + return proposed; + } + + private static Optional proposalOf(final Task task) { + try { + return Optional.of(TestCaseSuggestion.proposalOf(JsonUtils.valueToTree(task.getPayload()))); + } catch (RuntimeException unreadable) { + LOG.warn("[OntologyChecks] Task {} holds no readable test case proposal", task.getId()); + return Optional.empty(); + } + } + + private static TaskState stateOf(final Task task) { + return switch (task.getStatus()) { + case Open, InProgress, Pending -> TaskState.OPEN; + case Rejected -> TaskState.REJECTED; + case Approved, Completed -> TaskState.APPROVED; + default -> TaskState.OTHER; + }; + } + + private static List bindings(final List read) { + return listOrEmpty(read).stream() + .map(b -> new Binding(b.getConceptId(), b.getAssetId(), b.getRevision())) + .toList(); + } + + private static List> chunks(final List all) { + final List> chunks = new ArrayList<>(); + for (int from = 0; from < all.size(); from += ID_CHUNK) { + chunks.add(all.subList(from, Math.min(all.size(), from + ID_CHUNK))); + } + return chunks; + } + + // ---- which classes ----------------------------------------------------------------------- + + private Set classesOf( + final UUID ontologyId, + final Release active, + final Scope scope, + final Map tests, + final Map tasks) { + final Set classes = new LinkedHashSet<>(); + if (scope.all()) { + classes.addAll(shapeTargets(ontologyId, active)); + tests.values().forEach(test -> classes.add(test.classId())); + tasks.values().forEach(task -> classes.add(task.classId())); + return inOntology(ontologyId, classes); + } + classes.addAll(scope.classes()); + tests.values().stream() + .filter(test -> mentions(test.readBindings(), scope.classes())) + .forEach(test -> classes.add(test.classId())); + tasks.values().stream() + .filter(task -> mentions(task.readBindings(), scope.classes())) + .forEach(task -> classes.add(task.classId())); + return inOntology(ontologyId, classes); + } + + private static boolean mentions(final List bindings, final Set classes) { + return bindings.stream().anyMatch(binding -> classes.contains(binding.conceptId())); + } + + /** The classes of the ontology that a shape of the active release targets. */ + private Set shapeTargets(final UUID ontologyId, final Release active) { + final Set targets = new LinkedHashSet<>(); + String after = ""; + List page; + do { + page = + dao.ontologyReleaseDAO() + .listMembers( + active.release().getId(), + MemberKind.SHAPE.value(), + after, + OntologyVersion.SHAPE_MEMBERS_READ); + for (final var member : page) { + final OntologyShape shape = + (OntologyShape) OntologyReleaseReader.definition(active.release(), member); + if (shape.getTargetConcept() != null) { + targets.add(shape.getTargetConcept()); + } + after = member.getMemberId().toString(); + } + } while (page.size() == OntologyVersion.SHAPE_MEMBERS_READ); + return targets.isEmpty() + ? Set.of() + : active.classesNamed(store, ontologyId, targets).stream() + .map(OntologyConcept::getId) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + /** A class of another ontology is not this run's to reconcile. A class that is gone stays in. */ + private Set inOntology(final UUID ontologyId, final Set classes) { + final Set kept = new LinkedHashSet<>(classes); + final List ids = List.copyOf(classes); + for (final List chunk : chunks(ids)) { + for (final OntologyConcept row : + dao.ontologyConceptDAO().findEntitiesByIds(chunk, Include.ALL)) { + if (!ontologyId.equals(row.getOntology().getId())) { + kept.remove(row.getId()); + } + } + } + return kept; + } + + // ---- the compile ------------------------------------------------------------------------- + + private Found compile(final UUID ontologyId, final Release active, final UUID classId) { + return attempt(classId, () -> compiled(ontologyId, active, classId)); + } + + /** Runs one compile, and turns a refusal or a failure into an answer that changes nothing. */ + static Found attempt(final UUID classId, final Supplier compile) { + try { + return compile.get(); + } catch (final WebApplicationException refusal) { + LOG.warn( + "[OntologyChecks] The compile of class {} was refused, so nothing changes for it: {}", + classId, + refusal.getMessage()); + return new Found(new Refused(String.valueOf(refusal.getMessage())), Map.of()); + } catch (final RuntimeException failed) { + LOG.warn( + "[OntologyChecks] The compile of class {} failed, so nothing changes for it", + classId, + failed); + return new Found(new Refused(String.valueOf(failed.getMessage())), Map.of()); + } + } + + private Found compiled(final UUID ontologyId, final Release active, final UUID classId) { + final Optional declared = declared(active, classId); + if (declared.isEmpty()) { + return new Found(new Checks(List.of()), Map.of()); + } + final OntologyConcept type = declared.get(); + final Read read = + reader.read(NO_CALLER, new Asked(type.getId(), type.getIri(), ontologyId, active)); + final List generated = + OntologyShapeCheckAnswer.generated(read.facts(), read.shapes()); + final EntityReference classReference = type.getEntityReference(); + final Map byIdentity = new LinkedHashMap<>(); + final List wanted = new ArrayList<>(); + for (final Generated one : generated) { + final OntologyShapeCheck check = one.check(); + final Wanted want = + new Wanted( + check.getIdentity(), + TestCaseSuggestion.digest( + check.getTestDefinition(), check.getEntityLink(), check.getParameterValues()), + check.getReadBindings().stream() + .map(b -> new Binding(b.getConceptId(), b.getAssetId(), b.getRevision())) + .toList()); + if (byIdentity.putIfAbsent(want.identity(), plan(want, one, classReference, type)) == null) { + wanted.add(want); + } + } + return new Found(new Checks(wanted), byIdentity); + } + + private static Planned plan( + final Wanted wanted, + final Generated one, + final EntityReference classReference, + final OntologyConcept type) { + return new Planned( + wanted, one, classReference, one.shape().getEntityReference(), type.getIri()); + } + + /** The class as the active release declares it, empty when the release lacks it. */ + private Optional declared(final Release active, final UUID classId) { + try { + catalog.working(NO_CALLER, Entity.ONTOLOGY_CONCEPT, classId); + } catch (final org.openmetadata.service.exception.EntityNotFoundException gone) { + return Optional.empty(); + } + return active.member(MemberKind.CONCEPT, classId).map(OntologyConcept.class::cast); + } + + // ---- the writes -------------------------------------------------------------------------- + + private Outcome execute( + final UUID ontologyId, + final String user, + final List writes, + final Map found, + final Map tests, + final Map tasks) { + final List made = new ArrayList<>(); + int failed = 0; + for (final Write write : writes) { + try { + switch (write) { + case CreateTask create -> createTask( + ontologyId, planned(found, create.classId(), create.identity())); + case ReplaceTask replace -> replaceTask( + user, replace.taskId(), planned(found, replace.classId(), replace.identity())); + case CancelTask cancel -> cancelTask(user, cancel); + case UpdateTest update -> updateTest( + user, update.testId(), planned(found, update.classId(), update.identity())); + case DeleteTest delete -> deleteTest(delete.testId()); + case RestoreTest restore -> restoreTest(restore.testId()); + } + made.add(write); + } catch (final RuntimeException failure) { + failed++; + LOG.warn("[OntologyChecks] A write of the reconcile failed: {}", write, failure); + } + } + final long refusedCompiles = + found.values().stream().filter(one -> one.decision() instanceof Refused).count(); + return Outcome.tally(made, failed + (int) refusedCompiles); + } + + private static Planned planned( + final Map found, final UUID classId, final String identity) { + return found.get(classId).byIdentity().get(identity); + } + + private TestCaseProposal proposal(final Planned planned, final String name) { + final OntologyShapeCheck check = planned.generated().check(); + final CreateTestCase create = + new CreateTestCase() + .withName(name) + .withDescription(describe(planned)) + .withTestDefinition(check.getTestDefinition()) + .withEntityLink(check.getEntityLink()) + .withParameterValues(check.getParameterValues()); + final TestCaseGeneratedBy by = + new TestCaseGeneratedBy() + .withIdentity(check.getIdentity()) + .withShape(planned.shapeReference()) + .withConstraintId(planned.generated().constraintId()) + .withPart(planned.generated().part().value()) + .withClass(planned.classReference()) + .withReadBindings( + check.getReadBindings().stream().map(OntologyCheckReconciler::generatedBy).toList()) + .withContentDigest(planned.wanted().digest()); + return new TestCaseProposal() + .withTestCase(create) + .withInspectionQuery(check.getInspectionQuery()) + .withGeneratedBy(by); + } + + private static TestCaseGeneratedByBinding generatedBy(final OntologyShapeCheckBinding binding) { + return new TestCaseGeneratedByBinding() + .withConceptId(binding.getConceptId()) + .withAssetId(binding.getAssetId()) + .withRevision(binding.getRevision()); + } + + private static String describe(final Planned planned) { + return "Counts the records of class %s that break the %s of constraint %s of shape %s. A record can span several rows of the table, so the count is of records, not rows." + .formatted( + planned.classIri(), + planned.generated().part().value(), + planned.generated().constraintId(), + planned.generated().shape().getName()); + } + + private static String newName(final String identity) { + return NAME_PREFIX + + identity.substring(0, NAME_IDENTITY_LENGTH) + + "_" + + UUID.randomUUID().toString().replace("-", "").substring(0, NAME_SUFFIX_LENGTH); + } + + private void createTask(final UUID ontologyId, final Planned planned) { + final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); + final OntologyShapeCheck check = planned.generated().check(); + final TestCaseProposal proposal = proposal(planned, newName(check.getIdentity())); + final Table table = Entity.getEntity(check.getTable(), "owners", Include.NON_DELETED); + final long now = System.currentTimeMillis(); + final Task task = + new Task() + .withId(UUID.randomUUID()) + .withName(proposal.getTestCase().getName()) + .withDescription(proposal.getTestCase().getDescription()) + .withCategory(TaskCategory.MetadataUpdate) + .withType(TaskEntityType.Suggestion) + .withStatus(TaskEntityStatus.Open) + .withAbout(table.getEntityReference()) + .withPayload(suggestion(proposal)) + .withAssignees(assignees(ontologyId, table)) + .withUseEntityOwnerFallback(false) + .withCreatedBy( + Entity.getEntityReferenceByName(Entity.USER, DELETE_AS, Include.NON_DELETED)) + .withCreatedAt(now) + .withUpdatedBy(DELETE_AS) + .withUpdatedAt(now); + tasks.create(null, task); + } + + private static SuggestionPayload suggestion(final TestCaseProposal proposal) { + return new SuggestionPayload() + .withSuggestionType(SuggestionPayload.SuggestionType.TEST_CASE) + .withFieldPath(TestCaseSuggestion.FIELD_PATH) + .withSuggestedValue(JsonUtils.pojoToJson(proposal)) + .withSource(SuggestionPayload.Source.INGESTION) + .withReasoning(REASONING); + } + + private void replaceTask(final String user, final UUID taskId, final Planned planned) { + final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); + final Task task = tasks.get(null, taskId, tasks.getFields("*")); + final String name = + TestCaseSuggestion.proposalOf(JsonUtils.valueToTree(task.getPayload())) + .getTestCase() + .getName(); + task.setPayload(suggestion(proposal(planned, name))); + task.setDescription(describe(planned)); + task.setUpdatedAt(System.currentTimeMillis()); + tasks.createOrUpdate(null, task, user); + } + + private void cancelTask(final String user, final CancelTask cancel) { + final TaskRepository tasks = (TaskRepository) Entity.getEntityRepository(Entity.TASK); + tasks.closeTaskAndCancelWorkflowRun( + tasks.get(null, cancel.taskId(), tasks.getFields("*")), user, cancel.reason()); + } + + private void updateTest(final String user, final UUID testId, final Planned planned) { + final TestCaseRepository tests = + (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + final OntologyShapeCheck check = planned.generated().check(); + final TestCaseProposal proposal = proposal(planned, "unused"); + tests.updateGenerated( + testId, + check.getEntityLink(), + check.getParameterValues(), + proposal.getInspectionQuery(), + proposal.getGeneratedBy(), + user); + } + + /** + * Deletes as the governance bot, which is how a later run tells this delete from a person's. It + * is recursive because a test with a failed result has an incident under it, which a plain delete + * refuses. + */ + private void deleteTest(final UUID testId) { + final TestCaseRepository tests = + (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + tests.delete(DELETE_AS, testId, true, false); + } + + private void restoreTest(final UUID testId) { + final TestCaseRepository tests = + (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + tests.restoreEntity(DELETE_AS, testId); + } + + // ---- who is asked ------------------------------------------------------------------------ + + /** + * The owners of the table who may create tests on it, else the owners of the ontology who may. A + * team stands for its users, and a user who lacks the right is left out. + */ + private List assignees(final UUID ontologyId, final Table table) { + final List fromTable = mayCreate(listOrEmpty(table.getOwners()), table); + if (!fromTable.isEmpty()) { + return fromTable; + } + final Ontology ontology = + Entity.getEntity(Entity.ONTOLOGY, ontologyId, "owners", Include.NON_DELETED); + return mayCreate(listOrEmpty(ontology.getOwners()), table); + } + + private List mayCreate(final List owners, final Table table) { + final Map users = new LinkedHashMap<>(); + for (final EntityReference owner : owners) { + for (final EntityReference user : usersOf(owner)) { + if (mayCreateTests(user, table)) { + users.putIfAbsent(user.getId(), user); + } + } + } + return List.copyOf(users.values()); + } + + private static List usersOf(final EntityReference owner) { + if (Entity.USER.equals(owner.getType())) { + return List.of(owner); + } + final Team team = Entity.getEntity(owner, "users", Include.NON_DELETED); + return listOrEmpty(team.getUsers()); + } + + private boolean mayCreateTests(final EntityReference user, final Table table) { + final String name = user.getName(); + if (nullOrEmpty(name)) { + return false; + } + final ChangeActor actor = ChangeActor.user(name, null); + final ResourceContext resource = new ResourceContext<>(Entity.TABLE, table.getId(), null); + try { + authorizer.authorizeActor( + actor, new OperationContext(Entity.TABLE, MetadataOperation.CREATE_TESTS), resource); + return true; + } catch (final AuthorizationException denied) { + LOG.debug("[OntologyChecks] {} may not create tests on {}", name, table.getId()); + return false; + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciliation.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciliation.java new file mode 100644 index 000000000000..2ba199abe2ae --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCheckReconciliation.java @@ -0,0 +1,280 @@ +/* + * 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.ontology; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +/** + * The decision of the reconcile that keeps the tests of shape checks in step with the active + * release and the table bindings (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + * It is a function from what the compile says, what test cases exist and what suggestion tasks + * exist to the list of writes that bring them in line. It reads and writes nothing, so a second + * run over the state that the first one wrote is an empty list. + */ +final class OntologyCheckReconciliation { + /** What closes an open task whose check no longer appears. */ + static final String NO_LONGER_CHECKED = "The shape no longer asks for this check"; + + /** What closes an open task whose check already has a test. */ + static final String ALREADY_TESTED = "A test of this check exists"; + + /** What closes a second open task of one check. */ + static final String ANOTHER_OPEN = "Another open suggestion proposes this check"; + + private OntologyCheckReconciliation() {} + + /** One table binding a check was built from. */ + record Binding(UUID conceptId, UUID assetId, long revision) {} + + /** One check the compile of a class produced. */ + record Wanted(String identity, String digest, List readBindings) {} + + /** What the compile of one class answered. */ + sealed interface Compiled permits Checks, Refused {} + + /** The compile answered with these checks, none included. */ + record Checks(List checks) implements Compiled {} + + /** The compile refused, so nothing can be said about the class. */ + record Refused(String reason) implements Compiled {} + + /** Whether a test case is live, and who deleted it when it is not. */ + enum TestState { + LIVE, + DELETED_BY_PERSON, + DELETED_BY_RECONCILE + } + + /** A test case that was generated from a check. */ + record Held( + UUID id, + UUID classId, + String name, + String identity, + String digest, + List readBindings, + TestState state) { + boolean live() { + return state == TestState.LIVE; + } + } + + /** Where a suggestion task of a check stands. */ + enum TaskState { + OPEN, + REJECTED, + APPROVED, + OTHER + } + + /** + * A suggestion task that proposes a check. {@code testName} is the name of the test the proposal + * creates, which is how an approved task finds the test it made. + */ + record Proposed( + UUID id, + UUID classId, + String identity, + String digest, + List readBindings, + TaskState state, + String testName) {} + + /** One write the reconcile makes. */ + sealed interface Write + permits UpdateTest, DeleteTest, RestoreTest, ReplaceTask, CancelTask, CreateTask {} + + record UpdateTest(UUID testId, UUID classId, String identity) implements Write {} + + record DeleteTest(UUID testId) implements Write {} + + record RestoreTest(UUID testId) implements Write {} + + record ReplaceTask(UUID taskId, UUID classId, String identity) implements Write {} + + record CancelTask(UUID taskId, String reason) implements Write {} + + record CreateTask(UUID classId, String identity) implements Write {} + + /** + * The writes that bring the tests and the tasks of each class in line with its checks. A class + * whose compile was refused is left as it is, and so are the tests and tasks of a class that is + * not named. + */ + static List decide( + final Map classes, final List tests, final List tasks) { + final List writes = new ArrayList<>(); + classes.forEach( + (classId, compiled) -> { + if (compiled instanceof Checks checks) { + writes.addAll( + decide(classId, checks.checks(), of(tests, classId), ofTasks(tasks, classId))); + } + }); + return List.copyOf(writes); + } + + private static List of(final List tests, final UUID classId) { + return tests.stream().filter(test -> classId.equals(test.classId())).toList(); + } + + private static List ofTasks(final List tasks, final UUID classId) { + return tasks.stream().filter(task -> classId.equals(task.classId())).toList(); + } + + private static List decide( + final UUID classId, + final List checks, + final List tests, + final List tasks) { + final List writes = new ArrayList<>(); + final Set wanted = new HashSet<>(); + final Set claimed = new HashSet<>(); + for (final Wanted check : checks) { + if (wanted.add(check.identity())) { + writes.addAll(forCheck(classId, check, tests, tasks, claimed)); + } + } + tests.stream() + .filter(test -> test.live() && !wanted.contains(test.identity())) + .forEach(test -> writes.add(new DeleteTest(test.id()))); + tasks.stream() + .filter(task -> task.state() == TaskState.OPEN && !claimed.contains(task.id())) + .forEach(task -> writes.add(new CancelTask(task.id(), reasonFor(task, wanted, tests)))); + return writes; + } + + private static String reasonFor( + final Proposed task, final Set wanted, final List tests) { + if (!wanted.contains(task.identity())) { + return NO_LONGER_CHECKED; + } + final boolean tested = + tests.stream().anyMatch(test -> test.live() && test.identity().equals(task.identity())); + return tested ? ALREADY_TESTED : ANOTHER_OPEN; + } + + private static List forCheck( + final UUID classId, + final Wanted check, + final List tests, + final List tasks, + final Set claimed) { + final List mine = byId(tests.stream().filter(t -> t.identity().equals(check.identity()))); + final List live = mine.stream().filter(Held::live).toList(); + if (!live.isEmpty()) { + return keepOne(classId, check, live); + } + final List open = + tasks.stream() + .filter(task -> task.identity().equals(check.identity())) + .filter(task -> task.state() == TaskState.OPEN) + .toList(); + if (!open.isEmpty()) { + claimed.add(open.getFirst().id()); + return changed(check, open.getFirst().digest(), open.getFirst().readBindings()) + ? List.of(new ReplaceTask(open.getFirst().id(), classId, check.identity())) + : List.of(); + } + final Set personAnswered = answeredByPerson(check, mine, tasks, tests); + if (personAnswered.contains(check.digest()) || rejectedWith(check, tasks)) { + return List.of(); + } + final List reconcileDeleted = + mine.stream().filter(test -> test.state() == TestState.DELETED_BY_RECONCILE).toList(); + if (personAnswered.isEmpty() && !reconcileDeleted.isEmpty()) { + return restore(classId, check, reconcileDeleted.getFirst()); + } + return List.of(new CreateTask(classId, check.identity())); + } + + /** Keeps the live test with the lowest id, updates it when it is stale, and deletes the rest. */ + private static List keepOne( + final UUID classId, final Wanted check, final List live) { + final Held kept = live.getFirst(); + final List writes = new ArrayList<>(); + if (changed(check, kept.digest(), kept.readBindings())) { + writes.add(new UpdateTest(kept.id(), classId, check.identity())); + } + live.stream().skip(1).forEach(extra -> writes.add(new DeleteTest(extra.id()))); + return writes; + } + + private static List restore(final UUID classId, final Wanted check, final Held deleted) { + final List writes = new ArrayList<>(); + writes.add(new RestoreTest(deleted.id())); + if (changed(check, deleted.digest(), deleted.readBindings())) { + writes.add(new UpdateTest(deleted.id(), classId, check.identity())); + } + return writes; + } + + /** The tests of one identity, lowest id first, so two servers choose the same one. */ + private static List byId(final java.util.stream.Stream tests) { + return tests.sorted(Comparator.comparing(test -> test.id().toString())).toList(); + } + + /** + * The digests of what a person deleted for this check: a test they soft deleted, and an approved + * task whose test has no row left, which a hard delete leaves behind. + */ + private static Set answeredByPerson( + final Wanted check, + final List mine, + final List tasks, + final List allTests) { + final Set names = new HashSet<>(); + allTests.forEach(test -> names.add(test.name())); + final Set digests = new HashSet<>(); + mine.stream() + .filter(test -> test.state() == TestState.DELETED_BY_PERSON) + .forEach(test -> digests.add(test.digest())); + tasks.stream() + .filter(task -> task.identity().equals(check.identity())) + .filter(task -> task.state() == TaskState.APPROVED && !names.contains(task.testName())) + .forEach(task -> digests.add(task.digest())); + return digests; + } + + /** A person rejected this content. */ + private static boolean rejectedWith(final Wanted check, final List tasks) { + return tasks.stream() + .anyMatch( + task -> + task.identity().equals(check.identity()) + && task.state() == TaskState.REJECTED + && task.digest().equals(check.digest())); + } + + private static boolean changed( + final Wanted check, final String digest, final List bindings) { + return !check.digest().equals(digest) || !sameBindings(check.readBindings(), bindings); + } + + private static boolean sameBindings(final List left, final List right) { + return new HashSet<>(left).equals(new HashSet<>(right)); + } + + /** Keeps the order the classes were named in. */ + static Map ordered() { + return new LinkedHashMap<>(); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyClassHierarchy.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyClassHierarchy.java index 68fdcd1d93a9..f198fa755a5c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyClassHierarchy.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyClassHierarchy.java @@ -5,6 +5,8 @@ import java.net.URI; import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Collection; +import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -281,7 +283,23 @@ public static List namedParents(final OntologyAxiom axiom) { .toList(); } - private static Map> namedEdges( + /** Every IRI that a walk up the named parents reaches from {@code starts}, the starts included. */ + public static Set reachable( + final Map> parents, final Collection starts) { + final Set visited = new HashSet<>(starts); + final Deque pending = new ArrayDeque<>(starts); + while (!pending.isEmpty()) { + for (final String parent : parents.getOrDefault(pending.pop(), Set.of())) { + if (visited.add(parent)) { + pending.push(parent); + } + } + } + return visited; + } + + /** The named parents that the subclass axioms give each class, by the IRI of the class. */ + public static Map> namedEdges( final List definitions) { final Map> edges = new HashMap<>(); definitions.stream() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyColumnTypeFit.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyColumnTypeFit.java new file mode 100644 index 000000000000..ef4439bb0625 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyColumnTypeFit.java @@ -0,0 +1,133 @@ +/* + * 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.ontology; + +import java.net.URI; +import java.util.EnumSet; +import java.util.Set; +import org.openmetadata.schema.type.ColumnDataType; + +/** + * Whether a column's type can hold the values of an XSD datatype. A datatype that is not listed + * here fits every column, and a column type that is neither numeric, text, a date or time, + * {@code BOOLEAN} nor {@code BIT} is never reported, since it may hold any value as text. + */ +final class OntologyColumnTypeFit { + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + + private static final Set NUMERIC_DATATYPES = + Set.of( + "integer", + "int", + "long", + "short", + "byte", + "nonNegativeInteger", + "positiveInteger", + "negativeInteger", + "nonPositiveInteger", + "unsignedLong", + "unsignedInt", + "unsignedShort", + "unsignedByte", + "decimal", + "float", + "double"); + + private static final Set DATE_DATATYPES = Set.of("date", "dateTime", "dateTimeStamp"); + private static final String TIME_DATATYPE = "time"; + private static final String BOOLEAN_DATATYPE = "boolean"; + + private static final Set NUMERIC = + EnumSet.of( + ColumnDataType.NUMBER, + ColumnDataType.TINYINT, + ColumnDataType.SMALLINT, + ColumnDataType.INT, + ColumnDataType.BIGINT, + ColumnDataType.BYTEINT, + ColumnDataType.LONG, + ColumnDataType.LARGEINT, + ColumnDataType.UINT, + ColumnDataType.FLOAT, + ColumnDataType.DOUBLE, + ColumnDataType.DECIMAL, + ColumnDataType.NUMERIC, + ColumnDataType.MONEY); + + private static final Set TEXT = + EnumSet.of( + ColumnDataType.STRING, + ColumnDataType.CHAR, + ColumnDataType.VARCHAR, + ColumnDataType.TEXT, + ColumnDataType.MEDIUMTEXT, + ColumnDataType.NTEXT, + ColumnDataType.CLOB); + + private static final Set DATES = + EnumSet.of( + ColumnDataType.DATE, + ColumnDataType.TIMESTAMP, + ColumnDataType.TIMESTAMPZ, + ColumnDataType.DATETIME); + + private static final Set FLAGS = + EnumSet.of(ColumnDataType.BOOLEAN, ColumnDataType.BIT); + + private OntologyColumnTypeFit() {} + + /** Whether a column of {@code type} is one a value of {@code datatype} does not fit. */ + static boolean mismatched(final URI datatype, final ColumnDataType type) { + final Set accepted = accepted(datatype); + return accepted != null && judged(type) && !accepted.contains(type); + } + + /** The column types that hold the datatype, or null when the datatype fits every column. */ + private static Set accepted(final URI datatype) { + final String iri = datatype.toString(); + if (OwlDatatypeSupport.isDate(iri)) { + return DATES; + } + if (!iri.startsWith(XSD)) { + return null; + } + final String local = iri.substring(XSD.length()); + if (NUMERIC_DATATYPES.contains(local)) { + return NUMERIC; + } + if (DATE_DATATYPES.contains(local)) { + return DATES; + } + if (TIME_DATATYPE.equals(local)) { + return union(DATES, EnumSet.of(ColumnDataType.TIME)); + } + return BOOLEAN_DATATYPE.equals(local) ? union(FLAGS, NUMERIC) : null; + } + + private static boolean judged(final ColumnDataType type) { + return NUMERIC.contains(type) + || TEXT.contains(type) + || DATES.contains(type) + || type == ColumnDataType.TIME + || FLAGS.contains(type); + } + + private static Set union( + final Set left, final Set right) { + final Set union = EnumSet.copyOf(left); + union.addAll(right); + return union; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java index 2f3a424e0837..df3077ad8101 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptBindingService.java @@ -7,7 +7,6 @@ import jakarta.ws.rs.core.UriInfo; import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; @@ -23,7 +22,6 @@ import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.EntityReference; -import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.OntologyAssetBinding; import org.openmetadata.schema.type.OntologyAssetConceptLink; @@ -41,16 +39,15 @@ import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore.Mutation; +import org.openmetadata.service.ontology.OntologyTableBindingChecks.Write; import org.openmetadata.service.rdf.RdfUpdater; import org.openmetadata.service.search.OntologyTermSearch; import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; -import org.openmetadata.service.security.policyevaluator.BulkFieldHydrator; -import org.openmetadata.service.security.policyevaluator.OperationContext; -import org.openmetadata.service.security.policyevaluator.ResourceContext; -import org.openmetadata.service.util.EntityUtil.Fields; import org.openmetadata.service.util.FreshReadScope; import org.openmetadata.service.util.FullyQualifiedName; +import org.openmetadata.service.util.PostCommitActionQueue; import org.openmetadata.service.util.RestUtil; @Slf4j @@ -61,12 +58,26 @@ public final class OntologyConceptBindingService { private static final int MAX_CURSOR_LENGTH = 256; private final OntologyConceptBindingStore store; - private final Authorizer authorizer; - private final Function> repositories; + private final OntologyBindingAccess targets; + private final OntologyTableBindingChecks tableChecks; private final Consumer bindingsChanged; public record Access(UriInfo uriInfo, SecurityContext securityContext) {} + /** + * How a changed write proves that it saw the bindings it replaces. It is asked under the ontology + * lock, after the writer's rights on the concept and the asset are checked and before the checks + * of a table binding, with the concept's current revision and the stored binding of the asset, if + * any. It returns the revision the write commits or refuses the write. + */ + @FunctionalInterface + public interface RevisionGuard { + long next(long current, BindingRow existing); + } + + /** One binding to write and the guard that admits it. */ + private record Replacement(OntologyAssetBinding asset, RevisionGuard guard) {} + public OntologyConceptBindingService( final OntologyConceptBindingStore store, final Authorizer authorizer, @@ -84,8 +95,8 @@ public OntologyConceptBindingService( final Function> repositories, final Consumer bindingsChanged) { this.store = store; - this.authorizer = authorizer; - this.repositories = repositories; + this.targets = new OntologyBindingAccess(authorizer, repositories); + this.tableChecks = new OntologyTableBindingChecks(targets); this.bindingsChanged = bindingsChanged; } @@ -108,7 +119,8 @@ public OntologyAssetConceptLinks linksForAsset( final Access access, final String assetType, final UUID assetId) { final var type = assetType(assetType); try (final var ignored = FreshReadScope.enter()) { - final var asset = authorized(access, type.value(), assetId, MetadataOperation.VIEW_BASIC); + final var asset = + targets.authorized(access, type.value(), assetId, MetadataOperation.VIEW_BASIC); final Map> properties = new HashMap<>(); final List links = new ArrayList<>(); // Rows are paged by concept id and filtered afterwards, so concepts the reader cannot see @@ -163,14 +175,37 @@ public OntologyConceptBindingsResponse put( throw new BadRequestException("A binding update is required"); } OntologyBindingRules.requireRevision(request.getExpectedRevision()); - OntologyBindingRules.validate(request.getAsset()); + final RevisionGuard sawExpectedRevision = + (current, existing) -> + OntologyBindingRules.nextRevision(current, request.getExpectedRevision()); + return firstPage( + access, write(access, conceptId, new Replacement(request.getAsset(), sawExpectedRevision))); + } + + /** + * Adds or replaces the binding of one asset as {@code access} and keeps the concept's other + * bindings. It is {@link #put} without the page it answers with, for a writer that names its own + * guard. Called inside a transaction, it joins that transaction and the ontology lock it holds. + */ + public void replace( + final Access access, + final UUID conceptId, + final OntologyAssetBinding asset, + final RevisionGuard guard) { + write(access, conceptId, new Replacement(asset, guard)); + } + + private OntologyConcept write( + final Access access, final UUID conceptId, final Replacement replacement) { + OntologyBindingRules.validate(replacement.asset()); final var concept = concept(access, conceptId, MetadataOperation.EDIT_ALL); - store.update( + update( + access, concept, (lockedConcept, locked, current) -> - replace(access, lockedConcept, locked, current, request)); - notifyChanged(concept, request.getAsset().getAssetType(), request.getAsset().getAssetId()); - return firstPage(access, concept); + replace(access, lockedConcept, locked, current, replacement)); + notifyChanged(concept, replacement.asset().getAssetType(), replacement.asset().getAssetId()); + return concept; } /** @@ -179,8 +214,11 @@ public OntologyConceptBindingsResponse put( */ private void notifyChanged( final OntologyConcept concept, final OntologyBindingAssetType type, final UUID assetId) { - OntologyTermSearch.bindingsChanged(concept.getEntityReference()); - bindingsChanged.accept(new EntityReference().withType(type.value()).withId(assetId)); + PostCommitActionQueue.runOrDefer( + () -> { + OntologyTermSearch.bindingsChanged(concept.getEntityReference()); + bindingsChanged.accept(new EntityReference().withType(type.value()).withId(assetId)); + }); } public OntologyConceptBindingsResponse remove( @@ -192,11 +230,12 @@ public OntologyConceptBindingsResponse remove( OntologyBindingRules.requireRevision(expectedRevision); final var type = assetType(assetType); final var concept = concept(access, conceptId, MetadataOperation.EDIT_ALL); - store.update( + update( + access, concept, (lockedConcept, locked, current) -> { concept(access, lockedConcept.getId(), MetadataOperation.EDIT_ALL); - authorized(access, type.value(), assetId, MetadataOperation.VIEW_BASIC); + targets.authorized(access, type.value(), assetId, MetadataOperation.VIEW_BASIC); if (locked.find(lockedConcept.getId(), assetId) == null) { return current; } @@ -209,28 +248,55 @@ public OntologyConceptBindingsResponse remove( return firstPage(access, concept); } + /** + * Writes under the ontology lock, and when the write moves the binding revision of the class asks + * for the reconcile of its checks once the outermost transaction has committed. + */ + private void update(final Access access, final OntologyConcept concept, final Mutation mutation) { + final boolean[] moved = {false}; + store.update( + concept, + (lockedConcept, locked, current) -> { + final long next = mutation.apply(lockedConcept, locked, current); + moved[0] = next != current; + return next; + }); + if (moved[0]) { + final UUID ontologyId = concept.getOntology().getId(); + final String user = + access.securityContext() == null + ? Entity.ADMIN_USER_NAME + : access.securityContext().getUserPrincipal().getName(); + PostCommitActionQueue.runOrDefer( + () -> + OntologyCheckReconcileQueue.instance() + .afterBindingWrite(ontologyId, concept.getId(), user)); + } + } + private long replace( final Access access, final OntologyConcept concept, final OntologyConceptBindingStore locked, final long current, - final UpdateOntologyConceptBinding request) { + final Replacement replacement) { concept(access, concept.getId(), MetadataOperation.EDIT_ALL); - final var asset = request.getAsset(); + final var asset = replacement.asset(); final var target = - authorized( + targets.authorized( access, asset.getAssetType().value(), asset.getAssetId(), MetadataOperation.VIEW_BASIC); final var existing = locked.find(concept.getId(), asset.getAssetId()); - if (existing != null - && existing.assetType() == asset.getAssetType() - && OntologyBindingRules.sameColumns(existing.columns(), asset.getColumns())) { + if (existing != null && OntologyBindingRules.sameBinding(existing, asset)) { return current; } - final long next = OntologyBindingRules.nextRevision(current, request.getExpectedRevision()); + final long next = replacement.guard().next(current, existing); final int retained = prune(locked, concept.getId(), asset.getAssetId()); OntologyBindingRules.requireColumnCapacity(retained + listOrEmpty(asset.getColumns()).size()); - validateColumns( - access, concept, existing == null ? List.of() : existing.columns(), asset, target); + if (target instanceof Table table) { + final var write = new Write(access, concept, locked, existing, asset, table); + tableChecks.check(write); + validateColumns(write); + } locked.save( concept.getId(), asset, FullyQualifiedName.buildHash(target.getFullyQualifiedName())); return next; @@ -270,31 +336,38 @@ private static int retainLive( .sum(); } - private void validateColumns( - final Access access, - final OntologyConcept concept, - final List retained, - final OntologyAssetBinding asset, - final EntityInterface target) { + /** + * Checks the column bindings this write adds or changes. One sent back exactly as stored is left + * alone, so a column whose property or path no longer resolves stays until it is rebound. + */ + private void validateColumns(final Write write) { + final List retained = + write.existing() == null ? List.of() : write.existing().columns(); final var additions = - listOrEmpty(asset.getColumns()).stream() + listOrEmpty(write.asset().getColumns()).stream() .filter(binding -> !retained.contains(binding)) .toList(); - final var ancestors = additions.isEmpty() ? Set.of() : store.ancestors(concept); - for (final var binding : additions) { - final var property = - (OntologyProperty) - authorized( - access, - Entity.ONTOLOGY_PROPERTY, - binding.getPropertyId(), - MetadataOperation.VIEW_BASIC); - if (!OntologyBindingRules.isApplicable(concept, property, ancestors) - || !(target instanceof Table table) - || OntologyBindingRules.resolveColumn(table, binding.getColumnPath()) == null) { - throw new BadRequestException( - "Bindings require an applicable same-ontology DATA or OBJECT property and an existing exact column path"); - } + final var ancestors = additions.isEmpty() ? Set.of() : store.ancestors(write.concept()); + additions.forEach(binding -> validateColumn(write, binding, ancestors)); + } + + private void validateColumn( + final Write write, final OntologyColumnBinding binding, final Set ancestors) { + final var property = + (OntologyProperty) + targets.authorized( + write.access(), + Entity.ONTOLOGY_PROPERTY, + binding.getPropertyId(), + MetadataOperation.VIEW_BASIC); + if (!OntologyBindingRules.isApplicable(write.concept(), property, ancestors) + || OntologyBindingRules.resolveColumn(write.table(), binding.getColumnPath()) == null) { + throw new BadRequestException( + "Bindings require an applicable same-ontology DATA or OBJECT property and an existing exact column path"); + } + OntologyBindingRules.requireJoinFor(property, binding); + if (binding.getJoin() != null) { + tableChecks.checkJoin(write, binding.getJoin()); } } @@ -354,11 +427,9 @@ private List visibleAssets(final Access access, final List BindingRow.assetIdsByType(rows) .forEach( (type, ids) -> - loadViewable( - access, - repositories.apply(type.value()), - ids.stream().filter(live::containsKey).toList(), - viewable)); + viewable.putAll( + targets.viewable( + access, type.value(), ids.stream().filter(live::containsKey).toList()))); return rows.stream() .filter(row -> viewable.containsKey(row.assetId())) .map( @@ -368,33 +439,6 @@ private List visibleAssets(final Access access, final List .toList(); } - private > void loadViewable( - final Access access, - final EntityRepository repository, - final List ids, - final Map> viewable) { - if (ids.isEmpty()) { - return; - } - final List entities = - repository.get(access.uriInfo(), ids, fields(repository), Include.NON_DELETED); - final var tags = BulkFieldHydrator.forTags(repository, entities); - for (final T entity : entities) { - try { - authorizer.authorize( - access.securityContext(), - new OperationContext(repository.getEntityType(), MetadataOperation.VIEW_BASIC), - new ResourceContext<>(repository.getEntityType(), entity, repository, tags)); - viewable.put(entity.getId(), entity); - } catch (final AuthorizationException hidden) { - LOG.debug( - "Binding target {} {} is hidden from the reader", - repository.getEntityType(), - entity.getId()); - } - } - } - private OntologyHydratedAssetBinding hydrateAsset( final Hydration hydration, final Visible visible) { return new OntologyHydratedAssetBinding() @@ -402,6 +446,9 @@ private OntologyHydratedAssetBinding hydrateAsset( .withAssetId(visible.row().assetId()) .withAsset(visible.entity().getEntityReference()) .withServiceType(visible.serviceType()) + .withRole(visible.row().role()) + .withSubjectKey(visible.row().subjectKey()) + .withRowFilter(visible.row().rowFilter()) .withColumns( visible.row().columns().stream() .map(column -> hydrateColumn(hydration, visible.entity(), column)) @@ -418,7 +465,8 @@ private OntologyHydratedColumnBinding hydrateColumn( .computeIfAbsent( binding.getPropertyId(), id -> - readable(hydration.access(), Entity.ONTOLOGY_PROPERTY, id) + targets + .readable(hydration.access(), Entity.ONTOLOGY_PROPERTY, id) .map(OntologyProperty.class::cast)); final var column = asset instanceof Table table @@ -438,7 +486,24 @@ private OntologyHydratedColumnBinding hydrateColumn( .withState( resolved ? OntologyColumnBindingState.RESOLVED : OntologyColumnBindingState.UNRESOLVED) .withProperty(property.map(OntologyProperty::getEntityReference).orElse(null)) - .withColumn(column == null ? null : columnMetadata(column)); + .withColumn(column == null ? null : columnMetadata(column)) + .withJoin(binding.getJoin()) + .withJoinTarget(joinTarget(hydration, binding)); + } + + private EntityReference joinTarget( + final Hydration hydration, final OntologyColumnBinding binding) { + return binding.getJoin() == null + ? null + : hydration + .joinTargets() + .computeIfAbsent( + binding.getJoin().getTargetAssetId(), + id -> + targets + .readable(hydration.access(), Entity.TABLE, id) + .map(EntityInterface::getEntityReference)) + .orElse(null); } private static OntologyBoundColumn columnMetadata(final Column column) { @@ -451,55 +516,9 @@ private static OntologyBoundColumn columnMetadata(final Column column) { .withDataTypeDisplay(column.getDataTypeDisplay()); } - private Optional> readable( - final Access access, final String type, final UUID id) { - try { - return Optional.of(authorized(access, type, id, MetadataOperation.VIEW_BASIC)); - } catch (final AuthorizationException | EntityNotFoundException unavailable) { - LOG.debug("Binding target {} {} is unavailable to the current reader", type, id); - return Optional.empty(); - } - } - private OntologyConcept concept( final Access access, final UUID id, final MetadataOperation operation) { - return (OntologyConcept) authorized(access, Entity.ONTOLOGY_CONCEPT, id, operation); - } - - private EntityInterface authorized( - final Access access, final String type, final UUID id, final MetadataOperation operation) { - return authorized(access, repositories.apply(type), id, operation); - } - - private > T authorized( - final Access access, - final EntityRepository repository, - final UUID id, - final MetadataOperation operation) { - final T entity = - repository.get(access.uriInfo(), id, fields(repository), Include.NON_DELETED, false); - authorize(access, repository, entity, operation); - return entity; - } - - private > void authorize( - final Access access, - final EntityRepository repository, - final T entity, - final MetadataOperation operation) { - authorizer.authorize( - access.securityContext(), - new OperationContext(repository.getEntityType(), operation), - new ResourceContext<>(repository.getEntityType(), entity, repository)); - } - - private static Fields fields(final EntityRepository repository) { - final var fieldNames = - new HashSet<>(ResourceContext.authorizationFields(repository).getFieldList()); - if (Entity.TABLE.equals(repository.getEntityType())) { - fieldNames.add(Entity.FIELD_COLUMNS); - } - return new Fields(fieldNames); + return (OntologyConcept) targets.authorized(access, Entity.ONTOLOGY_CONCEPT, id, operation); } static UUID decodeCursor(final String after) { @@ -530,5 +549,14 @@ private record Hydration( Access access, OntologyConcept concept, Set ancestors, - Map> properties) {} + Map> properties, + Map> joinTargets) { + private Hydration( + final Access access, + final OntologyConcept concept, + final Set ancestors, + final Map> properties) { + this(access, concept, ancestors, properties, new HashMap<>()); + } + } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptQueryService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptQueryService.java index ded0fccf8ed0..e2c0c08e82dd 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptQueryService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptQueryService.java @@ -55,6 +55,8 @@ import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.BoundTable; import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.Generated; import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.Hop; +import org.openmetadata.service.ontology.OntologyMappingReader.SearchStart.IdentityTable; +import org.openmetadata.service.ontology.OntologyMappingReader.SearchStart.OnlyTable; import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.policyevaluator.BulkFieldHydrator; @@ -65,16 +67,23 @@ /** * Reads what SQL generation needs in a fixed number of batched statements, whatever the hop count: - * the concepts, the hop properties and their inverses, each concept's first bound tables, those - * tables twice (for the view check, then columns of the kept ones), and the properties their - * columns bind. Tables the reader may not view are treated as unbound, so their columns never - * appear in the SQL. The call writes nothing. + * the concepts, the hop properties and their inverses, the table of the concept the statement + * starts from, the first bound tables of each concept a hop reaches, those tables twice (for the + * view check, then columns of the kept ones), and the properties their columns bind. The call + * writes nothing. + * + *

The table bindings of a concept pick the table its statement starts from, and who asks never + * does (ADR:2026-11-22-record-statements-start-from-the-identity-table). A concept with one table + * binding starts from that table, and a concept with several starts from its identity table. A + * table the reader may not view is treated as unbound, so its columns never appear in the SQL. + * The one exception is the identity table of a concept that binds several tables, which is a 403. */ @Slf4j public final class OntologyConceptQueryService { /** - * Each concept reads its first 100 table bindings and keeps the first 10 the reader may view, in - * asset-id order (ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension). + * Each concept a hop reaches reads its first 100 table bindings and keeps the first 10 the reader + * may view, in asset-id order + * (ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension). */ public static final int TABLE_BINDINGS_READ = 100; @@ -83,6 +92,7 @@ public final class OntologyConceptQueryService { private final OntologyConceptBindingStore store; private final Authorizer authorizer; private final Function> repositories; + private final OntologyMappingReader mapping; public OntologyConceptQueryService( final OntologyConceptBindingStore store, @@ -91,6 +101,8 @@ public OntologyConceptQueryService( this.store = store; this.authorizer = authorizer; this.repositories = repositories; + this.mapping = + new OntologyMappingReader(store, new OntologyBindingAccess(authorizer, repositories)); } public OntologyConceptQuery generate( @@ -103,7 +115,8 @@ public OntologyConceptQuery generate( store.requireLiveOntology(root); final Map relations = relations(access, root, hops); final Inverses inverses = inverses(access, root, relations.values()); - final Map bound = bind(access, concepts.values()); + final Map bound = + bind(access, hops.stream().map(hop -> concepts.get(hop.getTarget())).distinct().toList()); final List steps = new ArrayList<>(); final List labeled = new ArrayList<>(); for (final OntologyConceptQueryHop hop : hops) { @@ -121,7 +134,7 @@ public OntologyConceptQuery generate( .withDirection(hop.getDirection()) .withLabel(step.label())); } - return response(OntologyConceptSqlGenerator.generate(bound.get(conceptId), steps), labeled); + return response(OntologyConceptSqlGenerator.generate(start(access, root), steps), labeled); } } @@ -266,11 +279,47 @@ private Map relations( return properties; } + /** + * The concept a statement starts from, with the one table it starts from. The only table of a + * concept follows the rule of every bound table. A reader who may not view it gets the 400 of a + * concept with no table. + */ + private BoundConcept start(final Access access, final OntologyConcept root) { + return switch (mapping.searchStart(root.getId(), root.getIri())) { + case OnlyTable only -> bound(access, List.of(root), only.rows()).get(root.getId()); + case IdentityTable several -> identityBound(access, root, several.row()); + }; + } + + /** + * A concept with its identity table. A reader who may not view that table gets a 403 that names + * the concept and never the table. + */ + private BoundConcept identityBound( + final Access access, final OntologyConcept root, final BindingRow identity) { + final List rows = List.of(identity); + OntologyMappingReader.identity(root.getIri(), identity, mapping.tables(access, rows)); + final Table table = tablesWithColumns(access, rows).get(identity.assetId()); + return new BoundConcept( + label(root), + List.of(OntologyBoundTables.of(table, identity, boundProperties(access, rows)))); + } + + /** The tables that each concept a hop reaches binds and the reader may view. */ private Map bind( final Access access, final Collection concepts) { - final List rows = + return bound( + access, + concepts, store.firstTables( - concepts.stream().map(OntologyConcept::getId).toList(), TABLE_BINDINGS_READ); + concepts.stream().map(OntologyConcept::getId).toList(), TABLE_BINDINGS_READ)); + } + + /** Each concept with the tables among {@code rows} that it binds and the reader may view. */ + private Map bound( + final Access access, + final Collection concepts, + final List rows) { final Map> visible = firstVisibleTables(rows, viewableTableIds(access, rows)::contains); final List kept = visible.values().stream().flatMap(List::stream).toList(); @@ -280,7 +329,7 @@ private Map bind( for (final OntologyConcept concept : concepts) { final List conceptTables = visible.getOrDefault(concept.getId(), List.of()).stream() - .map(row -> boundTable(tables.get(row.assetId()), row, properties)) + .map(row -> OntologyBoundTables.of(tables.get(row.assetId()), row, properties)) .toList(); bound.put(concept.getId(), new BoundConcept(label(concept), conceptTables)); } @@ -372,56 +421,6 @@ private Map boundProperties( .collect(Collectors.toMap(OntologyProperty::getId, Function.identity())); } - private static BoundTable boundTable( - final Table table, final BindingRow row, final Map properties) { - final List resolved = - row.columns().stream() - .filter(binding -> properties.containsKey(binding.getPropertyId())) - .filter( - binding -> - OntologyBindingRules.resolveColumn(table, binding.getColumnPath()) != null) - .toList(); - return new BoundTable( - table.getFullyQualifiedName(), - table.getServiceType() == null ? null : table.getServiceType().value(), - resolved.stream().map(OntologyColumnBinding::getColumnPath).toList(), - objectColumns(resolved, properties), - identifierColumn(resolved, properties), - listOrEmpty(table.getTableConstraints())); - } - - /** The column each object property is bound to, the first binding winning. */ - private static Map> objectColumns( - final List resolved, final Map properties) { - return resolved.stream() - .filter(binding -> kindOf(properties, binding) == OntologyPropertyKind.OBJECT) - .collect( - Collectors.toMap( - OntologyColumnBinding::getPropertyId, - OntologyColumnBinding::getColumnPath, - (first, ignored) -> first, - LinkedHashMap::new)); - } - - private static List identifierColumn( - final List resolved, final Map properties) { - return resolved.stream() - .filter(binding -> isIdentifier(properties.get(binding.getPropertyId()))) - .findFirst() - .map(OntologyColumnBinding::getColumnPath) - .orElse(List.of()); - } - - private static OntologyPropertyKind kindOf( - final Map properties, final OntologyColumnBinding binding) { - return properties.get(binding.getPropertyId()).getKind(); - } - - private static boolean isIdentifier(final OntologyProperty property) { - return property.getKind() == OntologyPropertyKind.DATA - && Boolean.TRUE.equals(property.getIsIdentifier()); - } - private > Map authorizedAll( final Access access, final String type, final Set ids, final Class kind) { final EntityRepository repository = repositories.apply(type); @@ -476,6 +475,7 @@ private static OntologyConceptQuery response( return new OntologyConceptQuery() .withHops(hops) .withSql(generated.sql()) + .withEscapedSql(generated.escapedSql()) .withDialect(generated.dialect()) .withService(generated.service()) .withServiceType(generated.serviceType()) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java index 638b9a3e3c15..dc22a51cece9 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyConceptSqlGenerator.java @@ -14,67 +14,66 @@ package org.openmetadata.service.ontology; import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.service.ontology.OntologyRecordMapping.conflict; import java.util.ArrayList; import java.util.LinkedHashSet; 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.BiFunction; -import java.util.function.Function; -import java.util.regex.Pattern; -import java.util.stream.Collectors; +import java.util.function.Supplier; import java.util.stream.IntStream; import org.openmetadata.schema.api.data.OntologyConceptQueryDialect; +import org.openmetadata.schema.api.data.OntologyStatementColumn; +import org.openmetadata.schema.api.data.OntologyStatementDirection; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.ontology.OntologyHopJoins.ColumnPair; +import org.openmetadata.service.ontology.OntologyHopJoins.Join; +import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedClass; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyRecordMapping.PropertyColumn; +import org.openmetadata.service.ontology.OntologyRelationPath.Joined; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.ontology.sql.TypedRowFilter; +import org.openmetadata.service.ontology.sql.TypedStatement; +import org.openmetadata.service.ontology.sql.TypedValue; +import org.openmetadata.service.ontology.sql.TypedValues; import org.openmetadata.service.util.FullyQualifiedName; /** - * Builds the SELECT a concept's table bindings describe, with one JOIN per search-around hop. It - * reads no database: callers pass the bound tables the reader may view + * Builds every SELECT that the table bindings of a class describe. It reads no database: callers + * pass the bound tables the reader may view. Each statement keeps the rows that the row filter of + * each table it reads keeps. It is built as a {@link TypedStatement}, so the engine family of the + * first table writes every name and every value + * (ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text). + * + *

{@link #find}, {@link #open}, {@link #expand}, {@link #count} and {@link #top} are about + * records. A record is a row of the identity table whose subject key holds no null, and each of + * these statements starts from that table + * (ADR:2026-11-22-record-statements-start-from-the-identity-table). {@link #generate} lists the + * rows that search-around hops reach * (ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension). */ public final class OntologyConceptSqlGenerator { public static final int ROW_LIMIT = 50; - private static final String NO_VISIBLE_TABLE = + public static final int FIND_ROWS = 25; + public static final int EXPAND_ROWS = 25; + public static final int OPEN_ROWS = 100; + public static final int TOP_RECORDS = 8; + static final String NO_VISIBLE_TABLE = "has no bound table you can view among its first " + OntologyConceptQueryService.TABLE_BINDINGS_READ + " table bindings"; - - private static final Pattern PLAIN_IDENTIFIER = Pattern.compile("[a-z_][a-z0-9_]*"); - - /** - * Each service type whose engine accepts the SQL generated for its dialect. Any other type is a - * named 400 (ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension). - */ - private static final Map DIALECTS = - Map.ofEntries( - Map.entry("Postgres", OntologyConceptQueryDialect.ANSI), - Map.entry("Timescale", OntologyConceptQueryDialect.ANSI), - Map.entry("Redshift", OntologyConceptQueryDialect.ANSI), - Map.entry("Trino", OntologyConceptQueryDialect.ANSI), - Map.entry("Presto", OntologyConceptQueryDialect.ANSI), - Map.entry("Athena", OntologyConceptQueryDialect.ANSI), - Map.entry("Snowflake", OntologyConceptQueryDialect.SNOWFLAKE), - Map.entry("BigQuery", OntologyConceptQueryDialect.BIGQUERY), - Map.entry("Mysql", OntologyConceptQueryDialect.MYSQL), - Map.entry("MariaDB", OntologyConceptQueryDialect.MYSQL), - Map.entry("SingleStore", OntologyConceptQueryDialect.MYSQL), - Map.entry("Doris", OntologyConceptQueryDialect.MYSQL), - Map.entry("StarRocks", OntologyConceptQueryDialect.MYSQL), - Map.entry("Clickhouse", OntologyConceptQueryDialect.MYSQL), - Map.entry("Databricks", OntologyConceptQueryDialect.SPARK), - Map.entry("UnityCatalog", OntologyConceptQueryDialect.SPARK), - Map.entry("Hive", OntologyConceptQueryDialect.SPARK), - Map.entry("Impala", OntologyConceptQueryDialect.SPARK), - Map.entry("Iomete", OntologyConceptQueryDialect.SPARK), - Map.entry("Mssql", OntologyConceptQueryDialect.TSQL), - Map.entry("AzureSQL", OntologyConceptQueryDialect.TSQL), - Map.entry("Synapse", OntologyConceptQueryDialect.TSQL), - Map.entry("MicrosoftFabric", OntologyConceptQueryDialect.TSQL)); + private static final String FIRST = alias(0); + private static final String AFTER = "after key"; + private static final String COUNT = "COUNT(*) AS records"; + private static final String COUNT_LINKS = "COUNT(*) AS links"; + private static final String INNER_JOIN = "JOIN"; + private static final String LEFT_JOIN = "LEFT JOIN"; /** * One table bound to one concept, as that concept binds it. @@ -83,6 +82,9 @@ public final class OntologyConceptSqlGenerator { * @param objectColumns the column each object property is bound to, a foreign key to the target * concept's identifier column * @param identifier the column bound to the concept's identifier property, or empty + * @param rowFilter the binding's row filter with its values parsed, or null when it has none. It + * is asked only for a table the statement reads, and a stored filter that no longer parses + * is a 400 then */ public record BoundTable( String fullyQualifiedName, @@ -90,9 +92,31 @@ public record BoundTable( List> columns, Map> objectColumns, List identifier, - List constraints) {} + List constraints, + Supplier rowFilter) { + /** A table whose binding has no row filter. */ + public BoundTable( + final String fullyQualifiedName, + final String serviceType, + final List> columns, + final Map> objectColumns, + final List identifier, + final List constraints) { + this( + fullyQualifiedName, + serviceType, + columns, + objectColumns, + identifier, + constraints, + () -> null); + } + } - /** A concept and the tables it binds that the reader may view, in asset id order. */ + /** + * A concept and the tables it binds that the reader may view, in asset id order. The concept a + * statement starts from holds the one table that its bindings pick, or no table. + */ public record BoundConcept(String label, List tables) {} /** @@ -108,21 +132,61 @@ Optional otherInverse() { } } + /** + * The statement over search-around hops in its two finished forms. + * + * @param sql the form a person reads + * @param escapedSql the form a reader of {@code :name} parameters runs + */ public record Generated( String sql, + String escapedSql, OntologyConceptQueryDialect dialect, String service, String serviceType, List tables) {} - private record ColumnPair(List left, List right) {} + /** + * A statement about the records of a class. + * + * @param columns what each result column holds, in order + * @param rowCap the most rows a reader takes + * @param extraRow whether the statement asks for one row more than {@code rowCap} + * @param read the tables the statement reads, in join order + * @param orderedBy the indexes of the result columns that hold the key the statement orders by, + * in order, or empty when the statement has no order + */ + record RecordStatement( + TypedStatement text, + SqlEngineFamily family, + List columns, + int rowCap, + boolean extraRow, + List read, + List orderedBy) {} + + /** One statement about records while it is written. */ + private static final class Draft { + private final SqlEngineFamily family; + private final TypedStatement.Builder sql = TypedStatement.builder(); + private final OntologySelectText select; + private final OntologyStatementProjection list = new OntologyStatementProjection(); + private final List read = new ArrayList<>(); + + Draft(final MappedTable first) { + family = SqlEngineFamily.ofServiceType(first.serviceType()); + select = new OntologySelectText(sql, family.dialect()); + read.add(first); + } - private record Join(BoundTable table, List on, String label) {} + RecordStatement finished(final int rowCap, final boolean extraRow) { + return finished(rowCap, extraRow, List.of()); + } - private record Step(int position, Hop hop, BoundTable previous) { - BadRequestException failure(final String reason, final Object... args) { - return new BadRequestException( - String.format("Hop %d (%s)", position, hop.label()) + String.format(reason, args)); + RecordStatement finished( + final int rowCap, final boolean extraRow, final List orderedBy) { + return new RecordStatement( + sql.build(), family, list.columns(), rowCap, extraRow, List.copyOf(read), orderedBy); } } @@ -130,366 +194,421 @@ private OntologyConceptSqlGenerator() {} public static Generated generate(final BoundConcept root, final List hops) { final BoundTable first = rootTable(root); - final Syntax syntax = new Syntax(dialectOf(first.serviceType())); - final List joins = joins(first, hops); - final BoundTable last = joins.isEmpty() ? first : joins.getLast().table(); - final List tables = new ArrayList<>(List.of(first.fullyQualifiedName())); - joins.forEach(join -> tables.add(join.table().fullyQualifiedName())); + final SqlEngineFamily family = SqlEngineFamily.ofServiceType(first.serviceType()); + final List joins = OntologyHopJoins.joins(first, hops); + final List read = new ArrayList<>(List.of(first)); + joins.forEach(join -> read.add(join.table())); + final var finished = family.finish(statement(family.dialect(), read, joins)); return new Generated( - sql(syntax, first, joins, last), - syntax.dialect(), - fqnParts(first, 1).getFirst(), + finished.sql(), + finished.escapedSql(), + family.dialect(), + fqnParts(first.fullyQualifiedName(), 1).getFirst(), first.serviceType(), - List.copyOf(tables)); + read.stream().map(BoundTable::fullyQualifiedName).toList()); } public static OntologyConceptQueryDialect dialectOf(final String serviceType) { - final OntologyConceptQueryDialect dialect = - serviceType == null ? null : DIALECTS.get(serviceType); - if (dialect == null) { - throw new BadRequestException( - String.format("SQL generation does not support %s", serviceType)); - } - return dialect; + return SqlEngineFamily.ofServiceType(serviceType).dialect(); } - private static BoundTable rootTable(final BoundConcept root) { - final List tables = listOrEmpty(root.tables()); - if (tables.isEmpty()) { - throw new BadRequestException(String.format("Concept %s %s", root.label(), NO_VISIBLE_TABLE)); + /** The key, the display name and the bound columns of the identity table, at most 25 rows. */ + static RecordStatement find(final MappedClass type, final String matchText) { + final MappedTable identity = type.identity(); + final Draft draft = new Draft(identity); + draft.list.key(type, FIRST).values(type, identity, FIRST); + draft.list.writeTo(draft.select.select(FIND_ROWS)); + draft.select.from(identity.fullyQualifiedName(), FIRST); + keyIsSet(draft.select, identity, FIRST); + rowFilter(draft.select, identity, FIRST); + if (matchText != null && !matchText.isEmpty()) { + match(draft.select, type, matchText); } - return tables.stream() - .filter(table -> !table.columns().isEmpty()) - .findFirst() - .orElse(tables.getFirst()); + draft.select.limit(FIND_ROWS); + return draft.finished(FIND_ROWS, false); } - private static List joins(final BoundTable first, final List hops) { - final List joins = new ArrayList<>(); - BoundTable previous = first; - for (int index = 0; index < hops.size(); index++) { - final Join join = join(new Step(index + 1, hops.get(index), previous), fqnParts(first, 2)); - joins.add(join); - previous = join.table(); + /** + * Every bound column of one record. A contributing table joins on the subject key with a {@code + * LEFT JOIN} that carries its row filter, so a record with no contributing row still opens, and + * several contributing rows for one key give several rows. + */ + static RecordStatement open( + final MappedClass type, final List contributing, final List key) { + final MappedTable identity = type.identity(); + final List values = TypedValues.key(identity.key(), key); + final List joined = + contributing.stream().filter(table -> !type.dataColumns(table).isEmpty()).toList(); + final Draft draft = new Draft(identity); + draft.list.key(type, FIRST).values(type, identity, FIRST); + for (int index = 0; index < joined.size(); index++) { + draft.list.values(type, joined.get(index), alias(index + 1)); } - return joins; + draft.list.writeTo(draft.select.select(OPEN_ROWS + 1)); + draft.select.from(identity.fullyQualifiedName(), FIRST); + for (int index = 0; index < joined.size(); index++) { + leftJoin(draft, type, joined.get(index), alias(index + 1)); + } + keyEquals(draft.select, identity, values); + rowFilter(draft.select, identity, FIRST); + draft.select.limit(OPEN_ROWS + 1); + return draft.finished(OPEN_ROWS, true); } /** - * A bound hop property follows its binding: through a foreign key on the bound column, else to - * the other table's identifier. An unbound one whose declared inverse is bound takes the - * converse of the join a hop over the inverse would take back. Otherwise it follows the one - * foreign key between the tables. + * The records that one record relates to: the key of the start record, then the key and the + * display name of each related record. It asks for one row more than a page holds. The rows are + * ordered by the key of the related record, in key order, and an {@code after} that holds values + * keeps only the related records whose key comes after it. A null or an empty {@code after} + * starts at the first related record, because a request that leaves the field out reads as an + * empty list. A related key with a column of a type that takes no value, such as JSON, gives a + * statement with no order and an empty {@code orderedBy}, and {@code after} on it is refused + * (ADR:2026-11-22-record-statements-start-from-the-identity-table). */ - private static Join join(final Step step, final List database) { - final List candidates = - candidates(step).stream().filter(table -> database.equals(fqnParts(table, 2))).toList(); - final BoundTable previous = step.previous(); - final UUID property = step.hop().property(); - final Optional boundInverse = - step.hop().otherInverse().filter(inverse -> isBound(previous, candidates, inverse)); - final Optional join; - if (isBound(previous, candidates, property)) { - join = bindingJoin(step, candidates, property, false); - } else if (boundInverse.isPresent()) { - join = bindingJoin(step, candidates, boundInverse.get(), true); - } else { - join = firstJoin(candidates, table -> onlyKeyPairs(step, table), step.hop()); + static RecordStatement expand( + final OntologyRelationPath path, final List key, final List after) { + final MappedTable identity = path.start().identity(); + final List values = TypedValues.key(identity.key(), key); + final MappedTable related = path.related().identity(); + final boolean continued = after != null && !after.isEmpty(); + final List following = + continued ? TypedValues.key(related.key(), after, AFTER) : List.of(); + final String last = alias(path.joins().size()); + final Draft draft = new Draft(identity); + draft.list.key(path.start(), FIRST).key(path.related(), last).displayName(path.related(), last); + draft.list.writeTo(draft.select.select(EXPAND_ROWS + 1)); + chain(draft, path); + keyEquals(draft.select, identity, values); + chainFilters(draft.select, path); + if (continued) { + keyAfter(draft.select, related, following, last); } - return join.orElseThrow( - () -> - step.failure( - ": no foreign key or object-property binding joins %s to a table bound to %s", - step.previous().fullyQualifiedName(), step.hop().target().label())); - } - - private static List candidates(final Step step) { - final BoundConcept target = step.hop().target(); - if (listOrEmpty(target.tables()).isEmpty()) { - throw step.failure(" reaches concept %s, which %s", target.label(), NO_VISIBLE_TABLE); + final boolean ordered = TypedValues.takeValues(related.key()); + if (ordered) { + orderByKey(draft.select, related, last); } - return target.tables(); + draft.select.limit(EXPAND_ROWS + 1); + final int relatedKey = identity.keyPaths().size(); + return draft.finished( + EXPAND_ROWS, + true, + ordered + ? IntStream.range(relatedKey, relatedKey + related.keyPaths().size()).boxed().toList() + : List.of()); } - private static boolean isBound( - final BoundTable previous, final List candidates, final UUID property) { - return previous.objectColumns().containsKey(property) - || candidates.stream().anyMatch(table -> table.objectColumns().containsKey(property)); - } - - private static Optional firstJoin( - final List candidates, - final Function> pairs, - final Hop hop) { - for (final BoundTable candidate : candidates) { - final List on = pairs.apply(candidate); - if (!on.isEmpty()) { - return Optional.of(new Join(candidate, on, hop.label())); - } + /** The number of records of the class in one row: the distinct keys of its identity table. */ + static RecordStatement count(final MappedClass type) { + final MappedTable identity = type.identity(); + final Draft draft = new Draft(identity); + draft.list.count(type); + draft.select.select(1).sql(COUNT); + final OntologySelectText keys = draft.select.fromDistinct(draft.family.dialect()); + final List> key = identity.keyPaths(); + for (int part = 0; part < key.size(); part++) { + draft.sql.sql(part == 0 ? "" : ", ").column(FIRST, key.get(part)).sql(" AS k" + part); } - return Optional.empty(); + keys.from(identity.fullyQualifiedName(), FIRST); + keyIsSet(keys, identity, FIRST); + rowFilter(keys, identity, FIRST); + draft.select.closeDerived("k"); + draft.select.limit(1); + return draft.finished(1, false); } /** - * Follows a bound property, or takes the converse of a hop over a bound inverse from each - * candidate back to the previous table. Every candidate's key equal to the bound column is tried - * before any candidate's key that contains it, and both before the identifier join. + * The records of the start class that relate to the most records along the path, each with its + * key, its display name and the number of related rows it joins. */ - private static Optional bindingJoin( - final Step step, - final List candidates, - final UUID property, - final boolean overInverse) { - final BoundTable previous = step.previous(); - final Function>, Optional> pass = - pairs -> - firstJoin( - candidates, - table -> - overInverse - ? converse(pairs.apply(table, previous)) - : pairs.apply(previous, table), - step.hop()); - return pass.apply((from, to) -> equalKeyPairs(from, to, property)) - .or(() -> pass.apply((from, to) -> containingKeyPairs(step, from, to, property))) - .or(() -> pass.apply((from, to) -> bindingPairs(from, to, property))); + static RecordStatement top(final OntologyRelationPath path) { + final MappedTable identity = path.start().identity(); + final Draft draft = new Draft(identity); + draft.list.key(path.start(), FIRST).displayName(path.start(), FIRST); + draft.list.writeTo(draft.select.select(TOP_RECORDS)).sql(", " + COUNT); + chain(draft, path); + keyIsSet(draft.select, identity, FIRST); + chainFilters(draft.select, path); + draft.list.writeTo(draft.select.clause("GROUP BY")); + draft.select.clause("ORDER BY").sql("records DESC"); + identity.keyPaths().forEach(part -> draft.sql.sql(", ").column(FIRST, part)); + draft.select.limit(TOP_RECORDS); + draft.list.count(path.related()); + return draft.finished(TOP_RECORDS, false); } /** - * The table that binds {@code property}, {@code from} winning over {@code to} as in {@link - * #bindingPairs}, with its bound column and its keys to the other table. + * The number of links of a relation in one row. A link is a pair of a record of the class that + * binds the relation and an object key with no null part. The record passes the row filter of + * its identity table and has a whole key. Over a link table or another contributing table, the + * row of that table joins the record on the subject key and passes the table's own row filter. + * The object need not be a record. The statement has no {@code ORDER BY} and no row limit. + * + *

Forward from the binding class, the count is every link: the statement starts at the + * binding class's identity table and reads the object key from the columns that hold the join. + * Inverse from the other class, the count is the links whose object is a record of the start + * class: the statement starts at the start class's identity table, joins the binding class's + * identity table, through the link table when one holds the join, and applies that table's row + * filter and whole-key rule. The row filter of the object class applies only when the count + * starts from it. */ - private record BoundKeys(boolean reversed, List bound, List keys) { - static Optional of(final BoundTable from, final BoundTable to, final UUID property) { - final boolean reversed = !from.objectColumns().containsKey(property); - final BoundTable owner = reversed ? to : from; - return Optional.ofNullable(owner.objectColumns().get(property)) - .map(bound -> new BoundKeys(reversed, bound, foreignKeys(owner, reversed ? from : to))); + static RecordStatement links(final OntologyRelationPath path) { + final MappedTable identity = path.start().identity(); + final List joins = path.joins(); + final Joined last = joins.getLast(); + final boolean namesKeyOnly = path.direction() == OntologyStatementDirection.FORWARD; + final List read = namesKeyOnly ? joins.subList(0, joins.size() - 1) : joins; + final String relatedAlias = alias(read.size()); + final List> related = + namesKeyOnly + ? last.on().stream().map(JoinPair::previous).toList() + : last.table().keyPaths(); + final Draft draft = new Draft(identity); + draft.list.count(path.related()); + draft.select.selectAll().sql(COUNT_LINKS); + final OntologySelectText keys = draft.select.fromDistinct(draft.family.dialect()); + final List> start = identity.keyPaths(); + for (int part = 0; part < start.size(); part++) { + draft.sql.sql(part == 0 ? "" : ", ").column(FIRST, start.get(part)).sql(" AS k" + part); + } + for (int part = 0; part < related.size(); part++) { + draft.sql.sql(", ").column(relatedAlias, related.get(part)).sql(" AS r" + part); + } + chain(draft, keys, path.start(), read); + keyIsSet(keys, identity, FIRST); + rowFilter(keys, identity, FIRST); + related.forEach(part -> keys.where().column(relatedAlias, part).sql(" IS NOT NULL")); + final int filtered = read.size(); + for (int index = 0; index < filtered; index++) { + rowFilter(keys, read.get(index).table(), alias(index + 1)); } + draft.select.closeDerived("k"); + return draft.finished(1, false); } - private static List equalKeyPairs( - final BoundTable from, final BoundTable to, final UUID property) { - return BoundKeys.of(from, to, property) - .flatMap( - bound -> - bound.keys().stream() - .filter(key -> key.getColumns().equals(bound.bound())) - .findFirst() - .map(key -> pairs(key, bound.reversed()))) - .orElse(List.of()); + /** + * Text with no uppercase letter matches without regard to case. Text with an uppercase letter + * matches as written, because the text reaches the statement only as the pattern that {@link + * TypedValues#searchText} parsed and is never rewritten on the way. + */ + private static void match( + final OntologySelectText select, final MappedClass type, final String matchText) { + final PropertyColumn name = + type.displayName() + .orElseThrow( + () -> + conflict( + "Class %s binds no display name column on its identity table, so it takes" + + " no match text", + type.iri())); + final TypedValue text = TypedValues.searchText(type.identity().require(name.path()), matchText); + final boolean anyCase = matchText.equals(matchText.toLowerCase(Locale.ROOT)); + final TypedStatement.Builder sql = select.where(); + if (anyCase) { + sql.sql("LOWER(").column(FIRST, name.path()).sql(")"); + } else { + sql.column(FIRST, name.path()); + } + sql.sql(" LIKE ").contains(text); } - /** The one key that contains the bound column orients and joins on all of its columns. */ - private static List containingKeyPairs( - final Step step, final BoundTable from, final BoundTable to, final UUID property) { - final BoundKeys found = BoundKeys.of(from, to, property).orElse(null); - if (found == null || found.bound().size() != 1) { - return List.of(); - } - final String column = found.bound().getFirst(); - final List containing = - found.keys().stream().filter(key -> key.getColumns().contains(column)).toList(); - if (containing.size() > 1) { - throw step.failure( - ": %s is in several foreign keys between %s and %s", - column, - step.previous().fullyQualifiedName(), - (from == step.previous() ? to : from).fullyQualifiedName()); + private static void leftJoin( + final Draft draft, final MappedClass type, final MappedTable table, final String alias) { + requireSameDatabase(type, table); + final TypedStatement.Builder on = + draft.select.join(LEFT_JOIN, table.fullyQualifiedName(), alias); + equalColumns(on, type.keyPairs(table), FIRST, alias); + final TypedRowFilter filter = table.filter(); + if (filter != null) { + filter.appendTo(on.sql(" AND "), alias); } - return containing.isEmpty() ? List.of() : pairs(containing.getFirst(), found.reversed()); + draft.read.add(table); } - private static BadRequestException severalKeys(final Step step, final BoundTable candidate) { - return step.failure( - ": several foreign keys join %s and %s; bind the %s property to one of their columns", - step.previous().fullyQualifiedName(), candidate.fullyQualifiedName(), step.hop().label()); + /** The start table, then one inner join for each table of the path. */ + private static void chain(final Draft draft, final OntologyRelationPath path) { + chain(draft, draft.select, path.start(), path.joins()); } - private static List onlyKeyPairs(final Step step, final BoundTable candidate) { - final List outgoing = foreignKeys(step.previous(), candidate); - final boolean toItself = - candidate.fullyQualifiedName().equals(step.previous().fullyQualifiedName()); - // A key from a table to itself is both outgoing and incoming; count it once. - final List incoming = - toItself ? List.of() : foreignKeys(candidate, step.previous()); - if (outgoing.size() + incoming.size() > 1) { - throw severalKeys(step, candidate); + /** The start table, then one inner join for each of {@code joins}, written by {@code select}. */ + private static void chain( + final Draft draft, + final OntologySelectText select, + final MappedClass start, + final List joins) { + select.from(start.identity().fullyQualifiedName(), FIRST); + for (int index = 0; index < joins.size(); index++) { + final Joined joined = joins.get(index); + requireSameDatabase(start, joined.table()); + equalColumns( + select.join(INNER_JOIN, joined.table().fullyQualifiedName(), alias(index + 1)), + joined.on(), + alias(index), + alias(index + 1)); + draft.read.add(joined.table()); } - // The property and its inverse read the key in opposite directions, and neither says which. - if (toItself && !outgoing.isEmpty() && step.hop().otherInverse().isPresent()) { - final TableConstraint key = outgoing.getFirst(); - throw step.failure( - ": the foreign key from %s to %s joins %s to itself in either direction;" - + " bind the %s property or its inverse to %s%s", - String.join(", ", key.getColumns()), - pairs(key, false).stream() - .map(pair -> String.join(".", pair.right())) - .collect(Collectors.joining(", ")), - candidate.fullyQualifiedName(), - step.hop().label(), - key.getColumns().size() > 1 ? "one of " : "", - String.join(", ", key.getColumns())); + } + + /** The row filter of every table on the path, and a related key that holds no null. */ + private static void chainFilters( + final OntologySelectText select, final OntologyRelationPath path) { + rowFilter(select, path.start().identity(), FIRST); + final int last = path.joins().size() - 1; + for (int index = 0; index <= last; index++) { + final MappedTable table = path.joins().get(index).table(); + if (index == last) { + keyIsSet(select, table, alias(index + 1)); + } + rowFilter(select, table, alias(index + 1)); } - return outgoing.isEmpty() - ? incoming.stream().findFirst().map(key -> pairs(key, true)).orElse(List.of()) - : pairs(outgoing.getFirst(), false); } - private static List foreignKeys( - final BoundTable owner, final BoundTable referred) { - return listOrEmpty(owner.constraints()).stream() - .filter( - constraint -> - constraint.getConstraintType() == TableConstraint.ConstraintType.FOREIGN_KEY) - .filter(constraint -> refersTo(constraint, referred.fullyQualifiedName())) - .toList(); + static void equalColumns( + final TypedStatement.Builder on, + final List pairs, + final String previous, + final String joined) { + for (int index = 0; index < pairs.size(); index++) { + on.sql(index == 0 ? "" : " AND ") + .column(joined, pairs.get(index).joined()) + .sql(" = ") + .column(previous, pairs.get(index).previous()); + } } - private static boolean refersTo(final TableConstraint constraint, final String table) { - final List referred = listOrEmpty(constraint.getReferredColumns()); - return !referred.isEmpty() - && referred.size() == listOrEmpty(constraint.getColumns()).size() - && referred.stream().allMatch(column -> table.equals(tableOf(column))); + private static void keyIsSet( + final OntologySelectText select, final MappedTable table, final String alias) { + // A key column that left the table is a 409 here, before any text names it. + table.key(); + table.keyPaths().forEach(part -> select.where().column(alias, part).sql(" IS NOT NULL")); } - private static String tableOf(final String column) { - return FullyQualifiedName.split(column).length < 5 - ? "" - : FullyQualifiedName.getTableFQN(column); + private static void keyEquals( + final OntologySelectText select, final MappedTable identity, final List values) { + final List> key = identity.keyPaths(); + for (int part = 0; part < key.size(); part++) { + select.where().column(FIRST, key.get(part)).sql(" = ").value(values.get(part)); + } } - private static List pairs(final TableConstraint constraint, final boolean reversed) { - return IntStream.range(0, constraint.getColumns().size()) - .mapToObj( - index -> { - final List local = List.of(constraint.getColumns().get(index)); - final List remote = - List.of( - FullyQualifiedName.unquoteName( - FullyQualifiedName.getColumnName( - constraint.getReferredColumns().get(index)))); - return reversed ? new ColumnPair(remote, local) : new ColumnPair(local, remote); - }) - .toList(); + /** + * Keeps the rows whose key comes after {@code values} in key order, written as {@code (k1 > v1) + * OR (k1 = v1 AND k2 > v2) ...} because several engines have no row-value comparison. The engine + * compares, with its own collation. + */ + private static void keyAfter( + final OntologySelectText select, + final MappedTable table, + final List values, + final String alias) { + final List> key = table.keyPaths(); + final TypedStatement.Builder sql = select.where(); + final boolean several = key.size() > 1; + sql.sql(several ? "(" : ""); + for (int part = 0; part < key.size(); part++) { + sql.sql(part == 0 ? "" : " OR ").sql(part == 0 ? "" : "("); + for (int equal = 0; equal < part; equal++) { + sql.column(alias, key.get(equal)).sql(" = ").value(values.get(equal)).sql(" AND "); + } + sql.column(alias, key.get(part)).sql(" > ").value(values.get(part)); + sql.sql(part == 0 ? "" : ")"); + } + sql.sql(several ? ")" : ""); } - private static List bindingPairs( - final BoundTable from, final BoundTable to, final UUID property) { - final List outgoing = from.objectColumns().get(property); - if (outgoing != null && !to.identifier().isEmpty()) { - return List.of(new ColumnPair(outgoing, to.identifier())); + /** {@code ORDER BY} the key columns of {@code table}, ascending, in key order. */ + private static void orderByKey( + final OntologySelectText select, final MappedTable table, final String alias) { + final TypedStatement.Builder sql = select.clause("ORDER BY"); + final List> key = table.keyPaths(); + for (int part = 0; part < key.size(); part++) { + sql.sql(part == 0 ? "" : ", ").column(alias, key.get(part)); } - final List incoming = to.objectColumns().get(property); - return incoming != null && !from.identifier().isEmpty() - ? List.of(new ColumnPair(from.identifier(), incoming)) - : List.of(); } - private static List converse(final List pairs) { - return pairs.stream().map(pair -> new ColumnPair(pair.right(), pair.left())).toList(); + private static void rowFilter( + final OntologySelectText select, final MappedTable table, final String alias) { + final TypedRowFilter filter = table.filter(); + if (filter != null) { + filter.appendTo(select.where(), alias); + } } - private static String sql( - final Syntax syntax, final BoundTable first, final List joins, final BoundTable last) { - final String lastAlias = joins.isEmpty() ? null : alias(joins.size()); - final List lines = new ArrayList<>(); - lines.add(syntax.select() + " " + selectList(syntax, last, lastAlias)); - lines.add("FROM " + tableName(syntax, first) + (joins.isEmpty() ? "" : " " + alias(0))); - IntStream.range(0, joins.size()) - .forEach(index -> lines.add(joinLine(syntax, joins.get(index), index + 1))); - syntax.limit().ifPresent(lines::add); - return String.join("\n", lines); + /** A statement names {@code schema.table}, so every table it reads sits in one database. */ + private static void requireSameDatabase(final MappedClass type, final MappedTable table) { + if (!type.identity().database().equals(table.database())) { + throw conflict( + "Table %s is in another database than the identity table of class %s", + table.fullyQualifiedName(), type.iri()); + } } - private static String selectList( - final Syntax syntax, final BoundTable table, final String alias) { - final Set> columns = new LinkedHashSet<>(table.columns()); - if (columns.isEmpty()) { - return alias == null ? "*" : alias + ".*"; + /** The one table a statement starts from, which its caller found from the table bindings. */ + private static BoundTable rootTable(final BoundConcept root) { + final List tables = listOrEmpty(root.tables()); + if (tables.isEmpty()) { + throw new BadRequestException(String.format("Concept %s %s", root.label(), NO_VISIBLE_TABLE)); } - return columns.stream() - .map(path -> syntax.column(alias, path)) - .collect(Collectors.joining(", ")); + return tables.getFirst(); } - private static String joinLine(final Syntax syntax, final Join join, final int index) { - final String on = - join.on().stream() - .map( - pair -> - syntax.column(alias(index - 1), pair.left()) - + " = " - + syntax.column(alias(index), pair.right())) - .collect(Collectors.joining(" AND ")); - final String line = - "JOIN " + tableName(syntax, join.table()) + " " + alias(index) + " ON " + on; - final String label = comment(join.label()); - return label.isEmpty() ? line : line + " -- " + label; + /** + * The statement over the tables it reads, in join order: the first table, then one for each + * hop. It selects the bound columns of the last table. A hop's relation label is no part of the + * statement, and callers return the labels beside it. + */ + private static TypedStatement statement( + final OntologyConceptQueryDialect dialect, + final List read, + final List joins) { + final boolean aliased = !joins.isEmpty(); + final TypedStatement.Builder sql = TypedStatement.builder(); + final OntologySelectText select = new OntologySelectText(sql, dialect); + selectList(select.select(ROW_LIMIT), read.getLast(), aliased ? alias(joins.size()) : null); + select.from(read.getFirst().fullyQualifiedName(), aliased ? FIRST : null); + for (int index = 0; index < joins.size(); index++) { + joinLine(select, joins.get(index), index + 1); + } + for (int index = 0; index < read.size(); index++) { + final TypedRowFilter filter = read.get(index).rowFilter().get(); + if (filter != null) { + filter.appendTo(select.where(), aliased ? alias(index) : null); + } + } + select.limit(ROW_LIMIT); + return sql.build(); } - private static String comment(final String label) { - return label == null ? "" : label.replaceAll("\\p{Cntrl}", " ").strip(); + private static void selectList( + final TypedStatement.Builder sql, final BoundTable table, final String alias) { + final List> columns = List.copyOf(new LinkedHashSet<>(table.columns())); + if (columns.isEmpty()) { + sql.sql(alias == null ? "*" : alias + ".*"); + } else { + sql.column(alias, columns.getFirst()); + columns.subList(1, columns.size()).forEach(path -> sql.sql(", ").column(alias, path)); + } } - private static String alias(final int index) { - return "t" + index; + private static void joinLine(final OntologySelectText select, final Join join, final int index) { + final TypedStatement.Builder on = + select.join(INNER_JOIN, join.table().fullyQualifiedName(), alias(index)); + for (int pair = 0; pair < join.on().size(); pair++) { + final ColumnPair columns = join.on().get(pair); + on.sql(pair == 0 ? "" : " AND ") + .column(alias(index - 1), columns.left()) + .sql(" = ") + .column(alias(index), columns.right()); + } } - private static String tableName(final Syntax syntax, final BoundTable table) { - final String[] parts = FullyQualifiedName.split(table.fullyQualifiedName()); - return syntax.identifier(FullyQualifiedName.unquoteName(parts[parts.length - 2])) - + "." - + syntax.identifier(FullyQualifiedName.unquoteName(parts[parts.length - 1])); + static String alias(final int index) { + return "t" + index; } /** The first {@code count} unquoted FQN parts: 1 is the service, 2 its database too. */ - private static List fqnParts(final BoundTable table, final int count) { - return List.of(FullyQualifiedName.split(table.fullyQualifiedName())).subList(0, count).stream() + static List fqnParts(final String tableFqn, final int count) { + return List.of(FullyQualifiedName.split(tableFqn)).subList(0, count).stream() .map(FullyQualifiedName::unquoteName) .toList(); } - - private record Syntax(OntologyConceptQueryDialect dialect) { - String select() { - return dialect == OntologyConceptQueryDialect.TSQL ? "SELECT TOP " + ROW_LIMIT : "SELECT"; - } - - Optional limit() { - return dialect == OntologyConceptQueryDialect.TSQL - ? Optional.empty() - : Optional.of("LIMIT " + ROW_LIMIT); - } - - String column(final String alias, final List path) { - final String quoted = path.stream().map(this::identifier).collect(Collectors.joining(".")); - return alias == null ? quoted : alias + "." + quoted; - } - - /** - * Quoting never changes how the backtick and bracket dialects resolve a name, so they quote - * all. Snowflake's connector stores names in the case Snowflake reports, so the quoted stored - * name always resolves to the ingested object, while an unquoted lowercase name folds to upper - * case. The ANSI engines store and fold names in lowercase, so they quote only a name that - * lowercase folding or a reserved word would misread. - */ - String identifier(final String name) { - return switch (dialect) { - case TSQL -> "[" + name.replace("]", "]]") + "]"; - case BIGQUERY -> "`" + name.replace("\\", "\\\\").replace("`", "\\`") + "`"; - case MYSQL, SPARK -> "`" + name.replace("`", "``") + "`"; - case SNOWFLAKE -> doubleQuoted(name); - case ANSI -> readsPlain(name) ? name : doubleQuoted(name); - }; - } - - private static boolean readsPlain(final String name) { - return PLAIN_IDENTIFIER.matcher(name).matches() - && !OntologySqlReservedWords.ANSI.contains(name); - } - - private static String doubleQuoted(final String name) { - return "\"" + name.replace("\"", "\"\"") + "\""; - } - } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountReader.java new file mode 100644 index 000000000000..703245a42542 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountReader.java @@ -0,0 +1,305 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.service.ontology.OntologyCountRules.JOIN_HOLDERS_PER_CLASS; +import static org.openmetadata.service.ontology.OntologyCountRules.ROWS_PER_CLASS; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.function.BinaryOperator; +import java.util.function.ToLongFunction; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.openmetadata.schema.api.data.NativeOntologyCount; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.ColumnProfile; +import org.openmetadata.schema.type.EntityProfile; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.jdbi3.TimeSeriesDAOs.ProfilerDataTimeSeriesDAO; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyCountRules.ClassRows; +import org.openmetadata.service.ontology.OntologyCountRules.Facts; +import org.openmetadata.service.ontology.OntologyCountRules.Relation; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * Reads what {@link OntologyCountRules} needs for the classes and relations of one response, and + * applies the rules. Each kind is read once for the whole response, whatever the number of classes + * and relations: the binding rows of all classes in one statement, their identity tables in one + * batch read, and the latest table profiles and the latest column profiles in one statement each. + * Nothing is stored and nothing is sent to the database that a table is bound to. + */ +final class OntologyCountReader { + /** The ids, among {@code references}, that the caller may perform {@code operation} on. */ + @FunctionalInterface + interface Visibility { + Set viewable( + Access access, List references, MetadataOperation operation); + } + + /** The counts of one response. */ + record Counts(Map records, Map links) { + static final Counts NONE = new Counts(Map.of(), Map.of()); + } + + private final CollectionDAO dao; + private final OntologyConceptBindingStore store; + private final OntologyBindingAccess catalog; + private final Visibility visibility; + + OntologyCountReader( + final CollectionDAO dao, + final OntologyConceptBindingStore store, + final OntologyBindingAccess catalog, + final Visibility visibility) { + this.dao = dao; + this.store = store; + this.catalog = catalog; + this.visibility = visibility; + } + + /** + * @param classes the classes whose records are asked for + * @param relations the relations whose links are asked for; their classes are read too + */ + Counts read(final Access access, final Collection classes, final List relations) { + final Set all = new LinkedHashSet<>(classes); + relations.forEach( + relation -> { + all.add(relation.subject()); + all.add(relation.object()); + }); + if (all.isEmpty()) { + return Counts.NONE; + } + final Map firstRows = + classRows(all, store.identityFirstTables(all, ROWS_PER_CLASS), ROWS_PER_CLASS); + final Facts first = facts(access, firstRows.values()); + final Set checked = new HashSet<>(); + final Set deleted = new HashSet<>(); + markDeleted(firstRows.values(), checked, deleted); + final Map rows = readInFull(firstRows, relations, first.withDeleted(deleted)); + markDeleted(rows.values(), checked, deleted); + final Facts facts = first.withDeleted(deleted); + final Map records = new LinkedHashMap<>(); + for (final UUID id : classes) { + final var count = OntologyCountRules.records(rows.get(id), facts); + if (count != null) { + records.put(id, count); + } + } + final Map links = new LinkedHashMap<>(); + for (final Relation relation : relations) { + final var count = OntologyCountRules.links(relation, rows, facts); + if (count != null) { + links.put(relation, count); + } + } + return new Counts(records, links); + } + + /** + * The classes whose rows hold no confirmed join onto the table of a relation they hold and that + * were cut by the first read, read again as the statements of the mapping read them: the + * identity row and up to {@link OntologyCountRules#JOIN_HOLDERS_PER_CLASS} - 1 contributing + * rows, in one more statement for each group of classes that keeps it within one scan page. A + * page where no class is cut runs no more statement. + */ + private Map readInFull( + final Map rows, final List relations, final Facts facts) { + final Set cut = new LinkedHashSet<>(); + for (final Relation relation : relations) { + if (OntologyCountRules.needsAFullRead(relation, rows, facts)) { + cut.add(relation.subject()); + } + } + if (cut.isEmpty()) { + return rows; + } + final Map wide = new LinkedHashMap<>(rows); + wide.putAll( + classRows( + cut, store.joinHolderTables(cut, JOIN_HOLDERS_PER_CLASS), JOIN_HOLDERS_PER_CLASS)); + return wide; + } + + /** + * Adds to {@code deleted} the contributing tables, among the rows that hold a join and are not + * yet {@code checked}, that do not exist. One statement for all of them, and none when no such + * row holds a join. + */ + private void markDeleted( + final Collection classes, final Set checked, final Set deleted) { + final List holding = + classes.stream() + .flatMap(rows -> rows.rows().stream()) + .filter(row -> row.role() == OntologyBindingRole.CONTRIBUTING) + .filter(row -> listOrEmpty(row.columns()).stream().anyMatch(c -> c.getJoin() != null)) + .filter(row -> !checked.contains(row.assetId())) + .toList(); + if (holding.isEmpty()) { + return; + } + final Set live = store.liveAssets(holding).keySet(); + for (final BindingRow row : holding) { + checked.add(row.assetId()); + if (!live.contains(row.assetId())) { + deleted.add(row.assetId()); + } + } + } + + private static Map classRows( + final Collection ids, final List read, final int perClass) { + final Map> byClass = new HashMap<>(); + read.forEach(row -> byClass.computeIfAbsent(row.conceptId(), id -> new ArrayList<>()).add(row)); + final Map rows = new LinkedHashMap<>(); + for (final UUID id : ids) { + final List own = byClass.getOrDefault(id, List.of()); + final List ordered = + Stream.concat( + own.stream().filter(row -> row.role() == OntologyBindingRole.IDENTITY), + own.stream().filter(row -> row.role() != OntologyBindingRole.IDENTITY)) + .toList(); + rows.put(id, new ClassRows(id, ordered, own.size() >= perClass)); + } + return rows; + } + + private Facts facts(final Access access, final Collection classes) { + final List identities = + classes.stream().map(ClassRows::identity).filter(Objects::nonNull).toList(); + final Map tables = + catalog.viewableTables(access, identities.stream().map(BindingRow::assetId).toList()); + final Set permitted = + tables.isEmpty() + ? Set.of() + : visibility.viewable( + access, + tables.values().stream().map(Table::getEntityReference).toList(), + MetadataOperation.VIEW_DATA_PROFILE); + final List profiled = + identities.stream() + .filter(row -> tables.containsKey(row.assetId()) && permitted.contains(row.assetId())) + .toList(); + return new Facts( + tables, permitted, tableProfiles(profiled, tables), columnProfiles(profiled, tables)); + } + + private Map tableProfiles( + final List profiled, final Map tables) { + final Map byFqn = + latest( + profiled.stream() + .map(row -> tables.get(row.assetId()).getFullyQualifiedName()) + .toList(), + ProfilerDataTimeSeriesDAO.TABLE_PROFILE_EXTENSION, + TableProfile.class, + TableProfile::getTimestamp, + OntologyCountReader::sampledOverWhole); + final Map byId = new HashMap<>(); + for (final BindingRow row : profiled) { + final var profile = byFqn.get(tables.get(row.assetId()).getFullyQualifiedName()); + if (profile != null) { + byId.put(row.assetId(), profile); + } + } + return byId; + } + + /** The profile of the column paths that a class's counts can read, by column name. */ + private Map columnProfiles( + final List profiled, final Map tables) { + final List fqns = new ArrayList<>(); + for (final BindingRow row : profiled) { + final Table table = tables.get(row.assetId()); + for (final List path : OntologyCountRules.profiledPaths(row)) { + final var column = OntologyBindingRules.resolveColumn(table, path); + if (column != null && column.getFullyQualifiedName() != null) { + fqns.add(column.getFullyQualifiedName()); + } + } + } + return latest( + fqns.stream().distinct().toList(), + ProfilerDataTimeSeriesDAO.TABLE_COLUMN_PROFILE_EXTENSION, + ColumnProfile.class, + ColumnProfile::getTimestamp, + (first, second) -> first); + } + + /** + * The newest stored profile of each entity, by fully qualified name, from one statement. Two + * profiles with one timestamp are told apart by {@code tie}. + */ + private Map latest( + final List fqns, + final String extension, + final Class type, + final ToLongFunction timestamp, + final BinaryOperator tie) { + if (fqns.isEmpty()) { + return Map.of(); + } + final Map byHash = + fqns.stream() + .distinct() + .collect(Collectors.toMap(FullyQualifiedName::buildHash, fqn -> fqn, (a, b) -> a)); + final Map latest = new HashMap<>(); + for (final var record : + dao.profilerDataTimeSeriesDao().getLatestExtensionsBatch(fqns, extension)) { + final var entity = JsonUtils.readValue(record.json(), EntityProfile.class); + final String fqn = byHash.get(record.entityFQNHash()); + if (entity == null || entity.getProfileData() == null || fqn == null) { + continue; + } + final T profile = JsonUtils.convertValue(entity.getProfileData(), type); + latest.merge( + fqn, + profile, + (first, second) -> + timestamp.applyAsLong(first) == timestamp.applyAsLong(second) + ? tie.apply(first, second) + : timestamp.applyAsLong(first) > timestamp.applyAsLong(second) ? first : second); + } + return latest; + } + + /** + * Two table profiles with one timestamp can come from different operations. The one that + * records a sample is kept, so a doubt never makes a sampled profile look whole. + */ + private static TableProfile sampledOverWhole( + final TableProfile first, final TableProfile second) { + return first.getProfileSample() != null || second.getProfileSample() == null ? first : second; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java new file mode 100644 index 000000000000..ea13c54a9f6e --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyCountRules.java @@ -0,0 +1,672 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.openmetadata.schema.api.data.NativeOntologyCount; +import org.openmetadata.schema.api.data.NativeOntologyCount.State; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.ColumnProfile; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyRelationPath.Lookup; + +/** + * When the stored profiles of a table give the exact number of a class's records or of a + * relation's links, and when they do not. A count is exact or it is absent. A profile's table row + * count is never read, because the profiler may take it from the engine's catalog, where it can be + * an estimate (ADR:2026-11-22-a-count-is-exact-or-absent). The column metrics {@code valuesCount}, + * {@code nullCount} and {@code distinctCount} are counted over the rows the profiler read, which + * can be the whole table, a sample, a partition window or the result of a query. + * + *

Nothing here reads a database or a policy. Callers pass what they read. + */ +final class OntologyCountRules { + /** + * The identity row first, then the other table rows of a class, at most {@value #ROWS_PER_CLASS} + * in all, so that the response of a page of classes is read with rows well inside one scan page. + * A class that holds a relation onto a table and whose rows hold no confirmed join onto it is + * read again in full, as {@link #JOIN_HOLDERS_PER_CLASS} rows, so that its state is the one the + * statements of the mapping give. + */ + static final int ROWS_PER_CLASS = 5; + + /** + * The identity row and the contributing rows that the statements of the mapping read, one more + * than they accept, so that a class over the limit is told from a class at it. + */ + static final int JOIN_HOLDERS_PER_CLASS = OntologyMappingReader.MAX_CONTRIBUTING_TABLES + 2; + + /** + * The engines that check a declared primary or unique key, so a duplicate row cannot exist + * beside one. Snowflake, BigQuery, Redshift, Databricks, Unity Catalog, Synapse and Fabric store + * a declared key and never check it, so a table there can hold a duplicate that its declared key + * says is impossible, and no count may rest on the declaration. + */ + private static final Set ENGINES_THAT_ENFORCE_KEYS = + Set.of( + "Postgres", + "Timescale", + "Cockroach", + "Greenplum", + "Mysql", + "MariaDB", + "SingleStore", + "Mssql", + "AzureSQL", + "Oracle", + "Db2", + "SQLite"); + + private static final Set SQL_SERVER_TRUNCATED_TEXT = + EnumSet.of(ColumnDataType.TEXT, ColumnDataType.MEDIUMTEXT, ColumnDataType.NTEXT); + + private static final Set SQL_SERVER_TRUNCATED_BINARY = + EnumSet.of(ColumnDataType.IMAGE); + + private static final Set ORACLE_LENGTH_COUNTED = + EnumSet.of( + ColumnDataType.BYTES, + ColumnDataType.BYTEA, + ColumnDataType.BINARY, + ColumnDataType.VARBINARY, + ColumnDataType.BLOB); + + /** + * The column types whose distinct values the profiler counts after a transform, by service type, + * so that {@code distinctCount} can be below the number of distinct values. The profiler's + * {@code DistinctCount} is {@code count(distinct(CountFn(col)))}, and {@code CountFn} + * ({@code ingestion/src/metadata/profiler/orm/functions/count.py}) compiles to: + * + *

    + *
  • on the {@code mssql} dialect, which Mssql, AzureSQL, Synapse and MicrosoftFabric all + * use ({@code mssql+pyodbc}), {@code cast(col as [nvarchar])} for a column of the + * SQLAlchemy type {@code TEXT} or {@code NVARCHAR}, which are the types TEXT, MEDIUMTEXT + * and NTEXT (XML is a {@code TEXT} subclass, and the profiler computes no metric for it). + * A cast with no length keeps 30 characters, so two values that share their first 30 + * characters count once; + *
  • on the same dialect, {@code cast(col as [varbinary])} for the type IMAGE, which keeps 30 + * bytes, so two values that share their first 30 bytes count once; + *
  • on the {@code oracle} dialect, {@code DBMS_LOB.GETLENGTH(col)} for the {@code + * HexByteString} types, which are BYTES, BYTEA, BINARY, VARBINARY and BLOB, so the count + * is the number of distinct lengths. + *
+ * + * No other dialect function of {@code CountFn} exists, and no other metric function in {@code + * profiler/metrics/static} or {@code profiler/orm/functions} transforms a value before it is + * counted. On the SQL path {@code valuesCount} is {@code count(CountFn(col))} and {@code + * nullCount} is a sum of {@code col IS NULL}: a cast or a length of a null is null and of a value + * is never null, so neither changes with a transform, and a link count, which reads only those + * two and tests {@code distinctCount == valuesCount} (a count too low can only fail that test), + * is not affected there. The dataframe path is different ({@link #PROFILED_FROM_DATAFRAMES}). + */ + private static final Map> TRANSFORMED_BEFORE_DISTINCT_COUNT = + Map.of( + "Mssql", union(SQL_SERVER_TRUNCATED_TEXT, SQL_SERVER_TRUNCATED_BINARY), + "AzureSQL", union(SQL_SERVER_TRUNCATED_TEXT, SQL_SERVER_TRUNCATED_BINARY), + "Synapse", union(SQL_SERVER_TRUNCATED_TEXT, SQL_SERVER_TRUNCATED_BINARY), + "MicrosoftFabric", union(SQL_SERVER_TRUNCATED_TEXT, SQL_SERVER_TRUNCATED_BINARY), + "Oracle", ORACLE_LENGTH_COUNTED); + + /** + * The service types whose tables are profiled through a dataframe, so that a column's metrics + * are not counted over the rows as stored. The profiler interface of each reads the table in + * chunks and casts every chunk to the column types of the catalog before any metric + * ({@code PandasProfilerInterface._type_casted_dataset}, {@code + * ingestion/src/metadata/profiler/interface/pandas/profiler_interface.py:121-141}, with the + * mapping in {@code utils/datalake/datalake_utils.py:337-350}). A null in a string column becomes + * the text {@code 'None'} or {@code 'nan'}, in a bytes column {@code b'None'}, and in a boolean + * column {@code True}, so {@code nullCount} falls to 0 and {@code valuesCount} and {@code + * distinctCount} count the nulls. The service types, with the profiler that each names: + * + *
    + *
  • {@code Datalake}: {@code profiler_class=PandasProfilerInterface}, {@code + * ingestion/source/database/datalake/service_spec.py:14}; the class is declared at {@code + * profiler/interface/pandas/profiler_interface.py:61}; + *
  • {@code BurstIQ}: {@code profiler_class=BurstIQProfilerInterface}, {@code + * ingestion/source/database/burstiq/service_spec.py:16}; the class extends {@code + * PandasProfilerInterface} at {@code + * profiler/interface/pandas/burstiq/profiler_interface.py:49}. + *
+ * + * No other service type names a profiler that extends {@code PandasProfilerInterface}. The NoSQL + * service types (Cassandra, DynamoDB, MongoDB) compute no distinct, values or null count at all, + * so they store no column profile to read. + */ + private static final Set PROFILED_FROM_DATAFRAMES = Set.of("Datalake", "BurstIQ"); + + /** + * The service types whose column counts come from a catalog's statistics instead of a count over + * the rows, either because the profiler can read them from the catalog or because the connector + * writes the profile itself. The stored profile does not say which path made it, a pipeline's + * {@code useStatistics} can change after a run, and a run can come from outside a pipeline, so no + * table of these service types gives an exact count. Every profiler that reads catalog statistics + * extends {@code ProfilerWithStatistics} ({@code + * profiler/interface/sqlalchemy/stored_statistics_profiler.py:49}), which replaces the counts + * when {@code useStatistics} is set (lines 69 and 104), and implements the {@code + * StoredStatisticsSource} of its engine (line 37). Two do: + * + *
    + *
  • {@code Trino}: {@code profiler_class=TrinoProfilerInterface}, {@code + * ingestion/source/database/trino/service_spec.py:18}, declared at {@code + * profiler/interface/sqlalchemy/trino/profiler_interface.py:37}. {@code distinctCount} is + * {@code SHOW STATS} {@code distinct_values_count} ({@code + * ingestion/source/database/trino/profiler/system_tables_profiler.py:80}) and {@code + * nullCount} is {@code int(row_count * nulls_fraction)} (lines 166-168); + *
  • {@code StarRocks}: {@code profiler_class=StarRocksProfilerInterface}, {@code + * ingestion/source/database/starrocks/service_spec.py:28}, declared at {@code + * profiler/interface/sqlalchemy/starrocks/profiler_interface.py:33}. {@code distinctCount} + * is {@code HLL_CARDINALITY(ndv)}, a HyperLogLog estimate ({@code + * ingestion/source/database/starrocks/profiler/system_tables_profiler.py:82}). + *
+ * + * One connector writes the column profiles itself, from the catalog's statistics: {@code SAS} + * ({@code ingestion/source/database/sas/metadata.py:468-488}). Its {@code missingCount} becomes + * {@code nullCount}, its {@code cardinalityCount} becomes {@code distinctCount}, and the table's + * {@code rowCount} becomes {@code valuesCount}, so {@code valuesCount} counts the null rows. + * + *

No other profiler or sampler computes a distinct, values or null count other than over the + * rows it read: the approximate functions of the dialects are percentiles ({@code + * profiler/orm/functions/median.py}), and a sampled or windowed read is recorded by the profile's + * sample, the table's partition and the profiler configuration, which the rule already reads. + */ + private static final Set PROFILED_FROM_STATISTICS = Set.of("Trino", "StarRocks", "SAS"); + + private static final double WHOLE_PERCENTAGE = 100d; + + private OntologyCountRules() {} + + /** + * False for a table whose service type profiles through a dataframe or from catalog statistics: + * none of the counts of its profiles is exact. + */ + private static boolean countsOverTheRows(final Table table) { + if (table.getServiceType() == null) { + return true; + } + final String serviceType = table.getServiceType().value(); + return !PROFILED_FROM_DATAFRAMES.contains(serviceType) + && !PROFILED_FROM_STATISTICS.contains(serviceType); + } + + private static Set union( + final Set first, final Set second) { + final Set all = EnumSet.copyOf(first); + all.addAll(second); + return Set.copyOf(all); + } + + /** + * The table bindings of one class, as {@link + * org.openmetadata.service.jdbi3.OntologyConceptBindingStore#identityFirstTables} reads them. + * + * @param rows the identity row first when the class has one, then other table rows, hidden and + * deleted tables included + * @param truncated true when {@code rows} may lack a table that the statements of the mapping + * read: a class that is read as {@link #ROWS_PER_CLASS} rows and whose rows hold no + * confirmed join is read again in full, and after that it is truncated only when it binds + * more contributing tables than a statement accepts, so that none is run + */ + record ClassRows(UUID id, List rows, boolean truncated) { + BindingRow identity() { + return rows.stream().filter(OntologyCountRules::isIdentity).findFirst().orElse(null); + } + + /** + * The identity row, then the contributing rows: the rows that can hold a join. A table that + * does not exist holds none. + */ + List holders(final Set deleted) { + return rows.stream() + .filter( + row -> + isIdentity(row) + || row.role() == OntologyBindingRole.CONTRIBUTING + && !deleted.contains(row.assetId())) + .toList(); + } + } + + /** A relation between two classes of a page, from the class that binds it to the one it reaches. */ + record Relation(UUID subject, UUID object, UUID propertyId) {} + + /** + * What the catalog and the profiler store, for the tables the caller may view. + * + * @param tables the live tables the caller may view, by id + * @param profileViewable the ids of the tables whose data profile the caller may view + * @param tableProfiles the latest stored profile of a table, by table id + * @param columnProfiles the latest stored profile of a column, by the column's fully qualified + * name + * @param deleted the ids of the contributing tables that hold a join and do not exist + */ + record Facts( + Map tables, + Set profileViewable, + Map tableProfiles, + Map columnProfiles, + Set deleted) { + Facts( + final Map tables, + final Set profileViewable, + final Map tableProfiles, + final Map columnProfiles) { + this(tables, profileViewable, tableProfiles, columnProfiles, Set.of()); + } + + Facts withDeleted(final Set deleted) { + return new Facts(tables, profileViewable, tableProfiles, columnProfiles, deleted); + } + } + + /** The records of a class, or null when the class binds no table. */ + static NativeOntologyCount records(final ClassRows binding, final Facts facts) { + if (binding.rows().isEmpty()) { + return null; + } + final Source source = source(binding, facts); + if (source.refusal() != null) { + return source.refusal(); + } + return source.row().rowFilter() == null && !nullOrEmpty(source.row().subjectKey()) + ? recordCount(source) + : notDerivable(); + } + + /** + * The links of a relation, or null when the class that binds it binds no table or is not in + * {@code classes}. + */ + static NativeOntologyCount links( + final Relation relation, final Map classes, final Facts facts) { + final Probe probe = probe(relation, classes, facts); + if (probe.settled() != null || probe.lookup() == null) { + return probe.settled(); + } + final ClassRows subject = classes.get(relation.subject()); + return switch (probe.lookup()) { + case Lookup.Missing ignored -> subject.truncated() ? notDerivable() : state(State.NO_JOIN); + case Lookup.Unconfirmed ignored -> subject.truncated() + ? notDerivable() + : state(State.JOIN_NOT_CONFIRMED); + case Lookup.Confirmed found -> linkCount(probe.source(), probe.target(), found.stored()); + }; + } + + /** + * True when the class that binds {@code relation} is cut, so that the rows read hold no + * confirmed join onto the target and the tables left unread could hold one. Its state depends on + * those tables, so the class is read in full before its links are stated. + */ + static boolean needsAFullRead( + final Relation relation, final Map classes, final Facts facts) { + final Probe probe = probe(relation, classes, facts); + return probe.lookup() != null + && classes.get(relation.subject()).truncated() + && !(probe.lookup() instanceof Lookup.Confirmed); + } + + /** + * Everything the links of a relation are decided by before the join is looked up. + * + * @param settled the count that those facts already give, or null when the join decides + * @param lookup what the subject's rows store for the relation, or null when {@code settled} + * decides + */ + private record Probe( + NativeOntologyCount settled, Source source, BindingRow target, Lookup lookup) { + static Probe settled(final NativeOntologyCount count) { + return new Probe(count, null, null, null); + } + } + + private static Probe probe( + final Relation relation, final Map classes, final Facts facts) { + final ClassRows subject = classes.get(relation.subject()); + if (subject == null || subject.rows().isEmpty()) { + return Probe.settled(null); + } + final Source source = source(subject, facts); + if (source.refusal() != null) { + return Probe.settled(source.refusal()); + } + final ClassRows object = classes.get(relation.object()); + final BindingRow target = object == null ? null : object.identity(); + if (object == null || relation.propertyId() == null) { + return Probe.settled(notDerivable()); + } + if (target == null) { + return Probe.settled(state(State.NO_JOIN)); + } + if (!facts.tables().containsKey(target.assetId())) { + return Probe.settled(state(State.IDENTITY_TABLE_HIDDEN)); + } + return new Probe( + null, + source, + target, + OntologyRelationPath.lookup( + relation.propertyId(), subject.holders(facts.deleted()), target.assetId())); + } + + /** The column paths whose profiles a class's counts can read: its key and the children of joins. */ + static List> profiledPaths(final BindingRow identity) { + final List> paths = new ArrayList<>(listOrEmpty(identity.subjectKey())); + for (final OntologyColumnBinding column : listOrEmpty(identity.columns())) { + if (column.getJoin() != null) { + column.getJoin().getOn().stream().map(OntologyJoinColumnPair::getChild).forEach(paths::add); + } + } + return paths; + } + + private static NativeOntologyCount recordCount(final Source source) { + final List> key = source.row().subjectKey(); + if (key.size() == 1) { + final Metrics metrics = source.metrics(key.getFirst()); + return metrics == null || source.distinctIsTransformed(key.getFirst()) + ? notDerivable() + : exact(metrics.distinct(), source); + } + final List metrics = new ArrayList<>(); + for (final List path : key) { + metrics.add(source.metrics(path)); + } + return source.isUnique(key) && metrics.stream().allMatch(Metrics::isComplete) + ? valueOfAtMostOneNullable(metrics, source) + : notDerivable(); + } + + /** The values of the one column that holds nulls, or of any column when none does. */ + private static NativeOntologyCount valueOfAtMostOneNullable( + final List metrics, final Source source) { + final List nullable = metrics.stream().filter(Metrics::hasNulls).toList(); + if (nullable.size() > 1) { + return notDerivable(); + } + return exact((nullable.isEmpty() ? metrics.getFirst() : nullable.getFirst()).values(), source); + } + + private static NativeOntologyCount linkCount( + final Source source, final BindingRow target, final OntologyRelationPath.StoredJoin stored) { + final List> key = source.row().subjectKey(); + final List on = listOrEmpty(stored.join().getOn()); + final boolean joined = + !stored.isLink() + && !on.isEmpty() + && on.stream() + .map(OntologyJoinColumnPair::getParent) + .toList() + .equals(target.subjectKey()); + if (!joined + || source.row().rowFilter() != null + || target.rowFilter() != null + || nullOrEmpty(key) + || !source.isUnique(key) + || !key.stream().allMatch(source::hasNoNulls)) { + return notDerivable(); + } + final List children = new ArrayList<>(); + for (final OntologyJoinColumnPair pair : on) { + children.add(source.metrics(pair.getChild())); + } + return children.stream().allMatch(Metrics::isComplete) + ? valueOfAtMostOneNullable(children, source) + : notDerivable(); + } + + /** The identity table of a class with its profile, or the count that says why there is none. */ + private static Source source(final ClassRows binding, final Facts facts) { + final BindingRow row = binding.identity(); + if (row == null) { + return Source.refused(state(State.NO_IDENTITY_TABLE)); + } + final Table table = facts.tables().get(row.assetId()); + if (table == null) { + return Source.refused(state(State.IDENTITY_TABLE_HIDDEN)); + } + final TableProfile profile = + facts.profileViewable().contains(table.getId()) + ? facts.tableProfiles().get(table.getId()) + : null; + return profile == null + ? Source.refused(state(State.NO_PROFILE)) + : new Source(row, table, profile, facts.columnProfiles(), null); + } + + private static boolean isIdentity(final BindingRow row) { + return row.role() == OntologyBindingRole.IDENTITY; + } + + private static NativeOntologyCount state(final State state) { + return new NativeOntologyCount().withState(state); + } + + private static NativeOntologyCount notDerivable() { + return state(State.NOT_DERIVABLE); + } + + private static NativeOntologyCount exact(final Long value, final Source source) { + return value == null + ? notDerivable() + : state(State.EXACT).withValue(value).withProfiledAt(source.profile().getTimestamp()); + } + + /** A non-negative whole number, or null for anything else. */ + private static Long whole(final Number number) { + if (number == null) { + return null; + } + final double value = number.doubleValue(); + return value >= 0 && value == Math.rint(value) && value < Long.MAX_VALUE ? (long) value : null; + } + + /** + * The metrics of one column, which covered the whole table. + * + * @param values the non-null values + */ + private record Metrics(Long values, Long nulls, Long distinct) { + /** True for metrics that exist and state both the values and the nulls. */ + static boolean isComplete(final Metrics metrics) { + return metrics != null && metrics.values != null && metrics.nulls != null; + } + + boolean hasNulls() { + return nulls > 0; + } + } + + /** + * The identity table of a class and what is stored about it. + * + * @param refusal the count that says why the table gives none, or null when it can give one + */ + private record Source( + BindingRow row, + Table table, + TableProfile profile, + Map columnProfiles, + NativeOntologyCount refusal) { + static Source refused(final NativeOntologyCount refusal) { + return new Source(null, null, null, null, refusal); + } + + /** + * The metrics of the column at {@code path}, or null when they did not cover the table or the + * table's service type gives no exact count. + */ + Metrics metrics(final List path) { + if (!countsOverTheRows(table)) { + return null; + } + final Column column = OntologyBindingRules.resolveColumn(table, path); + final ColumnProfile stored = + column == null || column.getFullyQualifiedName() == null + ? null + : columnProfiles.get(column.getFullyQualifiedName()); + return stored != null && coversWholeTable(stored) + ? new Metrics( + whole(stored.getValuesCount()), + whole(stored.getNullCount()), + whole(stored.getDistinctCount())) + : null; + } + + private boolean coversWholeTable(final ColumnProfile column) { + final var config = table.getTableProfilerConfig(); + final boolean partitionedRead = + !listOrEmpty( + table.getTablePartition() == null ? null : table.getTablePartition().getColumns()) + .isEmpty(); + final boolean queried = config != null && !nullOrEmpty(config.getProfileQuery()); + final boolean windowed = + config != null + && config.getPartitioning() != null + && Boolean.TRUE.equals(config.getPartitioning().getEnablePartitioning()); + return Objects.equals(profile.getTimestamp(), column.getTimestamp()) + && !partitionedRead + && !queried + && !windowed + && readTheWholeTable(column); + } + + /** No sample, a full percentage, or a row cap that the column's rows stay below. */ + private boolean readTheWholeTable(final ColumnProfile column) { + final Number sample = profile.getProfileSample(); + if (sample == null) { + return true; + } + if (profile.getProfileSampleType() == TableProfile.ProfileSampleType.ROWS) { + final Long values = whole(column.getValuesCount()); + final Long nulls = whole(column.getNullCount()); + return values != null && nulls != null && values + nulls < sample.doubleValue(); + } + return sample.doubleValue() >= WHOLE_PERCENTAGE; + } + + /** + * One row per key value. For a key of one column whose metrics covered the table, they decide + * and the catalog is not asked. Otherwise a primary or unique key that the catalog declares on + * some of the key's columns decides, on an engine that checks it. + */ + boolean isUnique(final List> key) { + if (key.size() == 1) { + final Metrics metrics = metrics(key.getFirst()); + if (metrics != null) { + return metrics.values() != null && Objects.equals(metrics.distinct(), metrics.values()); + } + } + return enforcesKeys() && (declaresTableKey(key) || declaresColumnKey(key)); + } + + /** + * No nulls in a key column. When the metrics covered the table they decide. Otherwise the + * column is declared not null, or is part of a primary key on an engine that checks it. + */ + boolean hasNoNulls(final List path) { + final Metrics metrics = metrics(path); + if (metrics != null) { + return metrics.nulls() != null && metrics.nulls() == 0; + } + final Column column = OntologyBindingRules.resolveColumn(table, path); + return column != null + && (column.getConstraint() == ColumnConstraint.NOT_NULL + || enforcesKeys() && inPrimaryKey(column)); + } + + /** The profiler counted this column's distinct values after a transform on this engine. */ + boolean distinctIsTransformed(final List path) { + final Column column = OntologyBindingRules.resolveColumn(table, path); + return column != null + && column.getDataType() != null + && table.getServiceType() != null + && TRANSFORMED_BEFORE_DISTINCT_COUNT + .getOrDefault(table.getServiceType().value(), Set.of()) + .contains(column.getDataType()); + } + + /** + * A declared key decides only on an engine that checks it and whose table gives an exact count. + * No answer reads a declared key of a table that gives none, because {@link #metrics} is null + * there and every count needs metrics, so this refusal holds the line if a type reaches both + * lists. + */ + private boolean enforcesKeys() { + return table.getServiceType() != null + && countsOverTheRows(table) + && ENGINES_THAT_ENFORCE_KEYS.contains(table.getServiceType().value()); + } + + /** A declared primary or unique key whose columns are all in the subject key. */ + private boolean declaresTableKey(final List> key) { + final Set names = topLevelNames(key); + return listOrEmpty(table.getTableConstraints()).stream() + .filter(constraint -> isKey(constraint.getConstraintType())) + .map(TableConstraint::getColumns) + .anyMatch(columns -> !nullOrEmpty(columns) && names.containsAll(columns)); + } + + private boolean declaresColumnKey(final List> key) { + return key.stream() + .map(path -> OntologyBindingRules.resolveColumn(table, path)) + .filter(Objects::nonNull) + .map(Column::getConstraint) + .anyMatch( + constraint -> + constraint == ColumnConstraint.PRIMARY_KEY + || constraint == ColumnConstraint.UNIQUE); + } + + private boolean inPrimaryKey(final Column column) { + return column.getConstraint() == ColumnConstraint.PRIMARY_KEY + || listOrEmpty(table.getTableConstraints()).stream() + .filter( + constraint -> + constraint.getConstraintType() == TableConstraint.ConstraintType.PRIMARY_KEY) + .anyMatch( + constraint -> listOrEmpty(constraint.getColumns()).contains(column.getName())); + } + + private static boolean isKey(final TableConstraint.ConstraintType type) { + return type == TableConstraint.ConstraintType.PRIMARY_KEY + || type == TableConstraint.ConstraintType.UNIQUE; + } + + /** The names of the key's columns that sit at the top of the table, which constraints name. */ + private static Set topLevelNames(final List> key) { + return key.stream() + .filter(path -> path.size() == 1) + .map(List::getFirst) + .collect(Collectors.toSet()); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclaredKeys.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclaredKeys.java new file mode 100644 index 000000000000..c6cde820860b --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclaredKeys.java @@ -0,0 +1,90 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TableConstraint.ConstraintType; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; + +/** + * What the keys that the catalog declares on a table say about the records a binding makes of its + * rows. A declaration is taken at its word, whether the database or a person made it and whether + * or not the engine enforces it (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). A + * primary key is declared by a table constraint, or by the column constraint on the one column + * that carries it. + */ +final class OntologyDeclaredKeys { + private OntologyDeclaredKeys() {} + + /** + * True when the table holds at most one row for each value of its subject key, because a + * declared primary or unique key lies inside the subject key columns. A key with a column + * outside the subject key says nothing: two rows can share the subject key and differ there. + */ + static boolean oneRowPerKey(final MappedTable table) { + final Set key = topLevel(table.keyPaths()); + final List> declared = new ArrayList<>(primaryKeys(table.table())); + declared.addAll(uniqueKeys(table.table())); + return declared.stream().anyMatch(columns -> !columns.isEmpty() && key.containsAll(columns)); + } + + /** The names of the key's columns that sit at the top of the table, which constraints name. */ + private static Set topLevel(final List> key) { + return key.stream() + .filter(path -> path.size() == 1) + .map(List::getFirst) + .collect(Collectors.toSet()); + } + + private static List> primaryKeys(final Table table) { + final List> keys = new ArrayList<>(tableKeys(table, ConstraintType.PRIMARY_KEY)); + final Set flagged = flagged(table, ColumnConstraint.PRIMARY_KEY); + // Several columns that each carry the constraint are a key of unknown shape, so only one + // counts. + if (flagged.size() == 1) { + keys.add(flagged); + } + return keys; + } + + private static List> uniqueKeys(final Table table) { + final List> keys = new ArrayList<>(tableKeys(table, ConstraintType.UNIQUE)); + flagged(table, ColumnConstraint.UNIQUE).forEach(column -> keys.add(Set.of(column))); + return keys; + } + + private static List> tableKeys(final Table table, final ConstraintType type) { + return listOrEmpty(table.getTableConstraints()).stream() + .filter(constraint -> constraint.getConstraintType() == type) + .map(TableConstraint::getColumns) + .map(columns -> Set.copyOf(listOrEmpty(columns))) + .toList(); + } + + private static Set flagged(final Table table, final ColumnConstraint constraint) { + return listOrEmpty(table.getColumns()).stream() + .filter(column -> column.getConstraint() == constraint) + .map(Column::getName) + .collect(Collectors.toSet()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitions.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitions.java new file mode 100644 index 000000000000..7f2e9e314913 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitions.java @@ -0,0 +1,275 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import com.google.common.collect.Lists; +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.commons.codec.digest.DigestUtils; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.entity.data.OntologyAxiom; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyDeclinedDefinition; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionMatch; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionMatches; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionPage; +import org.openmetadata.service.jdbi3.OntologyDeclinedDefinitionDAO; +import org.openmetadata.service.jdbi3.OntologyDeclinedDefinitionDAO.StoredDeclinedDefinition; + +/** + * The record of definitions a person declined. A generator reads it to leave out what was declined + * before, and it matches on the operation type, the IRI and the content digest, so a definition + * that changed is proposed again. + */ +public final class OntologyDeclinedDefinitions { + private static final int LOOKUP_BATCH = 500; + private static final char CURSOR_SEPARATOR = '|'; + + private final OntologyDeclinedDefinitionDAO dao; + private final Clock clock; + + public OntologyDeclinedDefinitions(final OntologyDeclinedDefinitionDAO dao, final Clock clock) { + this.dao = dao; + this.clock = clock; + } + + /** The identity of one declinable definition. */ + record Key(OntologyChangeOperationType type, URI iri, String payloadDigest) { + String iriHash() { + return DigestUtils.sha256Hex(iri.toString()); + } + } + + /** The key of the definition the operation carries, or null when it carries none. */ + static Key keyOf(final OntologyChangeOperation operation) { + return switch (operation.getOperationType()) { + case UPSERT_BINDING -> bindingKey(operation); + case UPSERT_SHAPE -> shapeKey(operation); + default -> definitionKey(operation); + }; + } + + private static Key definitionKey(final OntologyChangeOperation operation) { + final OntologyDefinition definition = NativeOntologyChanges.definition(operation); + final URI iri = iriOf(definition); + return iri == null + ? null + : new Key(operation.getOperationType(), iri, OntologyDefinitionDigest.of(definition)); + } + + /** A binding stands under its class, and its digest covers the table, role, keys and columns. */ + private static Key bindingKey(final OntologyChangeOperation operation) { + final OntologyBindingChange binding = operation.getBinding(); + return binding == null || binding.getClassIri() == null + ? null + : new Key( + operation.getOperationType(), + binding.getClassIri(), + OntologyDefinitionDigest.ofBinding(binding)); + } + + /** A shape stands under its target class, and its digest covers its constraints. */ + private static Key shapeKey(final OntologyChangeOperation operation) { + final OntologyShape shape = operation.getShape(); + return shape == null || shape.getTargetConcept() == null + ? null + : new Key( + operation.getOperationType(), + shape.getTargetConcept(), + OntologyDefinitionDigest.ofShapeConstraints(shape)); + } + + /** + * An axiom has no IRI of its own, so its subject stands in. Several axioms of one subject differ + * by digest. + */ + private static URI iriOf(final OntologyDefinition definition) { + return definition == null + ? null + : switch (definition) { + case OntologyConcept concept -> concept.getIri(); + case OntologyProperty property -> property.getIri(); + case OntologyAxiom axiom -> axiom.getSubjectIri(); + default -> null; + }; + } + + /** + * Records the definitions of these operations as declined. An operation already declined keeps + * its first record, so declining twice changes nothing. The result holds the record of every + * named operation, in the order named. + */ + public OntologyDeclinedDefinitionPage decline( + final OntologyChangeSet changeSet, + final Collection operationIds, + final String reason, + final String user) { + final UUID ontologyId = changeSet.getOntology().getId(); + final Map stored = + listOrEmpty(changeSet.getOperations()).stream() + .collect(Collectors.toMap(OntologyChangeOperation::getId, operation -> operation)); + final Map keys = new LinkedHashMap<>(); + for (final UUID operationId : operationIds) { + keys.put(operationId, declinableKey(changeSet, stored.get(operationId), operationId)); + } + final long declinedAt = clock.millis(); + keys.forEach( + (operationId, key) -> + dao.insertIfAbsent( + new StoredDeclinedDefinition( + ontologyId.toString(), + key.type().value(), + key.iri().toString(), + key.iriHash(), + key.payloadDigest(), + user, + declinedAt, + reason, + changeSet.getId().toString(), + operationId.toString()))); + final Map records = + recordsByKey(ontologyId, List.copyOf(keys.values())); + return new OntologyDeclinedDefinitionPage() + .withRecords(keys.values().stream().map(records::get).toList()); + } + + private static Key declinableKey( + final OntologyChangeSet changeSet, + final OntologyChangeOperation operation, + final UUID operationId) { + if (operation == null) { + throw new BadRequestException( + "Operation '" + operationId + "' is not part of change set '" + changeSet.getId() + "'"); + } + final Key key = keyOf(operation); + if (key == null) { + throw new BadRequestException( + "Operation '" + operationId + "' carries no definition that can be declined"); + } + return key; + } + + /** For each candidate, in order, the record that matches its type, IRI and digest, if any. */ + public OntologyDeclinedDefinitionMatches match( + final UUID ontologyId, final List candidates) { + final List keys = candidates.stream().map(OntologyDeclinedDefinitions::keyOf).toList(); + final Map records = + recordsByKey(ontologyId, keys.stream().filter(java.util.Objects::nonNull).toList()); + final List matches = new ArrayList<>(); + for (int index = 0; index < candidates.size(); index++) { + matches.add(matchOf(candidates.get(index), keys.get(index), records)); + } + return new OntologyDeclinedDefinitionMatches().withMatches(matches); + } + + private static OntologyDeclinedDefinitionMatch matchOf( + final OntologyChangeOperation candidate, + final Key key, + final Map records) { + final OntologyDeclinedDefinition record = key == null ? null : records.get(key); + return new OntologyDeclinedDefinitionMatch() + .withOperationId(candidate.getId()) + .withOperationType(candidate.getOperationType()) + .withIri(key == null ? null : key.iri()) + .withPayloadDigest(key == null ? null : key.payloadDigest()) + .withDeclined(record != null) + .withRecord(record); + } + + private Map recordsByKey( + final UUID ontologyId, final List keys) { + final Set hashes = keys.stream().map(Key::iriHash).collect(Collectors.toSet()); + final Map found = new HashMap<>(); + Lists.partition(List.copyOf(hashes), LOOKUP_BATCH) + .forEach( + batch -> + dao.findByIriHashes(ontologyId.toString(), batch) + .forEach( + record -> + found.put( + new Key( + record.getOperationType(), + record.getIri(), + record.getPayloadDigest()), + record))); + return found; + } + + /** One page of records in the order they were declined; {@code after} comes from a page. */ + public OntologyDeclinedDefinitionPage list( + final UUID ontologyId, final int limit, final String after) { + final String[] position = after == null ? null : decodeCursor(after); + final List rows = + dao.listAfter( + ontologyId.toString(), + position != null, + position == null ? 0L : Long.parseLong(position[0]), + position == null ? "" : position[1], + position == null ? "" : position[2], + position == null ? "" : position[3], + limit + 1); + final List page = rows.subList(0, Math.min(limit, rows.size())); + return new OntologyDeclinedDefinitionPage() + .withRecords(List.copyOf(page)) + .withAfter(rows.size() > limit ? encodeCursor(page.get(page.size() - 1)) : null); + } + + private static String encodeCursor(final OntologyDeclinedDefinition last) { + final String position = + String.join( + String.valueOf(CURSOR_SEPARATOR), + String.valueOf(last.getDeclinedAt()), + last.getOperationType().value(), + DigestUtils.sha256Hex(last.getIri().toString()), + last.getPayloadDigest()); + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(position.getBytes(StandardCharsets.UTF_8)); + } + + private static String[] decodeCursor(final String cursor) { + try { + final String[] parts = + new String(Base64.getUrlDecoder().decode(cursor), StandardCharsets.UTF_8) + .split("\\" + CURSOR_SEPARATOR, -1); + Long.parseLong(parts[0]); + if (parts.length == 4) { + return parts; + } + } catch (IllegalArgumentException | ArrayIndexOutOfBoundsException exception) { + // Falls through to the refusal below. + } + throw new BadRequestException("The after cursor is not one this endpoint returned"); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java new file mode 100644 index 000000000000..4192f2545e6a --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDefinitionDigest.java @@ -0,0 +1,220 @@ +/* + * 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.ontology; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.StreamSupport; +import org.apache.commons.codec.digest.DigestUtils; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.entity.data.OntologyAxiom; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.utils.JsonUtils; + +/** + * The content digest of a definition, as a declined-definition record keys it. + * + *

The digest is the SHA-256 of the definition's canonical JSON, which {@link #canonicalJson} + * builds in these steps: + * + *

    + *
  1. The definition is written to JSON and read back into its own class, the round trip a stored + * draft takes. A field sent as {@code null} and a field left out both end as the schema's + * default. + *
  2. The fields in {@link #DROPPED_FIELDS} are removed: the ones a tool or the server sets afresh + * on every run, and the ones the schema marks read only. + *
  3. The {@code ontology} reference and each owner are reduced to their id and type. + *
  4. Null fields and empty arrays are removed at every depth. + *
  5. Object keys are sorted, numbers lose their trailing zeros, and each array the schema marks + * as a set ({@code uniqueItems}) is sorted by the text of its elements and stripped of + * duplicates. + *
  6. The result is written as compact JSON in UTF-8 and hashed. + *
+ */ +public final class OntologyDefinitionDigest { + /** + * The fields that leave the canonical form. The first seven are set by the tool that proposes the + * definition or by the server on every write. The last three the schema marks {@code readOnly} + * and derives from other rows ({@code superClasses} and {@code subClasses} from the subclass + * axioms, {@code lifecycleStatus} from the ontology's releases). + */ + static final Set DROPPED_FIELDS = + Set.of( + "id", + "version", + "updatedAt", + "updatedBy", + "href", + "changeDescription", + "incrementalChangeDescription", + "impersonatedBy", + "lifecycleStatus", + "superClasses", + "subClasses"); + + private static final List BINDING_KEY_FIELDS = + List.of("tableId", "role", "subjectKey", "rowFilter"); + private static final String SCHEMA_FOLDER = "/json/schema/entity/data/"; + private static final Map, String> SCHEMAS = + Map.of( + OntologyConcept.class, "ontologyConcept.json", + OntologyProperty.class, "ontologyProperty.json", + OntologyAxiom.class, "ontologyAxiom.json"); + private static final Map, Set> SET_FIELDS = new ConcurrentHashMap<>(); + + private OntologyDefinitionDigest() {} + + public static String of(final OntologyDefinition definition) { + return DigestUtils.sha256Hex(canonicalJson(definition)); + } + + /** + * The digest of a table binding, which a record keys by what a reviewer rejects: the table, the + * role, the subject key and the row filter. The class stays out, because a record keeps it as its + * IRI, and so do the columns and their joins, so a binding that maps fewer columns is the same + * declined binding. The subject key keeps its order, because a contributing table pairs its key + * with the identity table's by position. + */ + public static String ofBinding(final OntologyBindingChange binding) { + final JsonNode tree = + JsonUtils.valueToTree( + JsonUtils.readValue(JsonUtils.pojoToJson(binding), OntologyBindingChange.class)); + final ObjectNode content = JsonUtils.getObjectNode(); + BINDING_KEY_FIELDS.stream() + .filter(tree::has) + .forEach(field -> content.set(field, tree.get(field).deepCopy())); + return DigestUtils.sha256Hex(OntologyJson.canonical(withoutEmpty(content)).toString()); + } + + /** The digest of a shape's constraints, in the order they were authored. */ + public static String ofShapeConstraints(final OntologyShape shape) { + final JsonNode tree = + JsonUtils.valueToTree( + JsonUtils.readValue(JsonUtils.pojoToJson(shape), OntologyShape.class)); + final ObjectNode content = JsonUtils.getObjectNode(); + content.set("constraints", tree.path("constraints").deepCopy()); + return DigestUtils.sha256Hex(OntologyJson.canonical(withoutEmpty(content)).toString()); + } + + static String canonicalJson(final OntologyDefinition definition) { + final JsonNode tree = + JsonUtils.valueToTree( + JsonUtils.readValue(JsonUtils.pojoToJson(definition), definition.getClass())); + final ObjectNode content = tree.deepCopy(); + DROPPED_FIELDS.forEach(content::remove); + reduceReferences(content); + final JsonNode canonical = OntologyJson.canonical(withoutEmpty(content)); + setFieldsOf(definition.getClass()).forEach(field -> sortAsSet(canonical, field)); + return canonical.toString(); + } + + /** The names of the arrays that the definition's schema marks {@code uniqueItems}. */ + static Set setFieldsOf(final Class definitionClass) { + return SET_FIELDS.computeIfAbsent(definitionClass, OntologyDefinitionDigest::readSetFields); + } + + private static Set readSetFields(final Class definitionClass) { + final String schema = SCHEMAS.get(definitionClass); + final Set fields = new TreeSet<>(); + if (schema == null) { + return fields; + } + try (InputStream stream = + OntologyDefinitionDigest.class.getResourceAsStream(SCHEMA_FOLDER + schema)) { + if (stream == null) { + throw new IllegalStateException("Schema " + SCHEMA_FOLDER + schema + " is not packaged"); + } + final JsonNode properties = + JsonUtils.readTree(new String(stream.readAllBytes(), StandardCharsets.UTF_8)) + .get("properties"); + properties + .properties() + .forEach( + property -> { + if (property.getValue().path("uniqueItems").asBoolean(false)) { + fields.add(property.getKey()); + } + }); + return fields; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static void reduceReferences(final ObjectNode content) { + if (content.path("ontology").isObject()) { + content.set("ontology", idAndType(content.get("ontology"))); + } + if (content.path("owners").isArray()) { + final ArrayNode owners = JsonUtils.getObjectMapper().createArrayNode(); + content.get("owners").forEach(owner -> owners.add(idAndType(owner))); + content.set("owners", owners); + } + } + + private static ObjectNode idAndType(final JsonNode reference) { + final ObjectNode reduced = JsonUtils.getObjectNode(); + reduced.set("id", reference.get("id")); + reduced.set("type", reference.get("type")); + return reduced; + } + + private static JsonNode withoutEmpty(final JsonNode value) { + if (value instanceof ObjectNode object) { + final ObjectNode kept = JsonUtils.getObjectNode(); + object + .properties() + .forEach( + entry -> { + final JsonNode child = withoutEmpty(entry.getValue()); + if (!child.isNull() && !(child.isArray() && child.isEmpty())) { + kept.set(entry.getKey(), child); + } + }); + return kept; + } + if (value.isArray()) { + final ArrayNode items = JsonUtils.getObjectMapper().createArrayNode(); + value.forEach(item -> items.add(withoutEmpty(item))); + return items; + } + return value; + } + + private static void sortAsSet(final JsonNode canonical, final String field) { + if (canonical.get(field) instanceof ArrayNode array) { + final List ordered = + StreamSupport.stream(array.spliterator(), false) + .sorted(Comparator.comparing(JsonNode::toString)) + .distinct() + .toList(); + ((ObjectNode) canonical) + .set(field, JsonUtils.getObjectMapper().createArrayNode().addAll(ordered)); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftNarrowing.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftNarrowing.java new file mode 100644 index 000000000000..68eb3d56764e --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftNarrowing.java @@ -0,0 +1,123 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Predicate; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.service.ontology.OntologyChangePreflight.DeclaredConcepts; + +/** + * Refuses a replacement of a draft's operations that leaves an operation needing a class that only + * a removed operation of the same draft creates. Such a set cannot apply, and applying is the + * first time it would otherwise say so. + */ +public final class OntologyDraftNarrowing { + private static final String REMOVED_HEAD = + "Ontology operations need classes that only removed operations create: "; + private static final String REMOVED_TAIL = + ". Keep the operation that creates each class, or remove the operations that need it."; + private static final String UNDONE_HEAD = + "Ontology operations need classes that only kept operations past the undo cursor create: "; + private static final String UNDONE_TAIL = + ". Move the undo cursor past the operation that creates each class, or remove the operations" + + " that need it."; + + private OntologyDraftNarrowing() {} + + /** + * Refuses a replacement in which a kept operation needs a class that a redo or an apply of the + * kept operations would not have created before it. The operation at index {@code i} is active + * together with {@code kept[0 .. max(i + 1, cursor))}, whatever the cursor is now, because a redo + * moves the cursor forward one operation at a time. A class the operations before it do not + * create makes the draft fail at apply when a stored operation created it: when it is created by + * no kept operation, the removed one is to blame, and when a kept operation past the cursor + * creates it, the cursor is. + * + * @param replaced the draft with the operations and cursor that replace the stored ones + * @param stored the operations the draft held before the replacement + */ + public static void requireNoLostClasses( + final OntologyChangeSet replaced, + final List stored, + final DeclaredConcepts declaredConcepts) { + if (replaced.getOntology() == null) { + return; + } + final List kept = listOrEmpty(replaced.getOperations()); + final Set storedCreations = OntologyChangePreflight.createdConceptIris(stored); + final Map firstCreation = firstCreations(kept); + final Set removed = new TreeSet<>(); + final Set undone = new TreeSet<>(); + final Map> dataPropertiesBefore = new HashMap<>(); + for (int index = 0; index < kept.size(); index++) { + final int reachable = Math.max(index + 1, replaced.getUndoCursor()); + final var isDataProperty = + dataPropertiesBefore.computeIfAbsent( + reachable, end -> OntologyChangePreflight.dataProperties(kept.subList(0, end))); + for (final String needed : + OntologyChangePreflight.neededClassIris(kept.get(index), isDataProperty)) { + final Integer created = firstCreation.get(needed); + if (storedCreations.contains(needed) && (created == null || created >= reachable)) { + (created == null ? removed : undone).add(needed); + } + } + } + final Set lost = new TreeSet<>(removed); + lost.addAll(undone); + if (lost.isEmpty()) { + return; + } + final Set declared = declaredConcepts.declared(replaced.getOntology().getId(), lost); + removed.removeAll(declared); + undone.removeAll(declared); + if (!removed.isEmpty() || !undone.isEmpty()) { + throw new BadRequestException(refusal(removed, undone)); + } + } + + private static String refusal(final Set removed, final Set undone) { + final List sentences = new ArrayList<>(); + if (!removed.isEmpty()) { + sentences.add(REMOVED_HEAD + String.join(", ", removed) + REMOVED_TAIL); + } + if (!undone.isEmpty()) { + sentences.add(UNDONE_HEAD + String.join(", ", undone) + UNDONE_TAIL); + } + return String.join(" ", sentences); + } + + private static Map firstCreations(final List kept) { + final Map first = new HashMap<>(); + for (int index = 0; index < kept.size(); index++) { + final OntologyChangeOperation operation = kept.get(index); + if (operation.getOperationType() == OntologyChangeOperationType.UPSERT_CONCEPT + && operation.getConcept() != null) { + first.putIfAbsent(operation.getConcept().getIri().toString(), index); + } + } + return first; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftPreflight.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftPreflight.java new file mode 100644 index 000000000000..65c2389f8d26 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyDraftPreflight.java @@ -0,0 +1,272 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import com.google.common.collect.Lists; +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyColumnBindingChange; +import org.openmetadata.schema.type.OntologyJoinChange; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.rdf.OwlEntityDeclarations; + +/** + * What the binding and shape operations of a draft must satisfy when the draft is saved: the class + * and properties each one names exist in the ontology or are created by an earlier operation, and + * the table and columns a binding names exist in the catalog. It reads stored state only and asks + * nothing about the caller, whose rights are checked when the draft is applied. + */ +public final class OntologyDraftPreflight { + private static final int DECLARATION_BATCH = 500; + private static final String CLASS = "class"; + private static final String PROPERTY = "property"; + + private final Declarations declarations; + private final TableLoader tables; + + /** The subset of these IRIs that the live classes, or properties, of an ontology declare. */ + public interface Declarations { + Set classes(UUID ontologyId, Set iris); + + Set properties(UUID ontologyId, Set iris); + } + + /** The live table with its columns, or null when the catalog holds none with this id. */ + @FunctionalInterface + public interface TableLoader { + Table load(UUID id); + } + + public OntologyDraftPreflight(final Declarations declarations, final TableLoader tables) { + this.declarations = declarations; + this.tables = tables; + } + + /** Reads the ontology and the catalog as they are stored. */ + public static OntologyDraftPreflight production() { + return new OntologyDraftPreflight( + new StoredDeclarations(), + id -> Entity.getEntityOrNull(Entity.TABLE, id, Entity.FIELD_COLUMNS, Include.NON_DELETED)); + } + + public void validate(final UUID ontologyId, final List operations) { + requireDeclared(ontologyId, listOrEmpty(operations)); + final Map> loaded = new HashMap<>(); + listOrEmpty(operations).stream() + .filter(OntologyBindingChanges::isBinding) + .forEach(operation -> requireResolved(operation, loaded)); + } + + /** One class or property an operation needs before it can be applied. */ + private record Need(OntologyChangeOperation operation, String kind, String iri) {} + + /** + * Walks the draft in order, so a need is met only by an operation that comes before it. What no + * earlier operation creates is then looked up in the ontology, each kind in one read. + */ + private void requireDeclared( + final UUID ontologyId, final List operations) { + final Map> created = + Map.of(CLASS, new HashSet<>(), PROPERTY, new HashSet<>()); + final List pending = new ArrayList<>(); + for (final OntologyChangeOperation operation : operations) { + needs(operation) + .filter(need -> !created.get(need.kind()).contains(need.iri())) + .forEach(pending::add); + rememberCreated(operation, created); + } + final Map> declared = + Map.of( + CLASS, declarations.classes(ontologyId, iris(pending, CLASS)), + PROPERTY, declarations.properties(ontologyId, iris(pending, PROPERTY))); + pending.stream() + .filter(need -> !declared.get(need.kind()).contains(need.iri())) + .findFirst() + .ifPresent(OntologyDraftPreflight::refuse); + } + + private static void refuse(final Need need) { + throw new BadRequestException( + "Ontology operation '" + + need.operation().getId() + + "' needs the " + + need.kind() + + " " + + need.iri() + + ", which the ontology does not declare and no earlier operation creates"); + } + + private static Set iris(final List needs, final String kind) { + return needs.stream() + .filter(need -> kind.equals(need.kind())) + .map(Need::iri) + .collect(Collectors.toSet()); + } + + /** + * A binding is a row of its class, so that class is always needed. A shape may target a + * vocabulary class, which no ontology declares, as any concept an operation lists may be one. + */ + private static Stream needs(final OntologyChangeOperation operation) { + final Stream listed = listOrEmpty(operation.getRequiresConceptIris()).stream(); + return switch (operation.getOperationType()) { + case UPSERT_BINDING -> Stream.of( + Stream.of( + new Need(operation, CLASS, operation.getBinding().getClassIri().toString())), + declarable(operation, listed), + OntologyBindingChanges.propertyIris(operation.getBinding()).stream() + .map(iri -> new Need(operation, PROPERTY, iri.toString()))) + .flatMap(Function.identity()); + case UPSERT_SHAPE -> declarable( + operation, Stream.concat(Stream.of(operation.getShape().getTargetConcept()), listed)); + default -> Stream.empty(); + }; + } + + /** The classes among these that an ontology has to declare, as when a draft is applied. */ + private static Stream declarable( + final OntologyChangeOperation operation, final Stream iris) { + return iris.map(URI::toString) + .filter( + iri -> + !OntologyClassHierarchy.isVocabularyClass(iri) + && !OwlEntityDeclarations.isDatatype(iri)) + .map(iri -> new Need(operation, CLASS, iri)); + } + + private static void rememberCreated( + final OntologyChangeOperation operation, final Map> created) { + if (operation.getOperationType() == OntologyChangeOperationType.UPSERT_CONCEPT + && operation.getConcept() != null + && operation.getConcept().getIri() != null) { + created.get(CLASS).add(operation.getConcept().getIri().toString()); + } + if (operation.getOperationType() == OntologyChangeOperationType.UPSERT_PROPERTY + && operation.getProperty() != null + && operation.getProperty().getIri() != null) { + created.get(PROPERTY).add(operation.getProperty().getIri().toString()); + } + } + + private void requireResolved( + final OntologyChangeOperation operation, final Map> loaded) { + final OntologyBindingChange change = operation.getBinding(); + final Table table = requireTable(operation, change.getTableId(), "table", loaded); + ownColumns(change).forEach(path -> requireColumn(operation, table, path)); + for (final OntologyJoinChange join : joins(change)) { + final Table target = + requireTable(operation, join.getTargetAssetId(), "join target table", loaded); + for (final OntologyJoinColumnPair pair : join.getOn()) { + requireColumn(operation, table, pair.getChild()); + requireColumn(operation, target, pair.getParent()); + } + } + } + + /** The columns of the bound table that the binding names outside its joins. */ + private static List> ownColumns(final OntologyBindingChange change) { + final List> paths = new ArrayList<>(listOrEmpty(change.getSubjectKey())); + if (change.getRowFilter() != null) { + paths.add(change.getRowFilter().getColumn()); + } + listOrEmpty(change.getColumns()).stream() + .map(OntologyColumnBindingChange::getColumnPath) + .forEach(paths::add); + return paths; + } + + private static List joins(final OntologyBindingChange change) { + return listOrEmpty(change.getColumns()).stream() + .map(OntologyColumnBindingChange::getJoin) + .filter(Objects::nonNull) + .toList(); + } + + private Table requireTable( + final OntologyChangeOperation operation, + final UUID id, + final String role, + final Map> loaded) { + return loaded + .computeIfAbsent(id, missing -> Optional.ofNullable(tables.load(missing))) + .orElseThrow( + () -> + new BadRequestException( + "Ontology operation '" + + operation.getId() + + "' names the " + + role + + " " + + id + + ", which does not exist")); + } + + private static void requireColumn( + final OntologyChangeOperation operation, final Table table, final List path) { + if (OntologyBindingRules.resolveColumn(table, path) == null) { + throw new BadRequestException( + "Ontology operation '" + + operation.getId() + + "' names the column " + + String.join(".", path) + + ", which table " + + table.getId() + + " does not have"); + } + } + + /** The declarations as the ontology stores them, read in batches the database accepts. */ + private static final class StoredDeclarations implements Declarations { + @Override + public Set classes(final UUID ontologyId, final Set iris) { + return OntologyChangeApplicationService.declaredConcepts(ontologyId, iris); + } + + @Override + public Set properties(final UUID ontologyId, final Set iris) { + final OntologyConceptBindingStore store = + new OntologyConceptBindingStore( + Entity.getCollectionDAO(), OntologyConceptBindingStore.registeredAssetTables()); + final Set declared = new HashSet<>(); + Lists.partition(iris.stream().map(URI::create).toList(), DECLARATION_BATCH) + .forEach( + batch -> + store + .liveProperties(ontologyId, batch) + .forEach(property -> declared.add(property.getIri().toString()))); + return declared; + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyHeldDatatypes.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyHeldDatatypes.java new file mode 100644 index 000000000000..599c7f59d524 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyHeldDatatypes.java @@ -0,0 +1,138 @@ +/* + * 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.ontology; + +import static java.util.Map.entry; + +import java.net.URI; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; + +/** + * The column types that store nothing but values of a datatype, by engine family + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). The catalog gives one name to types + * that differ between engines, so a line names the families on which every type of that name was + * read. A column of a service type with no family is held for no datatype. + * + *

The lines that are missing are missing on purpose. A fixed-point column of Postgres stores + * {@code NaN}, and its dates and timestamps store {@code infinity}. The MySQL family stores a + * boolean as a number from -128 to 127, a time of {@code 25:00:00} and the zero date. A {@code + * TIMESTAMP} column of SQL Server is a row version. The Databricks source reads a {@code decimal} + * column as a type that the catalog names {@code INT}. A {@code FLOAT} column has 32 bits on one + * engine and 64 on another, so it can hold a number that no {@code xsd:float} is. {@code DOUBLE} + * also names a decimal floating-point type. Every text type stores control characters that {@code + * xsd:string} leaves out. + */ +final class OntologyHeldDatatypes { + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + + private static final Set EVERY_FAMILY = EnumSet.allOf(SqlEngineFamily.class); + private static final Set WITH_A_BOOLEAN_TYPE = + EnumSet.complementOf(EnumSet.of(SqlEngineFamily.MYSQL, SqlEngineFamily.TSQL)); + private static final Set WITH_FINITE_FIXED_POINT = + EnumSet.complementOf(EnumSet.of(SqlEngineFamily.POSTGRES)); + private static final Set WITH_INT_FOR_WHOLE_NUMBERS_ONLY = + EnumSet.complementOf(EnumSet.of(SqlEngineFamily.SPARK)); + private static final Set WITH_CALENDAR_VALUES_ONLY = + EnumSet.of(SqlEngineFamily.BIGQUERY, SqlEngineFamily.TSQL); + + private static final Map> HOLDS_ONLY = + Map.ofEntries( + entry(XSD + "boolean", List.of(held(WITH_A_BOOLEAN_TYPE, ColumnDataType.BOOLEAN))), + entry( + XSD + "integer", + List.of( + held( + EVERY_FAMILY, + ColumnDataType.TINYINT, + ColumnDataType.BYTEINT, + ColumnDataType.SMALLINT, + ColumnDataType.BIGINT, + ColumnDataType.LARGEINT), + held(WITH_INT_FOR_WHOLE_NUMBERS_ONLY, ColumnDataType.INT), + withNoFraction( + WITH_FINITE_FIXED_POINT, ColumnDataType.DECIMAL, ColumnDataType.NUMERIC))), + entry( + XSD + "decimal", + List.of( + held( + EVERY_FAMILY, + ColumnDataType.TINYINT, + ColumnDataType.BYTEINT, + ColumnDataType.SMALLINT, + ColumnDataType.INT, + ColumnDataType.BIGINT, + ColumnDataType.LARGEINT), + held(WITH_FINITE_FIXED_POINT, ColumnDataType.DECIMAL, ColumnDataType.NUMERIC))), + entry(XSD + "double", List.of(held(EVERY_FAMILY, ColumnDataType.FLOAT))), + entry(XSD + "float", List.of()), + entry(XSD + "string", List.of()), + entry(XSD + "date", List.of(held(WITH_CALENDAR_VALUES_ONLY, ColumnDataType.DATE))), + entry(XSD + "time", List.of(held(WITH_CALENDAR_VALUES_ONLY, ColumnDataType.TIME))), + entry( + XSD + "dateTime", + List.of( + held(WITH_CALENDAR_VALUES_ONLY, ColumnDataType.DATETIME), + held(EnumSet.of(SqlEngineFamily.BIGQUERY), ColumnDataType.TIMESTAMP)))); + + private OntologyHeldDatatypes() {} + + /** + * One line of the table: on each of {@code families}, a column of one of {@code types} stores + * nothing but values of the datatype. + * + * @param noFraction true when that is so only for a column with a scale of zero + */ + private record Held( + Set families, Set types, boolean noFraction) { + boolean covers(final SqlEngineFamily family, final Column column) { + final boolean whole = column.getScale() != null && column.getScale() == 0; + return families.contains(family) + && types.contains(column.getDataType()) + && (!noFraction || whole); + } + } + + private static Held held( + final Set families, + final ColumnDataType first, + final ColumnDataType... rest) { + return new Held(families, EnumSet.of(first, rest), false); + } + + private static Held withNoFraction( + final Set families, + final ColumnDataType first, + final ColumnDataType... rest) { + return new Held(families, EnumSet.of(first, rest), true); + } + + /** True when the table has lines for the datatype, which may be none. */ + static boolean reads(final URI datatype) { + return HOLDS_ONLY.containsKey(datatype.toString()); + } + + /** True when every value that a column of a service of the type stores is of the datatype. */ + static boolean holdsOnly(final String serviceType, final URI datatype, final Column column) { + final List lines = HOLDS_ONLY.getOrDefault(datatype.toString(), List.of()); + return SqlEngineFamily.forServiceType(serviceType) + .filter(family -> lines.stream().anyMatch(line -> line.covers(family, column))) + .isPresent(); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyHopJoins.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyHopJoins.java new file mode 100644 index 000000000000..c055c02b2ecc --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyHopJoins.java @@ -0,0 +1,284 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.BoundConcept; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.BoundTable; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.Hop; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * Finds the join of each search-around hop from the foreign keys and the object-property bindings + * of the tables on both sides (ADR:2026-10-21-ontology-live-data-execution-is-a-collate-extension). + * It reads no database and writes no statement text. + */ +final class OntologyHopJoins { + private OntologyHopJoins() {} + + record ColumnPair(List left, List right) {} + + record Join(BoundTable table, List on) {} + + private record Step(int position, Hop hop, BoundTable previous) { + BadRequestException failure(final String reason, final Object... args) { + return new BadRequestException( + String.format("Hop %d (%s)", position, hop.label()) + String.format(reason, args)); + } + } + + static List joins(final BoundTable first, final List hops) { + final List joins = new ArrayList<>(); + BoundTable previous = first; + for (int index = 0; index < hops.size(); index++) { + final Join join = + join( + new Step(index + 1, hops.get(index), previous), + OntologyConceptSqlGenerator.fqnParts(first.fullyQualifiedName(), 2)); + joins.add(join); + previous = join.table(); + } + return joins; + } + + /** + * A bound hop property follows its binding: through a foreign key on the bound column, else to + * the other table's identifier. An unbound one whose declared inverse is bound takes the + * converse of the join a hop over the inverse would take back. Otherwise it follows the one + * foreign key between the tables. + */ + private static Join join(final Step step, final List database) { + final List candidates = + candidates(step).stream() + .filter( + table -> + database.equals( + OntologyConceptSqlGenerator.fqnParts(table.fullyQualifiedName(), 2))) + .toList(); + final BoundTable previous = step.previous(); + final UUID property = step.hop().property(); + final Optional boundInverse = + step.hop().otherInverse().filter(inverse -> isBound(previous, candidates, inverse)); + final Optional join; + if (isBound(previous, candidates, property)) { + join = bindingJoin(step, candidates, property, false); + } else if (boundInverse.isPresent()) { + join = bindingJoin(step, candidates, boundInverse.get(), true); + } else { + join = firstJoin(candidates, table -> onlyKeyPairs(step, table)); + } + return join.orElseThrow( + () -> + step.failure( + ": no foreign key or object-property binding joins %s to a table bound to %s", + step.previous().fullyQualifiedName(), step.hop().target().label())); + } + + private static List candidates(final Step step) { + final BoundConcept target = step.hop().target(); + if (listOrEmpty(target.tables()).isEmpty()) { + throw step.failure( + " reaches concept %s, which %s", + target.label(), OntologyConceptSqlGenerator.NO_VISIBLE_TABLE); + } + return target.tables(); + } + + private static boolean isBound( + final BoundTable previous, final List candidates, final UUID property) { + return previous.objectColumns().containsKey(property) + || candidates.stream().anyMatch(table -> table.objectColumns().containsKey(property)); + } + + private static Optional firstJoin( + final List candidates, final Function> pairs) { + for (final BoundTable candidate : candidates) { + final List on = pairs.apply(candidate); + if (!on.isEmpty()) { + return Optional.of(new Join(candidate, on)); + } + } + return Optional.empty(); + } + + /** + * Follows a bound property, or takes the converse of a hop over a bound inverse from each + * candidate back to the previous table. Every candidate's key equal to the bound column is tried + * before any candidate's key that contains it, and both before the identifier join. + */ + private static Optional bindingJoin( + final Step step, + final List candidates, + final UUID property, + final boolean overInverse) { + final BoundTable previous = step.previous(); + final Function>, Optional> pass = + pairs -> + firstJoin( + candidates, + table -> + overInverse + ? converse(pairs.apply(table, previous)) + : pairs.apply(previous, table)); + return pass.apply((from, to) -> equalKeyPairs(from, to, property)) + .or(() -> pass.apply((from, to) -> containingKeyPairs(step, from, to, property))) + .or(() -> pass.apply((from, to) -> bindingPairs(from, to, property))); + } + + /** + * The table that binds {@code property}, {@code from} winning over {@code to} as in {@link + * #bindingPairs}, with its bound column and its keys to the other table. + */ + private record BoundKeys(boolean reversed, List bound, List keys) { + static Optional of(final BoundTable from, final BoundTable to, final UUID property) { + final boolean reversed = !from.objectColumns().containsKey(property); + final BoundTable owner = reversed ? to : from; + return Optional.ofNullable(owner.objectColumns().get(property)) + .map(bound -> new BoundKeys(reversed, bound, foreignKeys(owner, reversed ? from : to))); + } + } + + private static List equalKeyPairs( + final BoundTable from, final BoundTable to, final UUID property) { + return BoundKeys.of(from, to, property) + .flatMap( + bound -> + bound.keys().stream() + .filter(key -> key.getColumns().equals(bound.bound())) + .findFirst() + .map(key -> pairs(key, bound.reversed()))) + .orElse(List.of()); + } + + /** The one key that contains the bound column orients and joins on all of its columns. */ + private static List containingKeyPairs( + final Step step, final BoundTable from, final BoundTable to, final UUID property) { + final BoundKeys found = BoundKeys.of(from, to, property).orElse(null); + if (found == null || found.bound().size() != 1) { + return List.of(); + } + final String column = found.bound().getFirst(); + final List containing = + found.keys().stream().filter(key -> key.getColumns().contains(column)).toList(); + if (containing.size() > 1) { + throw step.failure( + ": %s is in several foreign keys between %s and %s", + column, + step.previous().fullyQualifiedName(), + (from == step.previous() ? to : from).fullyQualifiedName()); + } + return containing.isEmpty() ? List.of() : pairs(containing.getFirst(), found.reversed()); + } + + private static BadRequestException severalKeys(final Step step, final BoundTable candidate) { + return step.failure( + ": several foreign keys join %s and %s; bind the %s property to one of their columns", + step.previous().fullyQualifiedName(), candidate.fullyQualifiedName(), step.hop().label()); + } + + private static List onlyKeyPairs(final Step step, final BoundTable candidate) { + final List outgoing = foreignKeys(step.previous(), candidate); + final boolean toItself = + candidate.fullyQualifiedName().equals(step.previous().fullyQualifiedName()); + // A key from a table to itself is both outgoing and incoming; count it once. + final List incoming = + toItself ? List.of() : foreignKeys(candidate, step.previous()); + if (outgoing.size() + incoming.size() > 1) { + throw severalKeys(step, candidate); + } + // The property and its inverse read the key in opposite directions, and neither says which. + if (toItself && !outgoing.isEmpty() && step.hop().otherInverse().isPresent()) { + final TableConstraint key = outgoing.getFirst(); + throw step.failure( + ": the foreign key from %s to %s joins %s to itself in either direction;" + + " bind the %s property or its inverse to %s%s", + String.join(", ", key.getColumns()), + pairs(key, false).stream() + .map(pair -> String.join(".", pair.right())) + .collect(Collectors.joining(", ")), + candidate.fullyQualifiedName(), + step.hop().label(), + key.getColumns().size() > 1 ? "one of " : "", + String.join(", ", key.getColumns())); + } + return outgoing.isEmpty() + ? incoming.stream().findFirst().map(key -> pairs(key, true)).orElse(List.of()) + : pairs(outgoing.getFirst(), false); + } + + private static List foreignKeys( + final BoundTable owner, final BoundTable referred) { + return listOrEmpty(owner.constraints()).stream() + .filter( + constraint -> + constraint.getConstraintType() == TableConstraint.ConstraintType.FOREIGN_KEY) + .filter(constraint -> refersTo(constraint, referred.fullyQualifiedName())) + .toList(); + } + + private static boolean refersTo(final TableConstraint constraint, final String table) { + final List referred = listOrEmpty(constraint.getReferredColumns()); + return !referred.isEmpty() + && referred.size() == listOrEmpty(constraint.getColumns()).size() + && referred.stream().allMatch(column -> table.equals(tableOf(column))); + } + + private static String tableOf(final String column) { + return FullyQualifiedName.split(column).length < 5 + ? "" + : FullyQualifiedName.getTableFQN(column); + } + + private static List pairs(final TableConstraint constraint, final boolean reversed) { + return IntStream.range(0, constraint.getColumns().size()) + .mapToObj( + index -> { + final List local = List.of(constraint.getColumns().get(index)); + final List remote = + List.of( + FullyQualifiedName.unquoteName( + FullyQualifiedName.getColumnName( + constraint.getReferredColumns().get(index)))); + return reversed ? new ColumnPair(remote, local) : new ColumnPair(local, remote); + }) + .toList(); + } + + private static List bindingPairs( + final BoundTable from, final BoundTable to, final UUID property) { + final List outgoing = from.objectColumns().get(property); + if (outgoing != null && !to.identifier().isEmpty()) { + return List.of(new ColumnPair(outgoing, to.identifier())); + } + final List incoming = to.objectColumns().get(property); + return incoming != null && !from.identifier().isEmpty() + ? List.of(new ColumnPair(from.identifier(), incoming)) + : List.of(); + } + + private static List converse(final List pairs) { + return pairs.stream().map(pair -> new ColumnPair(pair.right(), pair.left())).toList(); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthRules.java new file mode 100644 index 000000000000..5cd97d0c64f6 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthRules.java @@ -0,0 +1,320 @@ +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.net.URI; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.IntStream; +import org.openmetadata.schema.api.data.OntologyMappingHealthEntry; +import org.openmetadata.schema.api.data.OntologyMappingHealthEntryType; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.security.mask.PIIMasker; + +/** + * What the table bindings of an ontology still need before their rows can be read as records. The + * rules read the catalog metadata handed to them and nothing else, so they never reach a bound + * table, and every table, class and property they are handed is one the caller may view. + */ +public final class OntologyMappingHealthRules { + /** Types that compare and join with each other. A type in no group pairs only with itself. */ + private static final List> FAMILIES = + List.of( + EnumSet.of( + ColumnDataType.NUMBER, + ColumnDataType.TINYINT, + ColumnDataType.SMALLINT, + ColumnDataType.INT, + ColumnDataType.BIGINT, + ColumnDataType.BYTEINT, + ColumnDataType.LONG, + ColumnDataType.LARGEINT, + ColumnDataType.UINT, + ColumnDataType.FLOAT, + ColumnDataType.DOUBLE, + ColumnDataType.DECIMAL, + ColumnDataType.NUMERIC, + ColumnDataType.MONEY), + EnumSet.of( + ColumnDataType.STRING, + ColumnDataType.CHAR, + ColumnDataType.VARCHAR, + ColumnDataType.TEXT, + ColumnDataType.MEDIUMTEXT, + ColumnDataType.NTEXT, + ColumnDataType.CLOB), + EnumSet.of(ColumnDataType.TIMESTAMP, ColumnDataType.TIMESTAMPZ, ColumnDataType.DATETIME), + EnumSet.of( + ColumnDataType.BINARY, + ColumnDataType.VARBINARY, + ColumnDataType.BYTES, + ColumnDataType.BYTEA, + ColumnDataType.BLOB, + ColumnDataType.MEDIUMBLOB, + ColumnDataType.LONGBLOB)); + + private OntologyMappingHealthRules() {} + + /** One table binding of a class, with the class and the table as the caller may read them. */ + public record BoundTable(BindingRow row, EntityReference concept, Table table) {} + + /** The identity binding of a class. {@code table} is null when the caller may not view it. */ + public record Identity(BindingRow row, Table table) {} + + /** The catalog state a page of bound tables is checked against. */ + public record Context( + EntityReference mappingSource, + Map identities, + Map properties, + Map joinTargets) {} + + /** + * What the pages before this one settled: the classes already checked for an identity table, + * and one table for each database the bound tables were found in. + */ + public record Progress(Set settledConcepts, List

databaseWitnesses) { + public static Progress start() { + return new Progress(Set.of(), List.of()); + } + } + + public record Page(List entries, Progress progress) {} + + /** The findings for {@code tables}, in the order given, and the progress the next page takes. */ + public static Page check( + final List tables, final Context context, final Progress earlier) { + final List entries = new ArrayList<>(); + final Set settled = new HashSet<>(earlier.settledConcepts()); + for (final BoundTable bound : tables) { + final UUID conceptId = bound.row().conceptId(); + if (settled.add(conceptId) && !context.identities().containsKey(conceptId)) { + entries.add( + entry(OntologyMappingHealthEntryType.NO_IDENTITY_TABLE).withConcept(bound.concept())); + } + entries.addAll(tableEntries(bound, context)); + } + final List
witnesses = databaseWitnesses(tables, earlier.databaseWitnesses()); + if (spansDatabases(context, witnesses, earlier.databaseWitnesses())) { + entries.add( + entry(OntologyMappingHealthEntryType.MULTIPLE_DATABASES) + .withDatabases(witnesses.stream().map(Table::getDatabase).toList())); + } + return new Page(entries, new Progress(settled, witnesses)); + } + + /** Reported on each page that finds a database no earlier page found, once two are known. */ + private static boolean spansDatabases( + final Context context, final List
witnesses, final List
earlier) { + return context.mappingSource() == null + && witnesses.size() > 1 + && witnesses.size() > earlier.size(); + } + + private static List
databaseWitnesses( + final List tables, final List
earlier) { + final Map byDatabase = new LinkedHashMap<>(); + earlier.forEach(table -> byDatabase.putIfAbsent(table.getDatabase().getId(), table)); + tables.forEach( + bound -> byDatabase.putIfAbsent(bound.table().getDatabase().getId(), bound.table())); + return List.copyOf(byDatabase.values()); + } + + private static List tableEntries( + final BoundTable bound, final Context context) { + final List entries = new ArrayList<>(); + if (bound.row().role() == null) { + entries.add(entry(OntologyMappingHealthEntryType.UNASSIGNED_BINDING, bound)); + } + final EntityReference source = context.mappingSource(); + if (source != null && !source.getId().equals(bound.table().getDatabase().getId())) { + entries.add( + entry(OntologyMappingHealthEntryType.OUTSIDE_MAPPING_SOURCE, bound) + .withDatabases(List.of(bound.table().getDatabase()))); + } + entries.addAll(keyEntries(bound, context.identities().get(bound.row().conceptId()))); + listOrEmpty(bound.row().columns()) + .forEach(column -> entries.addAll(columnEntries(bound, column, context))); + entries.addAll(sensitiveKeyEntries(bound)); + listOrEmpty(bound.row().columns()) + .forEach(column -> typeFitEntry(bound, column, context).ifPresent(entries::add)); + return entries; + } + + /** A key column whose sample data and profile are masked, in key order. */ + private static List sensitiveKeyEntries(final BoundTable bound) { + if (bound.row().role() == null) { + return List.of(); + } + return listOrEmpty(bound.row().subjectKey()).stream() + .filter(path -> masked(bound.table(), path)) + .map( + path -> + entry(OntologyMappingHealthEntryType.SENSITIVE_KEY_COLUMN, bound) + .withColumnPath(path)) + .toList(); + } + + private static boolean masked(final Table table, final List path) { + final List resolved = OntologyBindingRules.resolveColumnPath(table, path); + return !resolved.isEmpty() && PIIMasker.isColumnMasked(table, resolved); + } + + /** A column bound to a DATA property whose one XSD datatype the column's type cannot hold. */ + private static Optional typeFitEntry( + final BoundTable bound, final OntologyColumnBinding column, final Context context) { + final OntologyProperty property = context.properties().get(column.getPropertyId()); + final Column resolved = + OntologyBindingRules.resolveColumn(bound.table(), column.getColumnPath()); + if (property == null + || resolved == null + || property.getKind() != OntologyPropertyKind.DATA + || listOrEmpty(property.getRange()).size() != 1) { + return Optional.empty(); + } + final URI datatype = property.getRange().getFirst(); + return OntologyColumnTypeFit.mismatched(datatype, resolved.getDataType()) + ? Optional.of( + entry(OntologyMappingHealthEntryType.COLUMN_TYPE_MISMATCH, bound) + .withProperty(property.getEntityReference()) + .withColumnPath(column.getColumnPath()) + .withDataType(resolved.getDataType()) + .withPropertyDatatype(datatype)) + : Optional.empty(); + } + + /** A contributing table's key pairs with the identity table's key column by column. */ + private static List keyEntries( + final BoundTable bound, final Identity identity) { + if (bound.row().role() != OntologyBindingRole.CONTRIBUTING + || identity == null + || identity.table() == null) { + return List.of(); + } + final List> own = listOrEmpty(bound.row().subjectKey()); + final List> other = listOrEmpty(identity.row().subjectKey()); + if (own.size() != other.size()) { + return List.of( + entry(OntologyMappingHealthEntryType.KEY_LENGTH_MISMATCH, bound) + .withRelatedAsset(identity.table().getEntityReference()) + .withKeyLength(own.size()) + .withRelatedKeyLength(other.size())); + } + return IntStream.range(0, own.size()) + .mapToObj(i -> ColumnPair.of(bound.table(), own.get(i), identity.table(), other.get(i))) + .filter(ColumnPair::mismatched) + .map(pair -> pair.entry(OntologyMappingHealthEntryType.KEY_TYPE_MISMATCH, bound)) + .toList(); + } + + private static List columnEntries( + final BoundTable bound, final OntologyColumnBinding column, final Context context) { + final OntologyProperty property = context.properties().get(column.getPropertyId()); + final EntityReference propertyRef = property == null ? null : property.getEntityReference(); + if (column.getJoin() == null) { + return property != null && property.getKind() == OntologyPropertyKind.OBJECT + ? List.of( + entry(OntologyMappingHealthEntryType.RELATION_COLUMN_WITHOUT_JOIN, bound) + .withProperty(propertyRef) + .withColumnPath(column.getColumnPath())) + : List.of(); + } + final List entries = new ArrayList<>(); + final Table target = context.joinTargets().get(column.getJoin().getTargetAssetId()); + if (column.getJoin().getStatus() != OntologyJoinStatus.CONFIRMED) { + entries.add( + entry(OntologyMappingHealthEntryType.JOIN_NOT_CONFIRMED, bound) + .withRelatedAsset(target == null ? null : target.getEntityReference()) + .withProperty(propertyRef) + .withColumnPath(column.getColumnPath())); + } + entries.addAll(joinTypeEntries(bound, column, target, propertyRef)); + return entries; + } + + private static List joinTypeEntries( + final BoundTable bound, + final OntologyColumnBinding column, + final Table target, + final EntityReference property) { + if (target == null) { + return List.of(); + } + return listOrEmpty(column.getJoin().getOn()).stream() + .map(pair -> ColumnPair.of(bound.table(), pair.getChild(), target, pair.getParent())) + .filter(ColumnPair::mismatched) + .map( + pair -> + pair.entry(OntologyMappingHealthEntryType.JOIN_TYPE_MISMATCH, bound) + .withProperty(property)) + .toList(); + } + + /** + * Two columns that must hold the same kind of data: a key column and the identity table's key + * column at the same position, or the two sides of a join pair. A column that no longer exists + * is no type finding. + */ + private record ColumnPair( + List path, Column column, EntityReference relatedTable, RelatedColumn related) { + private record RelatedColumn(List path, Column column) {} + + private static ColumnPair of( + final Table table, + final List path, + final Table relatedTable, + final List relatedPath) { + return new ColumnPair( + path, + OntologyBindingRules.resolveColumn(table, path), + relatedTable.getEntityReference(), + new RelatedColumn( + relatedPath, OntologyBindingRules.resolveColumn(relatedTable, relatedPath))); + } + + private boolean mismatched() { + return column != null + && related.column() != null + && !sameFamily(column.getDataType(), related.column().getDataType()); + } + + private OntologyMappingHealthEntry entry( + final OntologyMappingHealthEntryType type, final BoundTable bound) { + return OntologyMappingHealthRules.entry(type, bound) + .withRelatedAsset(relatedTable) + .withColumnPath(path) + .withRelatedColumnPath(related.path()) + .withDataType(column.getDataType()) + .withRelatedDataType(related.column().getDataType()); + } + } + + static boolean sameFamily(final ColumnDataType left, final ColumnDataType right) { + return left == right + || FAMILIES.stream().anyMatch(family -> family.contains(left) && family.contains(right)); + } + + private static OntologyMappingHealthEntry entry(final OntologyMappingHealthEntryType type) { + return new OntologyMappingHealthEntry().withType(type); + } + + private static OntologyMappingHealthEntry entry( + final OntologyMappingHealthEntryType type, final BoundTable bound) { + return entry(type).withConcept(bound.concept()).withAsset(bound.table().getEntityReference()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java new file mode 100644 index 000000000000..3b6491a64be6 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingHealthService.java @@ -0,0 +1,265 @@ +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Stream; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.api.data.OntologyMappingHealth; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingPosition; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.BoundTable; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Context; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Identity; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Progress; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.util.FreshReadScope; +import org.openmetadata.service.util.RestUtil; + +/** + * Reads one page of an ontology's table bindings with the catalog metadata the mapping health + * rules need. It loads tables, classes and properties through their repositories under the + * caller's policies and never opens a connection to a bound table. + */ +public final class OntologyMappingHealthService { + public static final int MAX_PAGE_SIZE = 100; + + /** The cursor remembers this many databases. A wider span is reported again on later pages. */ + static final int MAX_CURSOR_DATABASES = 8; + + private static final int MAX_CURSOR_LENGTH = 1024; + private static final String INVALID_CURSOR = "Invalid ontology mapping health cursor"; + private final OntologyConceptBindingStore store; + private final OntologyBindingAccess targets; + + public OntologyMappingHealthService( + final OntologyConceptBindingStore store, + final Authorizer authorizer, + final Function> repositories) { + this.store = store; + this.targets = new OntologyBindingAccess(authorizer, repositories); + } + + /** + * The ontology with the mapping source it names only when the caller may view that database. The + * findings of a health page use the stored source whoever reads them. + */ + public Ontology withViewableMappingSource(final Access access, final Ontology ontology) { + final EntityReference source = ontology.getMappingSource(); + if (source != null && !targets.viewableEvenIfDeleted(access, Entity.DATABASE, source.getId())) { + ontology.setMappingSource(null); + } + return ontology; + } + + /** {@code ontology} is one the caller may view, read with its mapping source. */ + public OntologyMappingHealth page( + final Access access, final Ontology ontology, final String after, final int limit) { + final Cursor cursor = Cursor.decode(after); + try (final var ignored = FreshReadScope.enter()) { + final List scanned = + store.tableRows(ontology.getId(), cursor.position(), limit + 1); + final List rows = scanned.subList(0, Math.min(limit, scanned.size())); + final Loaded loaded = load(access, rows); + final List tables = boundTables(access, rows, loaded); + final var page = + OntologyMappingHealthRules.check( + tables, context(access, ontology, tables, loaded), progress(access, cursor)); + return new OntologyMappingHealth() + .withMappingSource(withViewableMappingSource(access, copyOf(ontology)).getMappingSource()) + .withEntries(page.entries()) + .withAfter(scanned.size() > limit ? Cursor.next(rows.getLast(), page.progress()) : null); + } + } + + private static Ontology copyOf(final Ontology ontology) { + return new Ontology().withMappingSource(ontology.getMappingSource()); + } + + /** The rows whose table and class are both live and viewable. Every other row says nothing. */ + private List boundTables( + final Access access, final List rows, final Loaded loaded) { + final Map tables = loaded.tables(); + final var concepts = + targets.viewable( + access, + Entity.ONTOLOGY_CONCEPT, + rows.stream() + .filter(row -> tables.containsKey(row.assetId())) + .map(BindingRow::conceptId) + .toList()); + return rows.stream() + .filter(row -> tables.containsKey(row.assetId()) && concepts.containsKey(row.conceptId())) + .map( + row -> + new BoundTable( + row, + concepts.get(row.conceptId()).getEntityReference(), + tables.get(row.assetId()))) + .toList(); + } + + private Context context( + final Access access, + final Ontology ontology, + final List tables, + final Loaded loaded) { + final List columns = + tables.stream().flatMap(bound -> listOrEmpty(bound.row().columns()).stream()).toList(); + return new Context( + ontology.getMappingSource(), + identities(loaded), + typed( + targets.viewable( + access, + Entity.ONTOLOGY_PROPERTY, + columns.stream().map(OntologyColumnBinding::getPropertyId).toList()), + OntologyProperty.class), + typed( + targets.viewable( + access, + Entity.TABLE, + columns.stream() + .map(OntologyColumnBinding::getJoin) + .filter(Objects::nonNull) + .map(join -> join.getTargetAssetId()) + .toList()), + Table.class)); + } + + /** + * The binding rows of a page and of the identity tables of their classes, with the live and + * viewable tables they name, read in one pass. {@code tables} carries tags and columns, which + * the sensitive key check reads, so no table is read again for its identity role. + */ + private record Loaded(List identityRows, Set live, Map tables) {} + + private Loaded load(final Access access, final List rows) { + final List identityRows = + store.identityRows(rows.stream().map(BindingRow::conceptId).toList()); + final List every = Stream.concat(rows.stream(), identityRows.stream()).toList(); + final Set live = store.liveAssets(every).keySet(); + return new Loaded( + identityRows, + live, + typed( + targets.viewable( + access, + Entity.TABLE, + every.stream().map(BindingRow::assetId).filter(live::contains).toList(), + Set.of(Entity.FIELD_TAGS)), + Table.class)); + } + + /** + * A class has an identity table when a live one is stored, whether or not the caller may view + * it, so a hidden identity table never reads as a missing one. + */ + private static Map identities(final Loaded loaded) { + final Map identities = new HashMap<>(); + loaded.identityRows().stream() + .filter(row -> loaded.live().contains(row.assetId())) + .forEach( + row -> + identities.putIfAbsent( + row.conceptId(), new Identity(row, loaded.tables().get(row.assetId())))); + return identities; + } + + /** + * The cursor names one table for each database found so far. Each is read again under the + * caller's policies, so a cursor can only name what its holder may already view. + */ + private Progress progress(final Access access, final Cursor cursor) { + final Map witnesses = + typed(targets.viewable(access, Entity.TABLE, cursor.databaseWitnesses()), Table.class); + return new Progress( + cursor.settled() ? Set.of(cursor.position().conceptId()) : Set.of(), + cursor.databaseWitnesses().stream().map(witnesses::get).filter(Objects::nonNull).toList()); + } + + private static Map typed( + final Map> entities, final Class type) { + final Map typed = new HashMap<>(); + entities.forEach((id, entity) -> typed.put(id, type.cast(entity))); + return typed; + } + + /** + * Where the next page starts and what the pages before it settled: whether the class at the + * position was already checked for an identity table, and one table per database found. + */ + record Cursor(BindingPosition position, boolean settled, List databaseWitnesses) { + private static final Cursor START = new Cursor(null, false, List.of()); + private static final String SEPARATOR = "|"; + private static final String LIST_SEPARATOR = ","; + private static final String SETTLED = "1"; + private static final String UNSETTLED = "0"; + private static final int PARTS = 4; + + static String next(final BindingRow last, final Progress progress) { + final String witnesses = + String.join( + LIST_SEPARATOR, + progress.databaseWitnesses().stream() + .limit(MAX_CURSOR_DATABASES) + .map(table -> table.getId().toString()) + .toList()); + return RestUtil.encodeCursor( + String.join( + SEPARATOR, + last.conceptId().toString(), + last.assetId().toString(), + progress.settledConcepts().contains(last.conceptId()) ? SETTLED : UNSETTLED, + witnesses)); + } + + static Cursor decode(final String after) { + if (after == null || after.isEmpty()) { + return START; + } + if (after.length() > MAX_CURSOR_LENGTH) { + throw new BadRequestException(INVALID_CURSOR); + } + try { + return parse(RestUtil.decodeCursor(after).split("\\" + SEPARATOR, -1)); + } catch (final IllegalArgumentException invalid) { + throw new BadRequestException(INVALID_CURSOR, invalid); + } + } + + private static Cursor parse(final String[] parts) { + if (parts.length != PARTS || !Set.of(SETTLED, UNSETTLED).contains(parts[2])) { + throw new IllegalArgumentException(INVALID_CURSOR); + } + final List witnesses = + parts[3].isEmpty() + ? List.of() + : Arrays.stream(parts[3].split(LIST_SEPARATOR, -1)).map(UUID::fromString).toList(); + if (witnesses.size() > MAX_CURSOR_DATABASES) { + throw new IllegalArgumentException(INVALID_CURSOR); + } + return new Cursor( + new BindingPosition(UUID.fromString(parts[0]), UUID.fromString(parts[1])), + SETTLED.equals(parts[2]), + witnesses); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java new file mode 100644 index 000000000000..6064ce18d53e --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyMappingReader.java @@ -0,0 +1,254 @@ +/* + * 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.ontology; + +import static org.openmetadata.service.ontology.OntologyRecordMapping.conflict; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyMappingReader.SearchStart.IdentityTable; +import org.openmetadata.service.ontology.OntologyMappingReader.SearchStart.OnlyTable; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyRelationPath.End; +import org.openmetadata.service.ontology.OntologyRelationPath.Ends; +import org.openmetadata.service.ontology.OntologyRelationPath.Held; +import org.openmetadata.service.ontology.OntologyRelationPath.StoredJoin; +import org.openmetadata.service.security.AuthorizationException; + +/** + * Reads what a statement needs from the table bindings of its classes: the binding rows with the + * revisions they belong to, and the tables those rows name. It decides which table a statement + * starts from, and that never depends on who asks + * (ADR:2026-11-22-record-statements-start-from-the-identity-table). + */ +final class OntologyMappingReader { + /** A statement reads at most this many contributing tables of one class. */ + static final int MAX_CONTRIBUTING_TABLES = 32; + + static final int BINDING_READ_ATTEMPTS = 3; + private static final int SEVERAL_TABLES = 2; + private final OntologyConceptBindingStore store; + private final OntologyBindingAccess catalog; + + OntologyMappingReader( + final OntologyConceptBindingStore store, final OntologyBindingAccess catalog) { + this.store = store; + this.catalog = catalog; + } + + /** + * The binding rows of the classes of one statement, with the binding revision of each class. + * + * @param identity the identity table row of each class that has one + * @param contributing the first contributing table rows of each class that was asked for them + */ + record Bindings( + Map revisions, + Map identity, + Map> contributing) { + List rows() { + return Stream.concat( + identity.values().stream(), contributing.values().stream().flatMap(List::stream)) + .toList(); + } + } + + /** + * The tables that binding rows name. + * + * @param live the ids of the tables that exist + * @param viewable the tables the reader may view, with their columns + */ + record Tables(Set live, Map> viewable) { + boolean holds(final BindingRow row) { + return live.contains(row.assetId()); + } + + boolean shows(final BindingRow row) { + return viewable.containsKey(row.assetId()); + } + + MappedTable mapped(final BindingRow row) { + return new MappedTable((Table) viewable.get(row.assetId()), row); + } + } + + /** The table that the search-around statement of a class starts from. */ + sealed interface SearchStart { + /** + * The class binds at most one table, and the statement starts from that table whatever the + * role of its binding. + * + * @param rows the one table row of the class whose table exists, or no row + */ + record OnlyTable(List rows) implements SearchStart {} + + /** The class binds several tables, and the statement starts from its identity table. */ + record IdentityTable(BindingRow row) implements SearchStart {} + } + + /** + * Reads the binding rows between two reads of the binding revisions. A binding write commits its + * rows and its revision in one transaction, so two equal revision reads mean that no write + * landed between them, and the rows are the ones those revisions describe. + * + * @param withContributing the classes whose contributing table rows the statement reads + */ + Bindings bindings(final Collection classes, final Collection withContributing) { + return between( + classes, + "The table bindings changed while the statement was built. Ask again", + revisions -> + new Bindings(revisions, identityRows(classes), contributingRows(withContributing))); + } + + /** + * Runs {@code read} between two reads of the binding revisions of {@code classes} and returns + * its result when the two reads agree. After {@value #BINDING_READ_ATTEMPTS} attempts that never + * agree, it is a 409 with {@code refusal}. + * + * @param read takes the first revision read + */ + T between( + final Collection classes, + final String refusal, + final Function, T> read) { + for (int attempt = 0; attempt < BINDING_READ_ATTEMPTS; attempt++) { + final Map revisions = store.revisions(classes); + final T result = read.apply(revisions); + if (revisions.equals(store.revisions(classes))) { + return result; + } + } + throw conflict(refusal); + } + + /** + * Finds the table that the search-around statement of a class starts from. A class with one + * table binding starts from that table, as it did before a binding had a role. A class with + * several table bindings starts from its identity table. Without one it gets no statement, + * because the server never picks one of several tables for a reader. + * + *

A binding whose table no longer exists is no table binding here, as the list of the + * bindings of a class leaves it out. That holds for the identity binding too. The rule reads + * the first table bindings of the class, up to + * {@link OntologyConceptQueryService#TABLE_BINDINGS_READ}. + */ + SearchStart searchStart(final UUID type, final URI iri) { + final List classes = List.of(type); + final List tables = + held(store.firstTables(classes, OntologyConceptQueryService.TABLE_BINDINGS_READ)); + return tables.size() < SEVERAL_TABLES + ? new OnlyTable(tables) + : new IdentityTable(identityAmongSeveral(iri, held(store.identityRows(classes)))); + } + + /** The rows whose table exists. */ + private List held(final List rows) { + final Set live = store.liveAssets(rows).keySet(); + return rows.stream().filter(row -> live.contains(row.assetId())).toList(); + } + + private static BindingRow identityAmongSeveral(final URI type, final List identity) { + if (identity.isEmpty()) { + throw conflict( + "Class %s binds several tables and none is its identity table. Pick its identity table", + type); + } + return identity.getFirst(); + } + + private Map identityRows(final Collection classes) { + return store.identityRows(classes).stream() + .collect(Collectors.toMap(BindingRow::conceptId, Function.identity())); + } + + private Map> contributingRows(final Collection classes) { + return classes.stream() + .collect( + Collectors.toMap( + Function.identity(), + id -> store.contributingRows(id, MAX_CONTRIBUTING_TABLES + 1))); + } + + /** The tables of {@code rows}: which exist, and which of those the reader may view. */ + Tables tables(final Access access, final Collection rows) { + final Set live = store.liveAssets(List.copyOf(rows)).keySet(); + return new Tables(live, catalog.viewable(access, Entity.TABLE, live)); + } + + /** + * The identity table of a class. A class without one gives no statement. A class whose identity + * table the reader may not view is refused without naming the table, so a statement never + * starts from another table because of who asks. + * + * @param row the identity table row of the class, or null when it has none + */ + static MappedTable identity(final URI type, final BindingRow row, final Tables tables) { + if (row == null || !tables.holds(row)) { + throw conflict("Class %s has no identity table", type); + } + if (!tables.shows(row)) { + throw new AuthorizationException( + String.format("The identity table of class %s is not visible to you", type)); + } + return tables.mapped(row); + } + + /** The contributing table rows of a class whose tables exist, in asset id order. */ + static List contributing( + final URI type, final List rows, final Tables tables) { + if (rows.size() > MAX_CONTRIBUTING_TABLES) { + throw conflict( + "Class %s binds more than %d contributing tables", type, MAX_CONTRIBUTING_TABLES); + } + return rows.stream().filter(tables::holds).toList(); + } + + /** + * The confirmed join of a relation from the tables of its subject class onto the identity table + * of its object class. Both classes have an identity table. When a contributing table holds the + * join, a reader who may not view that table is refused without it being named. + */ + static Held join(final Ends ends, final Bindings bindings, final Tables tables) { + final End subject = ends.subject(); + final List holders = + new ArrayList<>(List.of(bindings.identity().get(subject.id()))); + holders.addAll(contributing(subject.iri(), bindings.contributing().get(subject.id()), tables)); + final StoredJoin stored = + OntologyRelationPath.choose( + ends, holders, bindings.identity().get(ends.object().id()).assetId()); + if (stored.isLink() && !tables.shows(stored.holder())) { + throw new AuthorizationException( + String.format( + "The table that links class %s to class %s for relation %s is not visible to you", + subject.iri(), ends.object().iri(), ends.relation())); + } + return new Held(stored.join(), stored.isLink() ? tables.mapped(stored.holder()) : null); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPartOutcome.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPartOutcome.java new file mode 100644 index 000000000000..6ce058fe68c6 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPartOutcome.java @@ -0,0 +1,49 @@ +/* + * 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.ontology; + +import java.util.List; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; + +/** + * How one part of a shape constraint is checked on the tables of a class + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). Only a check holds tests and only + * a refusal holds a reason. + */ +sealed interface OntologyPartOutcome { + /** Tests that find a violation exactly when a record breaks the part, one for each table. */ + record Check(List checks) implements OntologyPartOutcome {} + + /** The table bindings already hold the part for every record, so nothing is tested. */ + record HeldByMapping() implements OntologyPartOutcome {} + + /** The class binds the property in no column, or the version read has no such property. */ + record NotMapped() implements OntologyPartOutcome {} + + /** No test finds exactly the records that break the part. */ + record NotEnforceable(OntologyShapeCheckReason reason) implements OntologyPartOutcome {} + + /** + * One test on the table that holds the property: a statement written for the part, which counts + * the records in violation. + * + * @param columns the columns of that table whose values the test reads + * @param probe which records the statement counts + * @param read every binding row the test was built from + */ + record TableCheck( + Place place, List> columns, OntologyCheckProbe probe, List read) {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.java new file mode 100644 index 000000000000..f4b657d9c955 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPortablePattern.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.ontology; + +import java.util.BitSet; +import java.util.Optional; +import java.util.regex.Pattern; + +/** + * The regular expressions that an engine can match as SHACL does + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). SHACL reads a pattern as the + * {@code matches} function of XPath does with no flag. Engines differ in what they add to a + * common core, so a pattern is taken only when it stays inside it: + * + *

    + *
  • it starts with {@code ^} and ends with {@code $}, and holds no other anchor; + *
  • a character is an ASCII letter, a digit, a space, an ASCII punctuation character that is + * no metacharacter, {@code .}, or a backslash before a character of the single-character + * escape set of XPath; + *
  • a character class holds the same literal characters, escapes, and ranges of two digits or + * of two letters of one case, and may be negated; + *
  • a group has no prefix such as {@code (?:}, and holds every alternation; + *
  • a quantifier is {@code ?}, {@code *}, {@code +}, {@code {n}}, {@code {n,}} or {@code + * {n,m}}, and nothing follows it that would make it lazy or possessive. + *
+ * + * The metacharacters are {@code . \ ? * + { } ( ) [ ] | ^ $}, and {@code -} inside a class. The + * escape set is the one of XPath and XQuery Functions and Operators 3.1, section 5.6.1: {@code n}, + * {@code r}, {@code t}, and a backslash before {@code \ | . ? * + ( ) { } - [ ] ^ $}. Any other + * escape is an error in XPath, so a pattern that holds one is refused and not read as the escaped + * character. {@code \n}, {@code \r} and {@code \t} are a line feed, a carriage return and a tab + * on Postgres too, in a class and outside one. + * + *

An alternation outside a group is refused because {@code ^a|b$} anchors one branch each on an + * engine that searches and both on an engine that matches the whole value. + * + *

Postgres is the one engine that was run against every construct of the core. It reads one of + * them in another way: its {@code .} matches a line feed and a carriage return, and the one of + * XPath matches neither. So a pattern is written for Postgres with the class of every character + * but those two in place of each {@code .}. The rest it reads as XPath does. {@code $} matches at + * the very end only, a range in a class goes by code point whatever the collation, a negated + * class matches a line break, and each escape of the set above is the character it names. + */ +final class OntologyPortablePattern { + private static final Pattern COUNT = Pattern.compile("0|[1-9][0-9]{0,2}"); + private static final String ANY_BUT_A_LINE_BREAK = "[^\\n\\r]"; + private static final String QUANTIFIERS = "?*+{"; + + /** Every character that XPath reads as syntax outside a class. {@code -} joins them inside one. */ + private static final String METACHARACTERS = ".\\?*+{}()[]|^$"; + + /** The characters after a backslash that XPath reads: the escape set of its single characters. */ + private static final String ESCAPABLE = "nrt\\|.?*+(){}-[]^$"; + + private static final int MOST_REPEATS = 255; + private static final char LAST_ASCII = '~'; + private final String body; + + /** Where the body holds a {@code .} that stands for a character. */ + private final BitSet wildcards = new BitSet(); + + private int at; + + private OntologyPortablePattern(final String body) { + this.body = body; + } + + /** + * The pattern as Postgres matches it the way XPath matches {@code pattern}, or empty when the + * pattern leaves the common core. + */ + static Optional forPostgres(final String pattern) { + final int end = pattern.length() - 1; + if (end < 1 || pattern.charAt(0) != '^' || pattern.charAt(end) != '$') { + return Optional.empty(); + } + final OntologyPortablePattern parser = new OntologyPortablePattern(pattern.substring(1, end)); + final boolean portable = parser.sequence() && parser.at == parser.body.length(); + return portable ? Optional.of("^" + parser.withoutWildcards() + "$") : Optional.empty(); + } + + private String withoutWildcards() { + final StringBuilder written = new StringBuilder(); + for (int index = 0; index < body.length(); index++) { + written.append( + wildcards.get(index) ? ANY_BUT_A_LINE_BREAK : body.substring(index, index + 1)); + } + return written.toString(); + } + + private boolean more() { + return at < body.length(); + } + + /** Atoms, each with at most one quantifier, up to the end of an alternative. */ + private boolean sequence() { + while (more() && body.charAt(at) != '|' && body.charAt(at) != ')') { + if (!atom() || !quantifier()) { + return false; + } + } + return true; + } + + private boolean atom() { + final char next = body.charAt(at); + if (isLiteral(next) || next == '.') { + wildcards.set(at, next == '.'); + at++; + return true; + } + return switch (next) { + case '\\' -> escaped(); + case '[' -> characterClass(); + case '(' -> group(); + default -> false; + }; + } + + private static boolean isAlphanumeric(final char character) { + return character <= LAST_ASCII && Character.isLetterOrDigit(character); + } + + /** A character that stands for itself outside a class. */ + private static boolean isLiteral(final char character) { + return character >= ' ' && character <= LAST_ASCII && METACHARACTERS.indexOf(character) < 0; + } + + /** A character that stands for itself inside a class, where {@code -} is syntax too. */ + private static boolean isClassLiteral(final char character) { + return isLiteral(character) && character != '-'; + } + + /** A backslash before a character of the escape set, which XPath reads and Postgres agrees on. */ + private boolean escaped() { + final boolean known = at + 1 < body.length() && ESCAPABLE.indexOf(body.charAt(at + 1)) >= 0; + at += 2; + return known; + } + + private boolean characterClass() { + at++; + at += more() && body.charAt(at) == '^' ? 1 : 0; + final int first = at; + while (more() && body.charAt(at) != ']') { + if (!member()) { + return false; + } + } + return at > first && more() && body.charAt(at++) == ']'; + } + + /** + * One literal character or escape of a class, or a range of two digits or of two letters of one + * case. + */ + private boolean member() { + if (body.charAt(at) == '\\') { + return escaped(); + } + final char low = body.charAt(at++); + if (!isClassLiteral(low)) { + return false; + } + if (!more() || body.charAt(at) != '-') { + return true; + } + final char high = at + 1 < body.length() ? body.charAt(at + 1) : ' '; + at += 2; + return isAlphanumeric(low) + && isAlphanumeric(high) + && low <= high + && Character.getType(low) == Character.getType(high); + } + + private boolean group() { + at++; + if (more() && body.charAt(at) == '?') { + return false; + } + boolean another = true; + while (another) { + final int start = at; + if (!sequence() || at == start) { + return false; + } + another = more() && body.charAt(at) == '|'; + at += another ? 1 : 0; + } + return more() && body.charAt(at++) == ')'; + } + + /** At most one quantifier, with nothing after it that changes how it repeats. */ + private boolean quantifier() { + if (!more() || QUANTIFIERS.indexOf(body.charAt(at)) < 0) { + return true; + } + if (body.charAt(at) != '{') { + at++; + } else if (!counted()) { + return false; + } + return !more() || QUANTIFIERS.indexOf(body.charAt(at)) < 0; + } + + private boolean counted() { + final int close = body.indexOf('}', at); + if (close < 0) { + return false; + } + final String[] bounds = body.substring(at + 1, close).split(",", -1); + at = close + 1; + if (bounds.length > 2 || !isCount(bounds[0])) { + return false; + } + return bounds.length == 1 + || bounds[1].isEmpty() + || isCount(bounds[1]) && Integer.parseInt(bounds[0]) <= Integer.parseInt(bounds[1]); + } + + private static boolean isCount(final String digits) { + return COUNT.matcher(digits).matches() && Integer.parseInt(digits) <= MOST_REPEATS; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPropertyRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPropertyRules.java index a22113f266c7..f6ed6e18740e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPropertyRules.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyPropertyRules.java @@ -171,7 +171,9 @@ private static Violation dataMetadata(final OntologyProperty property) { final String field = dataOnlyField(property); if (field != null) { return new Violation( - field, "Only data properties can define enum values, units or identifier intent"); + field, + "Only data properties can define enum values, units, identifier intent or display-name" + + " intent"); } } if (unit != null && (unit.isBlank() || unit.length() > MAX_UNIT_LENGTH)) { @@ -194,7 +196,10 @@ private static String dataOnlyField(final OntologyProperty property) { if (property.getUnit() != null) { return "unit"; } - return Boolean.TRUE.equals(property.getIsIdentifier()) ? "isIdentifier" : null; + if (Boolean.TRUE.equals(property.getIsIdentifier())) { + return "isIdentifier"; + } + return Boolean.TRUE.equals(property.getIsDisplayName()) ? "isDisplayName" : null; } private static Violation literal(final OntologyLiteral literal) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyRecordMapping.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyRecordMapping.java new file mode 100644 index 000000000000..e95f06a9ecdd --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyRecordMapping.java @@ -0,0 +1,152 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import jakarta.ws.rs.ClientErrorException; +import jakarta.ws.rs.core.Response; +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.IntStream; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.sql.TypedRowFilter; + +/** + * The tables of a class as a statement about its records reads them + * (ADR:2026-11-22-record-statements-start-from-the-identity-table). Nothing here reads a database + * or a policy. Callers pass the tables the reader may view and the properties that the chosen + * ontology version declares. + */ +final class OntologyRecordMapping { + private OntologyRecordMapping() {} + + /** A 409: the mapping or the catalog is in a state that gives no statement. */ + static ClientErrorException conflict(final String message, final Object... args) { + return new ClientErrorException(String.format(message, args), Response.Status.CONFLICT); + } + + /** One table that a class binds, with the binding row that says how its rows become records. */ + record MappedTable(Table table, BindingRow row) { + String fullyQualifiedName() { + return table.getFullyQualifiedName(); + } + + String serviceType() { + return table.getServiceType() == null ? null : table.getServiceType().value(); + } + + /** The service and the database that hold the table, as unquoted names. */ + List database() { + return OntologyConceptSqlGenerator.fqnParts(fullyQualifiedName(), 2); + } + + List> keyPaths() { + return listOrEmpty(row.subjectKey()); + } + + /** The subject key columns in key order. */ + List key() { + return keyPaths().stream().map(this::require).toList(); + } + + /** The column at {@code path}, or a 409 when it left the table after the binding was saved. */ + Column require(final List path) { + final Column column = OntologyBindingRules.resolveColumn(table, path); + if (column == null) { + throw conflict( + "Column %s of %s no longer exists", String.join(".", path), fullyQualifiedName()); + } + return column; + } + + boolean holds(final List path) { + return OntologyBindingRules.resolveColumn(table, path) != null; + } + + /** The stored row filter with its values parsed again, or null when the binding has none. */ + TypedRowFilter filter() { + return OntologyTableBindingChecks.storedRowFilter(table, row.rowFilter()); + } + } + + /** A column of the table before that equals a column of the joined table. */ + record JoinPair(List previous, List joined) {} + + /** A column that holds the values of one data property. */ + record PropertyColumn(OntologyProperty property, List path) { + boolean isDisplayName() { + return Boolean.TRUE.equals(property.getIsDisplayName()); + } + } + + /** + * A class as one ontology version declares it, with its identity table. + * + * @param properties the properties of that version that the reader may view, by id + */ + record MappedClass( + UUID id, URI iri, MappedTable identity, Map properties) { + /** + * The columns of {@code table} that hold a data property, in binding order. A column that left + * the table is left out, and so is one whose property the version lacks or the reader may not + * view. + */ + List dataColumns(final MappedTable table) { + return listOrEmpty(table.row().columns()).stream() + .filter(binding -> isData(properties.get(binding.getPropertyId()))) + .filter(binding -> table.holds(binding.getColumnPath())) + .map( + binding -> + new PropertyColumn( + properties.get(binding.getPropertyId()), binding.getColumnPath())) + .toList(); + } + + /** The display name column of the identity table, when the class binds one there. */ + Optional displayName() { + return dataColumns(identity).stream().filter(PropertyColumn::isDisplayName).findFirst(); + } + + /** + * A contributing table pairs its subject key with the key of the identity table by position. + */ + List keyPairs(final MappedTable contributing) { + final List> key = identity.keyPaths(); + final List> paired = contributing.keyPaths(); + if (key.size() != paired.size()) { + throw conflict( + "The subject key of %s has %d columns and the key of class %s has %d", + contributing.fullyQualifiedName(), paired.size(), iri, key.size()); + } + // Both keys must still resolve to columns before they are paired. + identity.key(); + contributing.key(); + return IntStream.range(0, key.size()) + .mapToObj(part -> new JoinPair(key.get(part), paired.get(part))) + .toList(); + } + + private static boolean isData(final OntologyProperty property) { + return property != null && property.getKind() == OntologyPropertyKind.DATA; + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReferences.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReferences.java index 55dea6365ddb..b5a79ae3c24e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReferences.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReferences.java @@ -12,10 +12,12 @@ import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyExpression; import org.openmetadata.schema.type.OntologyLiteral; import org.openmetadata.schema.type.OntologyReference; import org.openmetadata.schema.type.OntologyReferenceRole; +import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.service.Entity; import org.openmetadata.service.exception.BadRequestException; @@ -46,6 +48,10 @@ public static List collect(final OntologyDefinition entity) { references.axiom(axiom); yield Entity.ONTOLOGY_AXIOM; } + case OntologyShape shape -> { + references.shape(shape); + yield Entity.ONTOLOGY_SHAPE; + } default -> throw new BadRequestException("Unsupported ontology reference source"); }; return references.targets.stream() @@ -80,6 +86,20 @@ private void property(final OntologyProperty property) { listOrEmpty(property.getEnumValues()).forEach(this::literal); } + /** + * A shape names the class it targets, the classes its constraints require and the properties + * they constrain, so deleting one of them is refused while the shape is live. + */ + private void shape(final OntologyShape shape) { + add(OntologyReferenceRole.CLASS_EXPRESSION, shape.getTargetConcept()); + for (final OntologyShapeConstraint constraint : listOrEmpty(shape.getConstraints())) { + if (constraint != null) { + add(OntologyReferenceRole.CLASS_EXPRESSION, constraint.getClassIri()); + add(OntologyReferenceRole.PROPERTY, constraint.getPath()); + } + } + } + private void axiom(final OntologyAxiom axiom) { add(OntologyReferenceRole.AXIOM_SUBJECT, axiom.getSubjectIri()); add(OntologyReferenceRole.SUPER_CLASS, OntologyClassHierarchy.namedParents(axiom)); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyRelationPath.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyRelationPath.java new file mode 100644 index 000000000000..26969f019077 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyRelationPath.java @@ -0,0 +1,195 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.service.ontology.OntologyRecordMapping.conflict; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedClass; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; + +/** + * How one relation joins the records of two classes: from the identity table of the start class, + * over a link table when a contributing table holds the relation, to the identity table of the + * related class. The class that binds the relation is its subject, and the class whose identity + * table the stored join names is its object. A {@code forward} path starts at the subject and an + * {@code inverse} path at the object. + * + * @param joins the tables after the first, in join order + */ +record OntologyRelationPath( + OntologyProperty relation, + OntologyStatementDirection direction, + MappedClass start, + MappedClass related, + List joins) { + + /** One table of the path after the first, with the columns that join it to the one before. */ + record Joined(MappedTable table, List on) {} + + /** One class at an end of a relation. */ + record End(UUID id, URI iri) {} + + /** + * A relation with the class that binds it and the class it reaches. A refusal names all three by + * IRI. + */ + record Ends(UUID relationId, URI relation, End subject, End object) {} + + /** + * The join that a class stores for a relation. + * + * @param holder the binding row whose column carries the join: the identity table of the subject + * class, or a contributing table that links the two classes + */ + record StoredJoin(BindingRow holder, OntologyColumnJoin join) { + boolean isLink() { + return holder.role() == OntologyBindingRole.CONTRIBUTING; + } + } + + /** + * The join a path follows. + * + * @param link the contributing table that holds the join, or null when the identity table of the + * subject class holds it + */ + record Held(OntologyColumnJoin join, MappedTable link) {} + + /** + * What the rows of the subject class store for a relation onto one table. + * + * @see #lookup + */ + sealed interface Lookup { + /** A confirmed join, from the first row that holds one. */ + record Confirmed(StoredJoin stored) implements Lookup {} + + /** The rows hold a join onto the table and none of them is confirmed. */ + record Unconfirmed() implements Lookup {} + + /** The rows hold no join of the relation onto the table. */ + record Missing() implements Lookup {} + } + + /** + * The join onto {@code objectTable} that {@code subjectRows} store for a relation, in the order + * of the rows: a confirmed join wins over one that is only inferred, and an inferred one over no + * join at all. + */ + static Lookup lookup( + final UUID relationId, final List subjectRows, final UUID objectTable) { + final List stored = + subjectRows.stream() + .flatMap( + row -> + listOrEmpty(row.columns()).stream() + .filter(column -> relationId.equals(column.getPropertyId())) + .filter(column -> column.getJoin() != null) + .filter(column -> objectTable.equals(column.getJoin().getTargetAssetId())) + .map(column -> new StoredJoin(row, column.getJoin()))) + .toList(); + final Optional confirmed = + stored.stream() + .filter(candidate -> candidate.join().getStatus() == OntologyJoinStatus.CONFIRMED) + .findFirst(); + if (confirmed.isPresent()) { + return new Lookup.Confirmed(confirmed.get()); + } + return stored.isEmpty() ? new Lookup.Missing() : new Lookup.Unconfirmed(); + } + + /** + * The confirmed join onto {@code objectTable} that the rows of the subject class store for the + * relation. The identity table is asked before the contributing tables, and the choice never + * depends on which tables a reader may view. A join that is only inferred is a 409, and so is no + * join at all. + */ + static StoredJoin choose( + final Ends ends, final List subjectRows, final UUID objectTable) { + return switch (lookup(ends.relationId(), subjectRows, objectTable)) { + case Lookup.Confirmed found -> found.stored(); + case Lookup.Unconfirmed ignored -> throw conflict( + "The join of relation %s from class %s to class %s is not confirmed", + ends.relation(), ends.subject().iri(), ends.object().iri()); + case Lookup.Missing ignored -> throw conflict( + "Relation %s has no join from class %s to the identity table of class %s", + ends.relation(), ends.subject().iri(), ends.object().iri()); + }; + } + + /** The path of {@code relation} from {@code start} to {@code related} over the join it holds. */ + static OntologyRelationPath of( + final OntologyProperty relation, + final OntologyStatementDirection direction, + final MappedClass start, + final MappedClass related, + final Held held) { + final boolean forward = direction == OntologyStatementDirection.FORWARD; + final MappedClass subject = forward ? start : related; + final MappedClass object = forward ? related : start; + final MappedTable holder = held.link() == null ? subject.identity() : held.link(); + final List forwardJoins = new ArrayList<>(); + if (held.link() != null) { + forwardJoins.add(new Joined(held.link(), subject.keyPairs(held.link()))); + } + forwardJoins.add(new Joined(object.identity(), stored(held.join(), holder, object.identity()))); + return new OntologyRelationPath( + relation, + direction, + start, + related, + forward ? List.copyOf(forwardJoins) : reversed(subject.identity(), forwardJoins)); + } + + /** The stored pairs, each a column of the holder and the column of the object table it equals. */ + private static List stored( + final OntologyColumnJoin join, final MappedTable holder, final MappedTable objectTable) { + return join.getOn().stream() + .map( + pair -> { + holder.require(pair.getChild()); + objectTable.require(pair.getParent()); + return new JoinPair(pair.getChild(), pair.getParent()); + }) + .toList(); + } + + /** The same joins read from the object back to the subject, which ends the path. */ + private static List reversed(final MappedTable subjectTable, final List joins) { + final List back = new ArrayList<>(); + for (int index = joins.size() - 1; index >= 0; index--) { + final MappedTable before = index == 0 ? subjectTable : joins.get(index - 1).table(); + back.add( + new Joined( + before, + joins.get(index).on().stream() + .map(pair -> new JoinPair(pair.joined(), pair.previous())) + .toList())); + } + return List.copyOf(back); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseContent.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseContent.java index 5c397695c903..0bab2382404e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseContent.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseContent.java @@ -8,6 +8,7 @@ import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.utils.JsonUtils; /** The explicit ontology-release-v1 content contract, independent of live entity metadata. */ @@ -47,6 +48,7 @@ private static List semanticFields(final OntologyDefinition definition) "enumValues", "unit", "isIdentifier", + "isDisplayName", "inverse", "characteristics", "propertyChain", @@ -62,6 +64,7 @@ private static List semanticFields(final OntologyDefinition definition) "targetIri", "literal", "provenance"); + case OntologyShape ignored -> List.of("targetConcept", "severity", "constraints"); default -> throw new IllegalArgumentException( "Unsupported ontology content: " + definition.getClass()); }; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseReader.java index 8f612147c72c..60180129273d 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseReader.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyReleaseReader.java @@ -13,6 +13,7 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; import org.openmetadata.schema.utils.JsonUtils; @@ -119,7 +120,8 @@ public static OntologyDefinition definition(final OntologyReleaseMember member) case CONCEPT -> OntologyConcept.class; case PROPERTY -> OntologyProperty.class; case AXIOM -> OntologyAxiom.class; - default -> throw new BadRequestException( + case SHAPE -> OntologyShape.class; + case ASSOCIATION -> throw new BadRequestException( "Unsupported ontology release member: " + member.getMemberKind()); }; final var value = JsonUtils.convertValueLenient(member.getPayload(), type); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySelectText.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySelectText.java new file mode 100644 index 000000000000..d6c8f2617456 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySelectText.java @@ -0,0 +1,113 @@ +/* + * 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.ontology; + +import org.openmetadata.schema.api.data.OntologyConceptQueryDialect; +import org.openmetadata.service.ontology.sql.TypedStatement; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * Writes the clauses of one SELECT in order. Every statement the generator returns is written + * through it, so the row limit, a table name and the start of each predicate have one spelling. + * T-SQL writes the row limit as {@code TOP} after {@code SELECT}. Every other dialect writes it as + * {@code LIMIT} at the end. + */ +final class OntologySelectText { + private static final String NESTED_INDENT = " "; + private final TypedStatement.Builder sql; + private final boolean limitsWithTop; + private final String lineBreak; + private boolean hasPredicate; + + OntologySelectText(final TypedStatement.Builder sql, final OntologyConceptQueryDialect dialect) { + this(sql, dialect, "\n"); + } + + private OntologySelectText( + final TypedStatement.Builder sql, + final OntologyConceptQueryDialect dialect, + final String lineBreak) { + this.sql = sql; + this.limitsWithTop = dialect == OntologyConceptQueryDialect.TSQL; + this.lineBreak = lineBreak; + } + + /** {@code SELECT}, ready for its list. */ + TypedStatement.Builder select(final int limit) { + return sql.sql(limitsWithTop ? "SELECT TOP " + limit + " " : "SELECT "); + } + + /** {@code SELECT} with no row limit, ready for its list. */ + TypedStatement.Builder selectAll() { + return sql.sql("SELECT "); + } + + /** + * Opens a derived table after {@code FROM} and returns the writer of the SELECT inside it, whose + * lines are indented. That SELECT is {@code DISTINCT} and carries no row limit. + */ + OntologySelectText fromDistinct(final OntologyConceptQueryDialect dialect) { + sql.sql(lineBreak + "FROM (" + lineBreak + NESTED_INDENT + "SELECT DISTINCT "); + return new OntologySelectText(sql, dialect, lineBreak + NESTED_INDENT); + } + + /** A derived table after {@code FROM} that holds {@code inner}, indented, under {@code alias}. */ + void fromStatement(final TypedStatement inner, final String alias) { + sql.sql(lineBreak + "FROM (" + lineBreak + NESTED_INDENT); + sql.nested(inner, lineBreak + NESTED_INDENT); + closeDerived(alias); + } + + /** Closes the derived table that {@link #fromDistinct} opened and names it. */ + void closeDerived(final String alias) { + sql.sql(lineBreak + ") " + alias); + } + + /** {@code FROM schema.table}, under {@code alias} when one is given. */ + OntologySelectText from(final String tableFqn, final String alias) { + tableName(sql.sql(lineBreak + "FROM "), tableFqn); + sql.sql(alias == null ? "" : " " + alias); + return this; + } + + /** One join line up to {@code ON}, ready for its condition. */ + TypedStatement.Builder join(final String keyword, final String tableFqn, final String alias) { + tableName(sql.sql(lineBreak + keyword + " "), tableFqn); + return sql.sql(" " + alias + " ON "); + } + + /** The start of the next predicate: {@code WHERE} for the first and {@code AND} after it. */ + TypedStatement.Builder where() { + sql.sql(lineBreak + (hasPredicate ? " AND " : "WHERE ")); + hasPredicate = true; + return sql; + } + + /** A clause on a line of its own, such as {@code GROUP BY}, ready for what follows it. */ + TypedStatement.Builder clause(final String keyword) { + return sql.sql(lineBreak + keyword + " "); + } + + /** The row limit, for a dialect that writes it at the end. */ + void limit(final int limit) { + sql.sql(limitsWithTop ? "" : lineBreak + "LIMIT " + limit); + } + + private static void tableName(final TypedStatement.Builder sql, final String tableFqn) { + final String[] parts = FullyQualifiedName.split(tableFqn); + sql.name(FullyQualifiedName.unquoteName(parts[parts.length - 2])) + .sql(".") + .name(FullyQualifiedName.unquoteName(parts[parts.length - 1])); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySettled.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySettled.java new file mode 100644 index 000000000000..2f81b3d2f6b0 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySettled.java @@ -0,0 +1,67 @@ +/* + * 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.ontology; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; + +/** + * What a rule of the shape check compile settles: a value, or the reason a part of a constraint + * has no exact test. A rule that needs several facts asks for them in order with {@link #then}, + * and the first refusal is the answer. + */ +sealed interface OntologySettled { + record Value(T value) implements OntologySettled {} + + record Refused(OntologyShapeCheckReason reason) implements OntologySettled {} + + static OntologySettled of(final T value) { + return new Value<>(value); + } + + static OntologySettled refused(final OntologyShapeCheckReason reason) { + return new Refused<>(reason); + } + + /** The value when {@code holds}, and the refusal otherwise. */ + static OntologySettled when( + final boolean holds, final T value, final OntologyShapeCheckReason otherwise) { + return holds ? of(value) : refused(otherwise); + } + + /** Every value in order, or the first refusal. */ + static OntologySettled> all(final List> settled) { + final List values = new ArrayList<>(); + for (final OntologySettled one : settled) { + if (one instanceof Refused refused) { + return refused(refused.reason()); + } + values.add(((Value) one).value()); + } + return of(List.copyOf(values)); + } + + default OntologySettled then(final Function> next) { + return switch (this) { + case Value found -> next.apply(found.value()); + case Refused refused -> refused(refused.reason()); + }; + } + + default OntologySettled map(final Function change) { + return then(value -> of(change.apply(value))); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCardinalityRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCardinalityRules.java new file mode 100644 index 000000000000..17418f915668 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCardinalityRules.java @@ -0,0 +1,134 @@ +/* + * 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.ontology; + +import static org.openmetadata.service.ontology.OntologySettled.of; +import static org.openmetadata.service.ontology.OntologySettled.refused; +import static org.openmetadata.service.ontology.OntologySettled.when; + +import java.util.List; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.service.ontology.OntologyCheckGates.Records; +import org.openmetadata.service.ontology.OntologyCheckGates.Route; +import org.openmetadata.service.ontology.OntologyCheckProbe.FewerValues; +import org.openmetadata.service.ontology.OntologyCheckProbe.MoreValues; +import org.openmetadata.service.ontology.OntologyCheckProbe.NoRecord; +import org.openmetadata.service.ontology.OntologyCheckProbe.Reach; +import org.openmetadata.service.ontology.OntologyCheckProbe.ReadTable; +import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; +import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Target; + +/** + * How the parts of a constraint that count the values of a property, or ask what a relation + * reaches, are checked at one place: {@code minCount}, {@code maxCount} and {@code class} + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). A data property has a value on a + * record in each row where its column is not null, and a relation where every column of its + * confirmed join is not null. Two rows that hold the same value hold one value. + */ +final class OntologyShapeCardinalityRules { + private OntologyShapeCardinalityRules() {} + + /** + * The values of a property at one place, with the way to them from the records. + * + * @param columns the columns that hold one value together + */ + record Values(Records records, Place place, List> columns, Route route) {} + + static OntologySettled values( + final Records records, final OntologyProperty property, final Place place) { + return OntologyCheckGates.values(property, place) + .then( + columns -> + OntologyCheckGates.route(records, place) + .map(route -> new Values(records, place, columns, route))); + } + + /** Every record has at least {@code count} values, for a count above zero. */ + static OntologySettled atLeast(final int count, final Values values) { + if (count == 1 && isKeyOfRecord(values)) { + return of(new HeldByMapping()); + } + return OntologyCheckGates.reach(values.route()) + .then(reach -> reach.joinsHolder() ? OntologyCheckGates.withOuterJoin(reach) : of(reach)) + .map(reach -> check(values, new FewerValues(reach, values.columns(), count))); + } + + /** Every record has at most {@code count} values. */ + static OntologySettled atMost(final int count, final Values values) { + if (count >= 1 && OntologyDeclaredKeys.oneRowPerKey(values.place().holder())) { + return of(new HeldByMapping()); + } + return OntologyCheckGates.reach(values.route()) + .map(reach -> check(values, new MoreValues(reach, values.columns(), count))); + } + + /** A record is a row with no null in its key, so a value made of key columns is never absent. */ + private static boolean isKeyOfRecord(final Values values) { + return values.place().onIdentity() + && values.records().identity().table().keyPaths().containsAll(values.columns()); + } + + private static OntologyPartOutcome check( + final Values values, final OntologyCheckProbe probe, final MappedTable... others) { + return OntologyCheckGates.check(values.place(), values.columns(), probe, others); + } + + /** + * Every value of a relation at one place is a record of the class the part names. The join must + * arrive at the identity table of that class, and a row there is a record when it passes the + * filter of that binding and has no null in its key. + * + * @param target the class the part names, or null when the version read has no such class + */ + static OntologySettled reaches(final Values values, final Target target) { + return OntologyCheckGates.join(values.place()) + .then(join -> arrival(values, join, target)) + .then( + probe -> + when( + !(target.subclassSharesTable() && probe.target().filter() != null), + probe, + OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE)) + .map(probe -> check(values, probe, target.identity())); + } + + private static OntologySettled arrival( + final Values values, final OntologyColumnJoin join, final Target target) { + final boolean arrives = + target != null + && target.identity() != null + && target.identity().row().assetId().equals(join.getTargetAssetId()); + if (!arrives) { + return refused(OntologyShapeCheckReason.TARGET_CLASS_NOT_ON_JOIN); + } + final List on = + join.getOn().stream().map(pair -> new JoinPair(pair.getChild(), pair.getParent())).toList(); + return OntologyCheckGates.held(target.identity(), on.stream().map(JoinPair::joined).toList()) + .then(parents -> OntologyCheckGates.joined(values.route().identity(), target.identity())) + .then(read -> antiJoin(values, on, read)); + } + + private static OntologySettled antiJoin( + final Values values, final List on, final ReadTable target) { + return OntologyCheckGates.reach(values.route()) + .then(OntologyCheckGates::withOuterJoin) + .map((final Reach reach) -> new NoRecord(reach, on, target)); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java new file mode 100644 index 000000000000..cc106894e7b5 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswer.java @@ -0,0 +1,251 @@ +/* + * 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.ontology; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import org.apache.commons.codec.digest.DigestUtils; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckBinding; +import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyPartOutcome.Check; +import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotEnforceable; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotMapped; +import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; +import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledConstraint; +import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledPart; +import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledShape; +import org.openmetadata.service.ontology.OntologyShapeCheckSql.Statements; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.resources.feeds.MessageParser.EntityLink; + +/** + * Writes the answer a caller gets from what the shape check compile settled + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). The compile is the same for every + * caller. What a caller may not view is masked here, in one step after it. A constraint that rests + * on a table the caller may not view answers {@code hidden} for each part it states, and says + * nothing else about it. A constraint about a property the caller may not view answers the same, + * and does not name the property either. So does a constraint whose {@code class} part names a + * class the caller may not view, which keeps its path because the caller may view the property. + */ +final class OntologyShapeCheckAnswer { + /** The table test that runs a statement written for the check. */ + static final String CUSTOM_SQL = "tableCustomSQLQuery"; + + static final String SQL_EXPRESSION = "sqlExpression"; + static final String STRATEGY = "strategy"; + static final String OPERATOR = "operator"; + static final String THRESHOLD = "threshold"; + + /** The statement returns one number, and the test passes when that number is at most zero. */ + private static final String COUNT = "COUNT"; + + private static final String AT_MOST = "<="; + private static final String NO_VIOLATION = "0"; + + /** No id, part name or column name holds a control character, so these two part them. */ + private static final String FIELD_SEPARATOR = "\u001f"; + + private static final String PATH_SEPARATOR = "\u001e"; + + private final OntologyShapeCheckFacts facts; + private final Hidden hidden; + + private OntologyShapeCheckAnswer(final OntologyShapeCheckFacts facts, final Hidden hidden) { + this.facts = facts; + this.hidden = hidden; + } + + /** + * What the caller may not view of what an answer rests on. + * + * @param tables the ids of the tables that exist and that the caller may not view + * @param paths the IRIs of the properties of the constraints that the caller may not view + * @param classes the IRIs of the classes that the {@code class} parts name and that the caller may + * not view + */ + record Hidden(Set tables, Set paths, Set classes) {} + + /** One generated check with the shape, the constraint and the part it comes from. */ + record Generated( + OntologyShape shape, String constraintId, OntologyShapePart part, OntologyShapeCheck check) {} + + /** + * Every check of the compile, for no caller: nothing is masked. A caller's answer is a view of + * this list, and a step that creates tests reads this one, so it never reads a hidden check as + * absent. + */ + static List generated( + final OntologyShapeCheckFacts facts, final List shapes) { + final OntologyShapeCheckAnswer answer = + new OntologyShapeCheckAnswer(facts, new Hidden(Set.of(), Set.of(), Set.of())); + final List found = new ArrayList<>(); + for (final CompiledShape shape : OntologyShapeCheckCompiler.compile(facts, shapes)) { + for (final CompiledConstraint constraint : shape.constraints()) { + for (final CompiledPart part : constraint.parts()) { + if (part.outcome() instanceof Check checks) { + final Named named = + new Named(shape.shape().getId(), constraint.constraint().getId(), part.part()); + for (final TableCheck test : checks.checks()) { + found.add( + new Generated( + shape.shape(), + named.constraintId(), + named.part(), + answer.check(named, test))); + } + } + } + } + } + return List.copyOf(found); + } + + /** The part of one constraint of one shape that a test checks. */ + private record Named(UUID shapeId, String constraintId, OntologyShapePart part) {} + + /** The answer for each shape, with what the caller may not view masked. */ + static List shapes( + final OntologyShapeCheckFacts facts, final List shapes, final Hidden hidden) { + final OntologyShapeCheckAnswer answer = new OntologyShapeCheckAnswer(facts, hidden); + return OntologyShapeCheckCompiler.compile(facts, shapes).stream().map(answer::shape).toList(); + } + + private OntologyCheckedShape shape(final CompiledShape compiled) { + final OntologyShape shape = compiled.shape(); + return new OntologyCheckedShape() + .withId(shape.getId()) + .withName(shape.getName()) + .withSeverity(shape.getSeverity()) + .withConstraints( + compiled.constraints().stream() + .map(constraint -> constraint(shape.getId(), constraint)) + .toList()); + } + + private OntologyCheckedConstraint constraint(final UUID shapeId, final CompiledConstraint found) { + final String id = found.constraint().getId(); + final URI path = found.constraint().getPath(); + final boolean aboutHiddenProperty = hidden.paths().contains(path); + final boolean masked = + aboutHiddenProperty + || namesHiddenClass(found.constraint()) + || found.rests().stream().anyMatch(hidden.tables()::contains); + return new OntologyCheckedConstraint() + .withId(id) + .withPath(aboutHiddenProperty ? null : path) + .withParts( + masked + ? masked(found.parts()) + : found.parts().stream() + .map(part -> part(new Named(shapeId, id, part.part()), part.outcome())) + .toList()); + } + + private boolean namesHiddenClass(final OntologyShapeConstraint constraint) { + return constraint.getClassIri() != null && hidden.classes().contains(constraint.getClassIri()); + } + + /** One entry for each part, so the number of answers the tables gave is not told either. */ + private static List masked(final List parts) { + return parts.stream() + .map(CompiledPart::part) + .distinct() + .map(part -> entry(part, OntologyShapeCheckOutcome.HIDDEN)) + .toList(); + } + + private OntologyCheckedPart part(final Named named, final OntologyPartOutcome outcome) { + return switch (outcome) { + case Check check -> entry(named.part(), OntologyShapeCheckOutcome.CHECK) + .withChecks(check.checks().stream().map(test -> check(named, test)).toList()); + case HeldByMapping held -> entry(named.part(), OntologyShapeCheckOutcome.HELD_BY_MAPPING); + case NotMapped none -> entry(named.part(), OntologyShapeCheckOutcome.NOT_MAPPED); + case NotEnforceable refused -> entry(named.part(), OntologyShapeCheckOutcome.NOT_ENFORCEABLE) + .withReason(refused.reason()); + }; + } + + private static OntologyCheckedPart entry( + final OntologyShapePart part, final OntologyShapeCheckOutcome outcome) { + return new OntologyCheckedPart().withPart(part).withOutcome(outcome); + } + + /** + * One test as a request to create a test case takes it. Both statements are finished by the + * engine family of the table. The test runs the count in the form with every colon escaped, + * because the runner reads {@code :name} as a parameter. The list of keys is the form a person + * reads. + */ + private OntologyShapeCheck check(final Named named, final TableCheck found) { + final Table table = found.place().holder().table(); + final Statements statements = OntologyShapeCheckSql.write(found.probe()); + final SqlEngineFamily family = found.probe().reach().family(); + return new OntologyShapeCheck() + .withIdentity(identity(named, found)) + .withTable(table.getEntityReference()) + .withColumns(found.columns()) + .withTestDefinition(CUSTOM_SQL) + .withEntityLink(new EntityLink(Entity.TABLE, table.getFullyQualifiedName()).getLinkString()) + .withParameterValues( + List.of( + parameter(SQL_EXPRESSION, family.finish(statements.count()).escapedSql()), + parameter(STRATEGY, COUNT), + parameter(OPERATOR, AT_MOST), + parameter(THRESHOLD, NO_VIOLATION))) + .withInspectionQuery(family.finish(statements.keys()).sql()) + .withReadBindings(found.read().stream().map(this::read).toList()); + } + + private static TestCaseParameterValue parameter(final String name, final String value) { + return new TestCaseParameterValue().withName(name).withValue(value); + } + + /** + * The name of a check. It holds no value of the constraint, so a changed bound keeps the name, + * and it holds the bound column, so two columns of one table are two checks. + */ + private String identity(final Named named, final TableCheck found) { + return DigestUtils.sha256Hex( + String.join( + FIELD_SEPARATOR, + named.shapeId().toString(), + named.constraintId(), + named.part().value(), + facts.subject().id().toString(), + found.place().holder().row().assetId().toString(), + String.join(PATH_SEPARATOR, found.place().binding().getColumnPath()))); + } + + private OntologyShapeCheckBinding read(final BindingRow row) { + return new OntologyShapeCheckBinding() + .withConceptId(row.conceptId()) + .withAssetId(row.assetId()) + .withRevision(facts.revisions().get(row.conceptId())); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckCompiler.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckCompiler.java new file mode 100644 index 000000000000..d7c6df86e067 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckCompiler.java @@ -0,0 +1,298 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.service.ontology.OntologyCheckGates.isRelation; +import static org.openmetadata.service.ontology.OntologySettled.refused; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.api.data.OntologyShapePart; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.service.ontology.OntologyCheckGates.Records; +import org.openmetadata.service.ontology.OntologyPartOutcome.Check; +import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotEnforceable; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotMapped; +import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Subject; + +/** + * Compiles the shapes that target a class into data quality checks on the tables the class binds + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). A constraint is answered part by + * part. A part gets a test only when the test finds a violation exactly when a record of the + * class breaks it. Otherwise the answer says that the mapping already holds the part, that the + * property is not mapped, or why no exact test exists. + * + *

Nothing here reads a database or a policy. The facts are the same for every caller, so the + * answer is too, and what a caller may not view is masked afterwards. + */ +final class OntologyShapeCheckCompiler { + static final int MOST_LISTED_VALUES = 1000; + + /** What each part of a constraint states, in the order the parts are answered. */ + private static final Map> STATED = + stated(); + + private final OntologyShapeCheckFacts facts; + private final OntologySettled records; + + private OntologyShapeCheckCompiler(final OntologyShapeCheckFacts facts) { + this.facts = facts; + this.records = OntologyCheckGates.records(facts.subject()); + } + + record CompiledShape(OntologyShape shape, List constraints) {} + + /** + * One constraint with the answer for each part it states. + * + * @param rests the ids of the tables the answer rests on: the identity table of the class, each + * table that binds the property, and each table a join of the property arrives at + * @param parts one entry for each part, or one for each different answer when the tables that + * hold the property do not agree + */ + record CompiledConstraint( + OntologyShapeConstraint constraint, Set rests, List parts) {} + + record CompiledPart(OntologyShapePart part, OntologyPartOutcome outcome) {} + + /** One constraint with its property as the version declares it and the records of the class. */ + private record Asked( + OntologyShapeConstraint constraint, OntologyProperty property, Records records) {} + + static List compile( + final OntologyShapeCheckFacts facts, final List shapes) { + final OntologyShapeCheckCompiler compiler = new OntologyShapeCheckCompiler(facts); + return shapes.stream() + .map( + shape -> + new CompiledShape( + shape, + listOrEmpty(shape.getConstraints()).stream() + .map(compiler::constraint) + .toList())) + .toList(); + } + + private static Map> stated() { + final Map> stated = + new EnumMap<>(OntologyShapePart.class); + stated.put(OntologyShapePart.MIN_COUNT, OntologyShapeConstraint::getMinCount); + stated.put(OntologyShapePart.MAX_COUNT, OntologyShapeConstraint::getMaxCount); + stated.put(OntologyShapePart.CLASS, OntologyShapeConstraint::getClassIri); + stated.put(OntologyShapePart.DATATYPE, OntologyShapeConstraint::getDatatypeIri); + stated.put( + OntologyShapePart.RANGE, + constraint -> + constraint.getMinInclusive() == null + ? constraint.getMaxInclusive() + : constraint.getMinInclusive()); + stated.put(OntologyShapePart.IN, OntologyShapeConstraint::getIn); + stated.put(OntologyShapePart.PATTERN, OntologyShapeConstraint::getPattern); + return stated; + } + + private CompiledConstraint constraint(final OntologyShapeConstraint constraint) { + final OntologyProperty property = facts.properties().get(constraint.getPath()); + final List places = + property == null ? List.of() : facts.subject().places(property.getId()); + final List parts = new ArrayList<>(); + STATED.forEach( + (part, value) -> { + if (value.apply(constraint) != null) { + answers(part, constraint, property, places) + .forEach(outcome -> parts.add(new CompiledPart(part, outcome))); + } + }); + return new CompiledConstraint(constraint, rests(property), List.copyOf(parts)); + } + + /** + * A table with no role is among them when it binds the property, because the answer says that + * the class binds the property there. + */ + private Set rests(final OntologyProperty property) { + final Set rests = new LinkedHashSet<>(); + final Subject subject = facts.subject(); + subject.identity().ifPresent(identity -> rests.add(identity.row().assetId())); + final List bindings = + property == null ? List.of() : subject.bindings(property.getId()); + for (final Place place : bindings) { + rests.add(place.holder().row().assetId()); + if (place.binding().getJoin() != null + && place.binding().getJoin().getTargetAssetId() != null) { + rests.add(place.binding().getJoin().getTargetAssetId()); + } + } + return rests; + } + + private List answers( + final OntologyShapePart part, + final OntologyShapeConstraint constraint, + final OntologyProperty property, + final List places) { + if (property == null) { + return List.of(new NotMapped()); + } + if (places.isEmpty()) { + return List.of(unmapped(property)); + } + if (part == OntologyShapePart.MIN_COUNT && constraint.getMinCount() == 0) { + return List.of(new HeldByMapping()); + } + return switch (records) { + case OntologySettled.Refused none -> List.of(new NotEnforceable(none.reason())); + case OntologySettled.Value found -> merged( + settled(part, new Asked(constraint, property, found.value()), places)); + }; + } + + /** + * The answer for a property that no identity or contributing table of the class holds. A table + * with no role holds no value of a record, so a class that binds the property only there has + * the property and no records to check it on. + */ + private OntologyPartOutcome unmapped(final OntologyProperty property) { + final Subject subject = facts.subject(); + if (subject.binds(property.getId())) { + return subject.identity().isEmpty() + ? new NotEnforceable(OntologyShapeCheckReason.NO_IDENTITY_TABLE) + : new NotMapped(); + } + return isRelation(property) && facts.boundOnInverse().contains(property.getId()) + ? new NotEnforceable(OntologyShapeCheckReason.BOUND_ON_INVERSE) + : new NotMapped(); + } + + private List> settled( + final OntologyShapePart part, final Asked asked, final List places) { + final OntologyShapeConstraint constraint = asked.constraint(); + final Records found = asked.records(); + return switch (part) { + case MIN_COUNT, MAX_COUNT -> List.of(counted(part, asked, places)); + case CLASS -> eachRelation(asked, places); + case DATATYPE -> eachData( + asked, + places, + place -> OntologyShapeValueRules.datatype(constraint.getDatatypeIri(), place)); + case RANGE -> eachData( + asked, places, place -> OntologyShapeValueRules.range(constraint, found, place)); + case IN -> listed(asked, places); + case PATTERN -> eachData( + asked, + places, + place -> OntologyShapeValueRules.pattern(constraint.getPattern(), found, place)); + }; + } + + /** A count over several columns is a count over all of them at once, which no test makes. */ + private static OntologySettled counted( + final OntologyShapePart part, final Asked asked, final List places) { + if (places.size() > 1) { + return refused(OntologyShapeCheckReason.SEVERAL_TABLES); + } + final OntologyShapeConstraint constraint = asked.constraint(); + return OntologyShapeCardinalityRules.values( + asked.records(), asked.property(), places.getFirst()) + .then( + values -> + part == OntologyShapePart.MIN_COUNT + ? OntologyShapeCardinalityRules.atLeast(constraint.getMinCount(), values) + : OntologyShapeCardinalityRules.atMost(constraint.getMaxCount(), values)); + } + + private List> eachRelation( + final Asked asked, final List places) { + if (!isRelation(asked.property())) { + return List.of(refused(OntologyShapeCheckReason.NOT_A_RELATION)); + } + return places.stream() + .map( + place -> + OntologyShapeCardinalityRules.values(asked.records(), asked.property(), place) + .then( + values -> + OntologyShapeCardinalityRules.reaches( + values, facts.targets().get(asked.constraint().getClassIri())))) + .toList(); + } + + private static List> eachData( + final Asked asked, + final List places, + final Function> rule) { + return isRelation(asked.property()) + ? List.of(refused(OntologyShapeCheckReason.NOT_A_DATA_PROPERTY)) + : places.stream().map(rule).toList(); + } + + /** A list that names a record compares records, and a column holds no record to compare. */ + private static List> listed( + final Asked asked, final List places) { + final List list = listOrEmpty(asked.constraint().getIn()); + if (list.stream().anyMatch(item -> item.getIri() != null)) { + return List.of(refused(OntologyShapeCheckReason.VALUES_ARE_RECORDS)); + } + if (list.size() > MOST_LISTED_VALUES) { + return List.of(refused(OntologyShapeCheckReason.TOO_MANY_VALUES)); + } + return eachData( + asked, places, place -> OntologyShapeValueRules.in(list, asked.records(), place)); + } + + /** + * One entry when every table gives the same answer: the tests of all of them together, or the + * one answer they share. Otherwise the tests first, then each other answer once. + */ + private static List merged( + final List> settled) { + final List outcomes = + settled.stream().map(OntologyShapeCheckCompiler::outcome).toList(); + final List checks = + outcomes.stream() + .filter(Check.class::isInstance) + .flatMap(outcome -> ((Check) outcome).checks().stream()) + .toList(); + final List merged = new ArrayList<>(); + if (!checks.isEmpty()) { + merged.add(new Check(checks)); + } + outcomes.stream() + .filter(outcome -> !(outcome instanceof Check)) + .distinct() + .forEach(merged::add); + return List.copyOf(merged); + } + + private static OntologyPartOutcome outcome(final OntologySettled settled) { + return switch (settled) { + case OntologySettled.Value found -> found.value(); + case OntologySettled.Refused none -> new NotEnforceable(none.reason()); + }; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckFacts.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckFacts.java new file mode 100644 index 000000000000..2354f57f3b72 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckFacts.java @@ -0,0 +1,106 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Stream; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; + +/** + * Everything the shape check compile reads, as plain values + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). Every table is here whether or not + * the caller may view it, because the compile is the same for every caller and what a caller may + * not view is masked after it. + * + * @param properties the properties of the ontology version that the shapes name, by IRI, with the + * property each relation declares as its inverse + * @param targets the classes of that version that a {@code class} part names, by IRI + * @param boundOnInverse the ids of the relations whose declared inverse a class of the domain of + * that inverse binds + * @param revisions the binding revision of every class whose bindings were read, by class id + */ +record OntologyShapeCheckFacts( + Subject subject, + Map properties, + Map targets, + Set boundOnInverse, + Map revisions) { + + /** + * The class whose shapes are compiled. + * + * @param tables every table the class binds that exists, the identity table first + */ + record Subject(UUID id, URI iri, List tables) { + Optional identity() { + return tables.stream() + .filter(table -> table.row().role() == OntologyBindingRole.IDENTITY) + .findFirst(); + } + + /** + * Where the records of the class hold the values of a property: each column of the identity + * table and of the contributing tables that the property is bound to, the identity table + * first. A table with no role defines no record and adds nothing to one. + */ + List places(final UUID propertyId) { + return tables.stream() + .filter(table -> table.row().role() != null) + .flatMap(table -> bound(table, propertyId)) + .toList(); + } + + /** Every column the class binds the property to, in a table of any role or of none. */ + List bindings(final UUID propertyId) { + return tables.stream().flatMap(table -> bound(table, propertyId)).toList(); + } + + /** True when the class binds the property in a column of any table, whatever its role. */ + boolean binds(final UUID propertyId) { + return !bindings(propertyId).isEmpty(); + } + + private static Stream bound(final MappedTable table, final UUID propertyId) { + return listOrEmpty(table.row().columns()).stream() + .filter(binding -> propertyId.equals(binding.getPropertyId())) + .map(binding -> new Place(table, binding)); + } + } + + /** One column of one table that a property is bound to. */ + record Place(MappedTable holder, OntologyColumnBinding binding) { + boolean onIdentity() { + return holder.row().role() == OntologyBindingRole.IDENTITY; + } + } + + /** + * A class that a {@code class} part names. + * + * @param identity its identity table, or null when it has none or the table no longer exists + * @param subclassSharesTable true when a subclass of the class has its identity table on the + * same table + */ + record Target(UUID id, MappedTable identity, boolean subclassSharesTable) {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java new file mode 100644 index 000000000000..fa8a97c5508b --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckReader.java @@ -0,0 +1,423 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.service.ontology.OntologyRecordMapping.conflict; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyBindingAccess.TableViews; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyShapeCheckAnswer.Hidden; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Subject; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Target; + +/** + * Reads what the shape check compile needs + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). Each kind is read once for the + * whole answer, whatever the number of shapes and constraints. The kinds are the shapes that + * target the class, the properties their constraints are about, the classes their {@code class} + * parts name, the binding rows between two reads of the binding revisions, and the tables those + * rows name. + * + *

The caller's right to view is checked once for the shapes, once for the properties, once for + * the classes that {@code class} parts name and once for the tables. A shape that the caller may not view is left out before anything is read for + * it. A property and a table are read whoever asks, because the compile is the same for every + * caller, and what the caller may not view of them is masked afterwards. + * + *

Two questions cost further reads, and only when a constraint asks them. A relation that the + * class binds nowhere is looked for on its declared inverse. A class that a {@code class} part + * names, and whose identity binding has a row filter, is checked for a subclass with an identity + * binding on the same table. + */ +final class OntologyShapeCheckReader { + /** An answer reads at most this many table bindings of the class, whatever their role. */ + static final int MOST_TABLES = OntologyConceptQueryService.TABLE_BINDINGS_READ; + + private static final int BINDING_READ_ATTEMPTS = 3; + + /** The rows of each class that can hold the inverse of a relation: one statement reads them. */ + private static final int JOIN_HOLDERS_READ = OntologyMappingReader.MAX_CONTRIBUTING_TABLES + 1; + + /** The classes bound to one table that are looked at for a subclass of a class. */ + private static final int MOST_CLASSES_ON_A_TABLE = 100; + + private final OntologyConceptBindingStore store; + private final OntologyBindingAccess catalog; + + OntologyShapeCheckReader( + final OntologyConceptBindingStore store, final OntologyBindingAccess catalog) { + this.store = store; + this.catalog = catalog; + } + + /** The class an answer is about, in the version that is read. */ + record Asked(UUID id, URI iri, UUID ontologyId, OntologyVersion version) {} + + /** + * Everything one answer reads. + * + * @param shapes the shapes that target the class and that the caller may view, in name order + */ + record Read(List shapes, OntologyShapeCheckFacts facts, Hidden hidden) {} + + /** + * The binding rows of one answer. + * + * @param subject the table rows of the class, its identity table first + * @param targets the identity table row of each class a {@code class} part names, by class id + */ + private record Rows( + Map revisions, List subject, Map targets) {} + + /** + * What the rows of other classes say about the class. + * + * @param inverseHolders the tables that bind the declared inverse of a relation, by the id of + * the relation, for each relation the class binds nowhere + * @param sharing the ids of the classes a {@code class} part names that have a subclass with an + * identity binding on their own identity table + */ + private record Others(Map> inverseHolders, Set sharing) {} + + Read read(final Access access, final Asked asked) { + final List shapes = shapes(access, asked); + final Map properties = + byIri( + asked + .version() + .propertiesNamed( + store, asked.ontologyId(), named(shapes, OntologyShapeConstraint::getPath)), + OntologyProperty::getIri); + final Map classes = + byIri( + asked + .version() + .classesNamed( + store, asked.ontologyId(), named(shapes, OntologyShapeConstraint::getClassIri)), + OntologyConcept::getIri); + final Rows rows = rows(asked, classes.values().stream().map(OntologyConcept::getId).toList()); + final Others others = + new Others( + inverseHolders(asked, properties.values(), rows.subject()), + sharing(asked, classes.values(), rows.targets())); + final TableViews tables = catalog.tableViews(access, assets(rows, others)); + return new Read( + shapes, + new OntologyShapeCheckFacts( + subject(asked, rows, tables), + properties, + targets(classes, rows, others, tables), + boundOnInverse(others, tables), + rows.revisions()), + new Hidden( + hidden(tables), + hiddenIris(access, asked, Entity.ONTOLOGY_PROPERTY, properties), + hiddenIris(access, asked, Entity.ONTOLOGY_CONCEPT, classes))); + } + + private List shapes(final Access access, final Asked asked) { + final List targeting = + asked.version().shapesTargeting(store, asked.ontologyId(), asked.iri()); + final Set viewable = + asked.version().viewable(catalog, access, Entity.ONTOLOGY_SHAPE, targeting); + return targeting.stream() + .filter(shape -> viewable.contains(shape.getId())) + .sorted(Comparator.comparing(OntologyShape::getName).thenComparing(OntologyShape::getId)) + .toList(); + } + + /** + * The IRIs among {@code definitions} that the caller may not view, judged on the definitions as + * this version holds them. One batch answers for all of one type. + */ + private Set hiddenIris( + final Access access, + final Asked asked, + final String entityType, + final Map definitions) { + final Set viewable = + asked.version().viewable(catalog, access, entityType, List.copyOf(definitions.values())); + return definitions.entrySet().stream() + .filter(definition -> !viewable.contains(definition.getValue().getId())) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + } + + /** The IRIs that the constraints of the shapes name in one of their fields. */ + private static Set named( + final List shapes, final Function field) { + return shapes.stream() + .flatMap(shape -> listOrEmpty(shape.getConstraints()).stream()) + .map(field) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + private static Map byIri(final List definitions, final Function iri) { + final Map byIri = new LinkedHashMap<>(); + definitions.forEach(definition -> byIri.putIfAbsent(iri.apply(definition), definition)); + return byIri; + } + + /** + * Reads the binding rows between two reads of the binding revisions. A binding write commits its + * rows and its revision in one transaction, so two equal revision reads mean that no write + * landed between them, and every row belongs to the revision that is returned with it. + */ + private Rows rows(final Asked asked, final List targets) { + final Set classes = new LinkedHashSet<>(targets); + classes.add(asked.id()); + for (int attempt = 0; attempt < BINDING_READ_ATTEMPTS; attempt++) { + final Map revisions = store.revisions(classes); + final List subject = + store.identityFirstTables(List.of(asked.id()), MOST_TABLES + 1); + final Map identity = + store.identityRows(targets).stream() + .collect(Collectors.toMap(BindingRow::conceptId, Function.identity())); + if (revisions.equals(store.revisions(classes))) { + return new Rows(revisions, identityFirst(asked, subject), identity); + } + } + throw conflict("The table bindings changed while the answer was built. Ask again"); + } + + /** + * A class that binds more tables than one answer reads gets no answer, because a binding left + * out could hold a property and change what a count over its values must read. + */ + private static List identityFirst(final Asked asked, final List rows) { + if (rows.size() > MOST_TABLES) { + throw conflict("Class %s binds more than %d tables", asked.iri(), MOST_TABLES); + } + return rows.stream() + .sorted(Comparator.comparing(row -> row.role() != OntologyBindingRole.IDENTITY)) + .toList(); + } + + /** + * For each relation of the constraints that the class binds in no table, the tables in which a + * class of the domain of its declared inverse, or of its own range, binds that inverse. Only an + * identity table or a contributing table counts, as only those hold a join that is read. + */ + private Map> inverseHolders( + final Asked asked, + final Collection properties, + final List subject) { + final List unbound = + properties.stream().filter(property -> isUnboundWithInverse(property, subject)).toList(); + if (unbound.isEmpty()) { + return Map.of(); + } + final Map inverses = + byIri( + asked + .version() + .propertiesNamed( + store, + asked.ontologyId(), + unbound.stream().map(OntologyProperty::getInverse).distinct().toList()), + OntologyProperty::getIri); + final List rows = + store.joinHolderTables( + classIds(asked, unbound.stream().flatMap(relation -> ends(relation, inverses))), + JOIN_HOLDERS_READ); + final Map> holders = new HashMap<>(); + for (final OntologyProperty relation : unbound) { + final OntologyProperty inverse = inverses.get(relation.getInverse()); + if (inverse != null && inverse.getKind() == OntologyPropertyKind.OBJECT) { + holders.put(relation.getId(), binding(rows, inverse.getId())); + } + } + return holders; + } + + private static boolean isUnboundWithInverse( + final OntologyProperty property, final List subject) { + return property.getKind() == OntologyPropertyKind.OBJECT + && property.getInverse() != null + && !property.getInverse().equals(property.getIri()) + && binding(subject, property.getId()).isEmpty(); + } + + /** The classes that can bind the inverse of a relation: its domain, or the range of the relation. */ + private static Stream ends( + final OntologyProperty relation, final Map inverses) { + final OntologyProperty inverse = inverses.get(relation.getInverse()); + return inverse == null + ? Stream.empty() + : Stream.concat( + listOrEmpty(inverse.getDomain()).stream(), listOrEmpty(relation.getRange()).stream()); + } + + private List classIds(final Asked asked, final Stream iris) { + return asked + .version() + .classesNamed(store, asked.ontologyId(), iris.distinct().toList()) + .stream() + .map(OntologyConcept::getId) + .toList(); + } + + /** The ids of the tables among {@code rows} that bind the property in a column. */ + private static Set binding(final List rows, final UUID propertyId) { + return rows.stream() + .filter( + row -> + listOrEmpty(row.columns()).stream() + .map(OntologyColumnBinding::getPropertyId) + .anyMatch(propertyId::equals)) + .map(BindingRow::assetId) + .collect(Collectors.toSet()); + } + + /** + * The classes of the {@code class} parts whose records a test would cut short: the identity + * binding has a row filter, and a subclass has its identity binding on the same table. A table + * that more classes bind than are looked at counts as shared, which only ever withholds a test. + */ + private Set sharing( + final Asked asked, + final Collection classes, + final Map identity) { + final List filtered = + classes.stream() + .filter(type -> identity.get(type.getId()) != null) + .filter(type -> identity.get(type.getId()).rowFilter() != null) + .toList(); + final Map> byTable = + store + .firstForAssets( + filtered.stream().map(type -> identity.get(type.getId()).assetId()).toList(), + MOST_CLASSES_ON_A_TABLE + 1) + .stream() + .collect(Collectors.groupingBy(BindingRow::assetId)); + final Set sharing = new HashSet<>(); + final Map> asking = new HashMap<>(); + for (final OntologyConcept type : filtered) { + final List onTable = + byTable.getOrDefault(identity.get(type.getId()).assetId(), List.of()); + if (onTable.size() > MOST_CLASSES_ON_A_TABLE) { + sharing.add(type.getId()); + } else { + final List others = identityOthers(onTable, type.getId()); + if (!others.isEmpty()) { + asking.put(type.getIri(), others); + } + } + } + final Set subclassed = + asking.isEmpty() + ? Set.of() + : asked.version().withSubclassAmong(store, asked.ontologyId(), asking); + filtered.stream() + .filter(type -> subclassed.contains(type.getIri())) + .forEach(type -> sharing.add(type.getId())); + return sharing; + } + + private static List identityOthers(final List onTable, final UUID self) { + return onTable.stream() + .filter(other -> other.role() == OntologyBindingRole.IDENTITY) + .map(BindingRow::conceptId) + .filter(id -> !id.equals(self)) + .toList(); + } + + /** The id of every table an answer can rest on or name. */ + private static Set assets(final Rows rows, final Others others) { + final Set assets = new LinkedHashSet<>(); + for (final BindingRow row : rows.subject()) { + assets.add(row.assetId()); + listOrEmpty(row.columns()).stream() + .map(OntologyColumnBinding::getJoin) + .filter(join -> join != null && join.getTargetAssetId() != null) + .forEach(join -> assets.add(join.getTargetAssetId())); + } + rows.targets().values().forEach(row -> assets.add(row.assetId())); + others.inverseHolders().values().forEach(assets::addAll); + return assets; + } + + /** A binding whose table no longer exists is no binding of the class here. */ + private static Subject subject(final Asked asked, final Rows rows, final TableViews tables) { + final List mapped = new ArrayList<>(); + for (final BindingRow row : rows.subject()) { + if (tables.live().containsKey(row.assetId())) { + mapped.add(new MappedTable(tables.live().get(row.assetId()), row)); + } + } + return new Subject(asked.id(), asked.iri(), List.copyOf(mapped)); + } + + private static Map targets( + final Map classes, + final Rows rows, + final Others others, + final TableViews tables) { + final Map targets = new HashMap<>(); + classes.forEach( + (iri, type) -> { + final BindingRow row = rows.targets().get(type.getId()); + final boolean held = row != null && tables.live().containsKey(row.assetId()); + targets.put( + iri, + new Target( + type.getId(), + held ? new MappedTable(tables.live().get(row.assetId()), row) : null, + others.sharing().contains(type.getId()))); + }); + return targets; + } + + private static Set boundOnInverse(final Others others, final TableViews tables) { + return others.inverseHolders().entrySet().stream() + .filter(holders -> holders.getValue().stream().anyMatch(tables.live()::containsKey)) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + } + + private static Set hidden(final TableViews tables) { + return tables.live().keySet().stream() + .filter(id -> !tables.viewable().contains(id)) + .collect(Collectors.toSet()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckSql.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckSql.java new file mode 100644 index 000000000000..9700cac3d9e3 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeCheckSql.java @@ -0,0 +1,272 @@ +/* + * 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.ontology; + +import static org.openmetadata.service.ontology.OntologyConceptSqlGenerator.alias; +import static org.openmetadata.service.ontology.OntologyConceptSqlGenerator.equalColumns; + +import java.util.List; +import org.openmetadata.service.ontology.OntologyCheckProbe.FewerValues; +import org.openmetadata.service.ontology.OntologyCheckProbe.MoreValues; +import org.openmetadata.service.ontology.OntologyCheckProbe.NoRecord; +import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideList; +import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideRange; +import org.openmetadata.service.ontology.OntologyCheckProbe.Reach; +import org.openmetadata.service.ontology.OntologyCheckProbe.ReadTable; +import org.openmetadata.service.ontology.OntologyCheckProbe.Unmatched; +import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; +import org.openmetadata.service.ontology.sql.TypedStatement; + +/** + * Writes the statements of a test from its probe + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). One statement lists the keys of + * the records in violation, and the other counts the rows of that list. Both start from the + * identity table of the class and keep only its records, so a row that is no record is never + * counted, and a record is counted once however many rows hold it. + */ +final class OntologyShapeCheckSql { + private static final String IDENTITY = alias(0); + private static final String HOLDER = alias(1); + private static final String VALUES = "k"; + private static final String VIOLATIONS = "c"; + private static final String COUNT = "COUNT(*) AS violations"; + private static final String DISTINCT = "DISTINCT "; + private static final String INNER_JOIN = "JOIN"; + private static final String LEFT_JOIN = "LEFT JOIN"; + private static final String AND = " AND "; + private static final String IS_NOT_NULL = " IS NOT NULL"; + + /** The Postgres collation that compares by code point and folds nothing. */ + private static final String CODE_POINT_COLLATION = "C"; + + private OntologyShapeCheckSql() {} + + /** + * The statements of one test. + * + * @param count one row with one number: the records in violation + * @param keys one row for each record in violation, with its key + */ + record Statements(TypedStatement count, TypedStatement keys) {} + + /** One list of keys while it is written. */ + private static final class Draft { + private final Reach reach; + private final TypedStatement.Builder sql = TypedStatement.builder(); + private final OntologySelectText select; + + /** The alias of the table that holds the property. */ + private final String holder; + + Draft(final Reach reach) { + this.reach = reach; + this.select = new OntologySelectText(sql, reach.family().dialect()); + this.holder = reach.joinsHolder() ? HOLDER : IDENTITY; + } + + List> key() { + return reach.identity().table().keyPaths(); + } + } + + static Statements write(final OntologyCheckProbe probe) { + final TypedStatement keys = keys(probe); + final TypedStatement.Builder count = TypedStatement.builder(); + final OntologySelectText select = + new OntologySelectText(count, probe.reach().family().dialect()); + select.selectAll().sql(COUNT); + select.fromStatement(keys, VIOLATIONS); + return new Statements(count.build(), keys); + } + + private static TypedStatement keys(final OntologyCheckProbe probe) { + final Draft draft = new Draft(probe.reach()); + switch (probe) { + case FewerValues fewer -> fewerValues(draft, fewer); + case MoreValues more -> moreValues(draft, more); + case OutsideList outside -> outsideList(draft, outside); + case OutsideRange outside -> outsideRange(draft, outside); + case Unmatched unmatched -> unmatched(draft, unmatched); + case NoRecord none -> noRecord(draft, none); + } + return draft.sql.build(); + } + + /** + * Every record is kept, with or without a row that holds a value, and a record has one row for + * each different value. A value is a row whose value columns are all non-null. + */ + private static void fewerValues(final Draft draft, final FewerValues probe) { + final OntologySelectText values = distinctValues(draft, probe.columns(), LEFT_JOIN); + records(values, draft); + final TypedStatement.Builder having = grouped(draft).sql("SUM(CASE WHEN "); + for (int index = 0; index < probe.columns().size(); index++) { + having.sql((index == 0 ? "" : AND) + VALUES + ".v" + index + IS_NOT_NULL); + } + having.sql(" THEN 1 ELSE 0 END) < " + probe.count()); + } + + /** Only the records with a value are kept, with one row for each different value. */ + private static void moreValues(final Draft draft, final MoreValues probe) { + final OntologySelectText values = distinctValues(draft, probe.columns(), INNER_JOIN); + records(values, draft); + probe.columns().forEach(column -> values.where().column(draft.holder, column).sql(IS_NOT_NULL)); + grouped(draft).sql("COUNT(*) > " + probe.count()); + } + + /** + * Opens the list of keys over a derived table of the different values of each record, and + * returns the writer of that table after its {@code FROM}. + */ + private static OntologySelectText distinctValues( + final Draft draft, final List> columns, final String join) { + keyList(draft.select.selectAll(), draft, false); + final OntologySelectText values = draft.select.fromDistinct(draft.reach.family().dialect()); + keyList(draft.sql, draft, true); + for (int index = 0; index < columns.size(); index++) { + draft.sql.sql(", ").column(draft.holder, columns.get(index)).sql(" AS v" + index); + } + from(values, draft, join); + return values; + } + + /** Closes the derived table of values and groups its rows by record, ready for the test. */ + private static TypedStatement.Builder grouped(final Draft draft) { + draft.select.closeDerived(VALUES); + keyList(draft.select.clause("GROUP BY"), draft, false); + return draft.select.clause("HAVING"); + } + + /** + * The key columns: read from the identity table and named {@code k0}, {@code k1} and so on, or + * read back under those names from the derived table of values. + */ + private static void keyList( + final TypedStatement.Builder sql, final Draft draft, final boolean fromIdentity) { + final List> key = draft.key(); + for (int part = 0; part < key.size(); part++) { + sql.sql(part == 0 ? "" : ", "); + if (fromIdentity) { + sql.column(IDENTITY, key.get(part)).sql(" AS k" + part); + } else { + sql.sql(VALUES + ".k" + part); + } + } + } + + private static void outsideList(final Draft draft, final OutsideList probe) { + final TypedStatement.Builder value = valueOfRecords(draft, probe.column()); + if (probe.allowed().isEmpty()) { + value.sql(IS_NOT_NULL); + } else { + value.sql(" NOT IN ").values(probe.allowed()); + } + } + + private static void outsideRange(final Draft draft, final OutsideRange probe) { + final boolean both = probe.min().isPresent() && probe.max().isPresent(); + final TypedStatement.Builder where = recordsWithHolder(draft).where().sql(both ? "(" : ""); + probe.min().ifPresent(min -> where.column(draft.holder, probe.column()).sql(" < ").value(min)); + where.sql(both ? " OR " : ""); + probe.max().ifPresent(max -> where.column(draft.holder, probe.column()).sql(" > ").value(max)); + where.sql(both ? ")" : ""); + } + + /** + * A null matches nothing and fails nothing, so it is no violation. The value is matched as text + * under the {@code C} collation: a {@code citext} column would fold case, an enumerated type has + * no match operator, and a nondeterministic collation refuses a regular expression. + */ + private static void unmatched(final Draft draft, final Unmatched probe) { + recordsWithHolder(draft) + .where() + .sql("NOT (CAST(") + .column(draft.holder, probe.column()) + .sql(" AS text) COLLATE ") + .name(CODE_POINT_COLLATION) + .sql(" ~ ") + .value(probe.pattern()) + .sql(")"); + } + + /** The keys of the records, ready for a test of one column of the table that holds it. */ + private static TypedStatement.Builder valueOfRecords( + final Draft draft, final List column) { + return recordsWithHolder(draft).where().column(draft.holder, column); + } + + /** The different keys of the records, each joined to the rows that hold the property. */ + private static OntologySelectText recordsWithHolder(final Draft draft) { + keyList(draft.select.selectAll().sql(DISTINCT), draft, true); + from(draft.select, draft, INNER_JOIN); + records(draft.select, draft); + return draft.select; + } + + /** + * A value that no record of the target class has: the join onto the identity table of that + * class finds no row that its row filter keeps and whose key holds no null. + */ + private static void noRecord(final Draft draft, final NoRecord probe) { + final String target = alias(draft.reach.joinsHolder() ? 2 : 1); + keyList(draft.select.selectAll().sql(DISTINCT), draft, true); + from(draft.select, draft, INNER_JOIN); + targetRecords(draft, probe, target); + records(draft.select, draft); + probe + .on() + .forEach( + pair -> draft.select.where().column(draft.holder, pair.previous()).sql(IS_NOT_NULL)); + draft.select.where().column(target, probe.on().getFirst().joined()).sql(" IS NULL"); + } + + private static void targetRecords(final Draft draft, final NoRecord probe, final String alias) { + final ReadTable target = probe.target(); + final TypedStatement.Builder on = + draft.select.join(LEFT_JOIN, target.table().fullyQualifiedName(), alias); + equalColumns(on, probe.on(), draft.holder, alias); + if (target.filter() != null) { + target.filter().appendTo(on.sql(AND), alias); + } + final List> joined = probe.on().stream().map(JoinPair::joined).toList(); + // A key column that the join compares is non-null in every row the join finds. + target.table().keyPaths().stream() + .filter(part -> !joined.contains(part)) + .forEach(part -> on.sql(AND).column(alias, part).sql(IS_NOT_NULL)); + } + + /** The identity table, then the table that holds the property when that is another table. */ + private static void from(final OntologySelectText select, final Draft draft, final String join) { + final Reach reach = draft.reach; + select.from(reach.identity().table().fullyQualifiedName(), IDENTITY); + if (reach.joinsHolder()) { + final ReadTable holder = reach.holder(); + final TypedStatement.Builder on = + select.join(join, holder.table().fullyQualifiedName(), HOLDER); + equalColumns(on, reach.keyPairs(), IDENTITY, HOLDER); + if (holder.filter() != null) { + holder.filter().appendTo(on.sql(AND), HOLDER); + } + } + } + + /** Only the rows of the identity table that are records. */ + private static void records(final OntologySelectText select, final Draft draft) { + final ReadTable identity = draft.reach.identity(); + draft.key().forEach(part -> select.where().column(IDENTITY, part).sql(IS_NOT_NULL)); + if (identity.filter() != null) { + identity.filter().appendTo(select.where(), IDENTITY); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeRules.java new file mode 100644 index 000000000000..dc1e62d95af3 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeRules.java @@ -0,0 +1,228 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyProfileViolation; +import org.openmetadata.schema.type.OntologyProfileViolationCode; +import org.openmetadata.schema.type.OntologyProfileViolationSeverity; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.exception.BadRequestException; + +/** + * The checks a shape passes on its own, without the ontology it belongs to: identity of its + * constraints, the supported constraint set, and values that cannot be satisfied. Whether the + * classes and properties it names exist is a question for a release. + */ +public final class OntologyShapeRules { + /** Constraints one shape holds; a class with more is described by several shapes. */ + public static final int MAX_CONSTRAINTS = 200; + + private static final Pattern CONSTRAINT_ID = Pattern.compile("^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$"); + + private OntologyShapeRules() {} + + public static List validate(final OntologyShape shape) { + final List findings = new ArrayList<>(); + requireAbsolute(findings, shape.getTargetConcept(), "/targetConcept"); + final Set ids = new HashSet<>(); + final List constraints = listOrEmpty(shape.getConstraints()); + if (constraints.size() > MAX_CONSTRAINTS) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + "/constraints", + "A shape holds at most " + MAX_CONSTRAINTS + " constraints: " + constraints.size()); + return findings; + } + for (int index = 0; index < constraints.size(); index++) { + final OntologyShapeConstraint constraint = constraints.get(index); + final String path = "/constraints/" + index; + if (constraint == null) { + add(findings, OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, path, "Empty entry"); + } else { + validate(findings, constraint, path, ids); + } + } + return findings; + } + + /** + * The checks a save runs. The constraint count is checked first, so the size of a shape that is + * rejected for its count is never measured. + */ + public static void requireValid(final OntologyShape shape) { + final List findings = validate(shape); + if (!findings.isEmpty()) { + final OntologyProfileViolation first = findings.getFirst(); + throw new BadRequestException(first.getPath() + ": " + first.getMessage()); + } + requireWithinMemberSize(shape); + } + + /** The member limit every other definition meets when it is saved, so capture never meets more. */ + private static void requireWithinMemberSize(final OntologyShape shape) { + final int bytes = JsonUtils.pojoToJson(shape).getBytes(StandardCharsets.UTF_8).length; + if (bytes > OntologyReleaseManifest.MAX_MEMBER_BYTES) { + throw new BadRequestException("An ontology definition exceeds the 1 MiB member limit"); + } + } + + private static void validate( + final List findings, + final OntologyShapeConstraint constraint, + final String path, + final Set ids) { + if (constraint.getId() == null || !CONSTRAINT_ID.matcher(constraint.getId()).matches()) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + path + "/id", + "A constraint id is 1 to 64 letters, digits, '_', '.' or '-', starting with a letter or digit"); + } else if (!ids.add(constraint.getId())) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + path + "/id", + "A constraint id is unique within its shape: " + constraint.getId()); + } + requireAbsolute(findings, constraint.getPath(), path + "/path"); + requireAbsolute(findings, constraint.getClassIri(), path + "/classIri"); + requireAbsolute(findings, constraint.getDatatypeIri(), path + "/datatypeIri"); + if (!carriesAConstraint(constraint)) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + path, + "A constraint states at least one of minCount, maxCount, classIri, datatypeIri, minInclusive, maxInclusive, in or pattern"); + } + validateCardinality(findings, constraint, path); + validateValues(findings, constraint, path); + validatePattern(findings, constraint, path); + } + + private static boolean carriesAConstraint(final OntologyShapeConstraint constraint) { + return constraint.getMinCount() != null + || constraint.getMaxCount() != null + || constraint.getClassIri() != null + || constraint.getDatatypeIri() != null + || constraint.getMinInclusive() != null + || constraint.getMaxInclusive() != null + || constraint.getIn() != null + || constraint.getPattern() != null; + } + + private static void validateCardinality( + final List findings, + final OntologyShapeConstraint constraint, + final String path) { + if (constraint.getMinCount() != null + && constraint.getMaxCount() != null + && constraint.getMinCount() > constraint.getMaxCount()) { + add( + findings, + OntologyProfileViolationCode.SHAPE_CARDINALITY_CONFLICT, + path, + "minCount " + + constraint.getMinCount() + + " is above maxCount " + + constraint.getMaxCount() + + ", so no value count satisfies the constraint"); + } + } + + private static void validateValues( + final List findings, + final OntologyShapeConstraint constraint, + final String path) { + if (constraint.getIn() == null) { + return; + } + if (constraint.getIn().isEmpty()) { + add( + findings, + OntologyProfileViolationCode.SHAPE_EMPTY_VALUE_LIST, + path + "/in", + "An in list names at least one value, or no value satisfies the constraint"); + } + for (int index = 0; index < constraint.getIn().size(); index++) { + final OntologyShapeValue value = constraint.getIn().get(index); + final boolean exactlyOne = + value != null && (value.getIri() == null) != (value.getLiteral() == null); + if (!exactlyOne) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + path + "/in/" + index, + "An in value is exactly one of an iri or a literal"); + } else { + requireAbsolute(findings, value.getIri(), path + "/in/" + index + "/iri"); + } + } + } + + private static void validatePattern( + final List findings, + final OntologyShapeConstraint constraint, + final String path) { + if (constraint.getPattern() == null) { + return; + } + try { + Pattern.compile(constraint.getPattern()); + } catch (PatternSyntaxException invalid) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + path + "/pattern", + "The pattern is not a valid regular expression: " + invalid.getDescription()); + } + } + + private static void requireAbsolute( + final List findings, final URI iri, final String path) { + if (iri != null && !iri.isAbsolute()) { + add( + findings, + OntologyProfileViolationCode.SHAPE_INVALID_CONSTRAINT, + path, + "An IRI must be absolute: " + iri); + } + } + + private static void add( + final List findings, + final OntologyProfileViolationCode code, + final String path, + final String message) { + findings.add( + new OntologyProfileViolation() + .withCode(code) + .withPath(path) + .withMessage(message) + .withSeverity(OntologyProfileViolationSeverity.ERROR)); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeValueRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeValueRules.java new file mode 100644 index 000000000000..0c755e1b1790 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyShapeValueRules.java @@ -0,0 +1,209 @@ +/* + * 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.ontology; + +import static org.openmetadata.service.ontology.OntologySettled.of; +import static org.openmetadata.service.ontology.OntologySettled.refused; +import static org.openmetadata.service.ontology.OntologySettled.when; + +import java.net.URI; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.api.services.CreateDatabaseService.DatabaseServiceType; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.ontology.OntologyCheckGates.Records; +import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideList; +import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideRange; +import org.openmetadata.service.ontology.OntologyCheckProbe.Unmatched; +import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Place; +import org.openmetadata.service.ontology.sql.TypedValue; +import org.openmetadata.service.ontology.sql.TypedValues; +import org.openmetadata.service.ontology.sql.TypedValues.Kind; + +/** + * How the parts of a constraint that ask about each value of a data property are checked at one + * place: {@code datatype}, {@code range}, {@code in} and {@code pattern} + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered). A null is no value, so it breaks + * none of them. A value of a constraint is read as a value of the column it is compared with, and + * the comparison is the engine's own. + */ +final class OntologyShapeValueRules { + private static final String TRUE = "true"; + private static final String FALSE = "false"; + + private static final String RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + + /** The datatypes of a literal that carries a language tag, which no column value has. */ + private static final Set TAGGED = Set.of(RDF + "langString", RDF + "PlainLiteral"); + + private static final Set ORDERED = + EnumSet.of(Kind.WHOLE, Kind.DECIMAL, Kind.DATE, Kind.TIME, Kind.TIMESTAMP); + + /** The one service type whose engine was run against every construct a pattern may use. */ + private static final String MATCHES_AS_SHACL_DOES = DatabaseServiceType.Postgres.value(); + + private OntologyShapeValueRules() {} + + /** The bounds of a range as values of the column. A range has at least one. */ + private record Bounds(Optional min, Optional max) {} + + /** Every value that the column can store is a value of the datatype, so no test is needed. */ + static OntologySettled datatype(final URI datatype, final Place place) { + return OntologyCheckGates.column(place) + .then( + column -> + OntologyHeldDatatypes.reads(datatype) + ? when( + OntologyHeldDatatypes.holdsOnly( + place.holder().serviceType(), datatype, column), + new HeldByMapping(), + OntologyShapeCheckReason.DATATYPE_MISMATCH) + : refused(OntologyShapeCheckReason.DATATYPE_NOT_SUPPORTED)); + } + + /** Every value lies between the bounds of the constraint, which are part of the range. */ + static OntologySettled range( + final OntologyShapeConstraint constraint, final Records records, final Place place) { + final List path = place.binding().getColumnPath(); + return OntologyCheckGates.column(place) + .then(column -> bounds(column, constraint)) + .then( + bounds -> + OntologyCheckGates.route(records, place) + .then(OntologyCheckGates::reach) + .map(reach -> new OutsideRange(reach, path, bounds.min(), bounds.max()))) + .map(probe -> check(place, probe)); + } + + private static OntologySettled bounds( + final Column column, final OntologyShapeConstraint constraint) { + if (TypedValues.kind(column).filter(ORDERED::contains).isEmpty()) { + return refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED); + } + return bound(column, constraint.getMinInclusive()) + .then(min -> bound(column, constraint.getMaxInclusive()).map(max -> new Bounds(min, max))); + } + + private static OntologySettled> bound( + final Column column, final OntologyLiteral literal) { + return literal == null ? of(Optional.empty()) : value(column, literal).map(Optional::of); + } + + /** Every value is one of the listed literals. */ + static OntologySettled in( + final List list, final Records records, final Place place) { + final List path = place.binding().getColumnPath(); + return OntologyCheckGates.column(place) + .then(column -> listed(column, list)) + .then( + values -> + OntologyCheckGates.route(records, place) + .then(OntologyCheckGates::reach) + .map(reach -> new OutsideList(reach, path, values))) + .map(probe -> check(place, probe)); + } + + private static OntologySettled> listed( + final Column column, final List list) { + if (TypedValues.kind(column).isEmpty()) { + return refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED); + } + return OntologySettled.all( + list.stream().map(item -> value(column, item.getLiteral())).toList()); + } + + /** + * Every value matches the pattern. An engine gets a statement only where it was run against + * every construct that {@link OntologyPortablePattern} lets through, so the service type is + * asked first and a pattern has one answer on every other one. + */ + static OntologySettled pattern( + final String pattern, final Records records, final Place place) { + if (!MATCHES_AS_SHACL_DOES.equals(records.identity().table().serviceType())) { + return refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED); + } + final List path = place.binding().getColumnPath(); + return OntologyCheckGates.column(place) + .then(column -> matched(column, pattern)) + .then( + written -> + OntologyCheckGates.route(records, place) + .then(OntologyCheckGates::reach) + .map(reach -> new Unmatched(reach, path, written))) + .map(probe -> check(place, probe)); + } + + /** + * The pattern as a text value that the engine matches the column with. A {@code CHAR} column + * pads its values with spaces, and nothing says whether a pattern is asked of the padding too. + */ + private static OntologySettled matched(final Column column, final String pattern) { + final boolean text = TypedValues.kind(column).filter(Kind.TEXT::equals).isPresent(); + if (!text || column.getDataType() == ColumnDataType.CHAR) { + return refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED); + } + return OntologyPortablePattern.forPostgres(pattern) + .flatMap(written -> text(column, written)) + .map(OntologySettled::of) + .orElseGet(() -> refused(OntologyShapeCheckReason.PATTERN_NOT_PORTABLE)); + } + + /** Empty when the text is longer than a statement takes. */ + private static Optional text(final Column column, final String text) { + try { + return Optional.of(TypedValues.value(column, text)); + } catch (final BadRequestException tooLong) { + return Optional.empty(); + } + } + + /** One literal of a constraint as a value of the column. */ + private static OntologySettled value( + final Column column, final OntologyLiteral literal) { + final boolean unreadable = + literal == null + || literal.getDatatypeIri() != null + && TAGGED.contains(literal.getDatatypeIri().toString()); + if (unreadable) { + return refused(OntologyShapeCheckReason.VALUE_DOES_NOT_FIT_COLUMN); + } + try { + return of(TypedValues.value(column, written(column, literal.getValue()))); + } catch (final BadRequestException unparsed) { + return refused(OntologyShapeCheckReason.VALUE_DOES_NOT_FIT_COLUMN); + } + } + + /** A literal is text, and a boolean column takes the JSON values true and false. */ + private static Object written(final Column column, final String text) { + final boolean bool = TypedValues.kind(column).filter(Kind.BOOL::equals).isPresent(); + if (bool && (TRUE.equals(text) || FALSE.equals(text))) { + return Boolean.valueOf(text); + } + return text; + } + + private static OntologyPartOutcome check(final Place place, final OntologyCheckProbe probe) { + return OntologyCheckGates.check(place, List.of(place.binding().getColumnPath()), probe); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementProjection.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementProjection.java new file mode 100644 index 000000000000..972245f506bf --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementProjection.java @@ -0,0 +1,109 @@ +/* + * 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.ontology; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.openmetadata.schema.api.data.OntologyStatementColumn; +import org.openmetadata.schema.api.data.OntologyStatementColumnKind; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedClass; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyRecordMapping.PropertyColumn; +import org.openmetadata.service.ontology.sql.TypedStatement; + +/** + * The select list of a statement about records, with what each of its columns holds. A column is + * listed once for each thing it holds, so a key column that is also bound to a property appears as + * a key part and again as that property. A class has one display name column at most: the first + * column of its identity table that a display name property is bound to. + */ +final class OntologyStatementProjection { + private record Item(String alias, List path) {} + + private final List items = new ArrayList<>(); + private final List columns = new ArrayList<>(); + + /** The key columns of the class, in key order. */ + OntologyStatementProjection key(final MappedClass type, final String alias) { + final List> key = type.identity().keyPaths(); + for (int part = 0; part < key.size(); part++) { + add(alias, key.get(part), plan(OntologyStatementColumnKind.KEY, type).withKeyPart(part)); + } + return this; + } + + /** + * The data property columns of {@code table}: the display name of the class first, then the + * others in binding order. + */ + OntologyStatementProjection values( + final MappedClass type, final MappedTable table, final String alias) { + final Optional name = + type.displayName().filter(column -> table.equals(type.identity())); + name.ifPresent(column -> displayName(type, alias)); + type.dataColumns(table).stream() + .filter(column -> name.filter(column::equals).isEmpty()) + .forEach( + column -> + add( + alias, + column.path(), + plan(OntologyStatementColumnKind.PROPERTY, type) + .withPropertyIri(column.property().getIri()))); + return this; + } + + /** The display name column of the identity table, when the class binds one there. */ + OntologyStatementProjection displayName(final MappedClass type, final String alias) { + type.displayName() + .ifPresent( + column -> + add( + alias, + column.path(), + plan(OntologyStatementColumnKind.DISPLAY_NAME, type) + .withPropertyIri(column.property().getIri()))); + return this; + } + + /** A column that counts records of {@code counted}. The caller writes it after the list. */ + OntologyStatementProjection count(final MappedClass counted) { + columns.add(plan(OntologyStatementColumnKind.COUNT, counted).withIndex(columns.size())); + return this; + } + + /** The listed columns, separated by commas. */ + TypedStatement.Builder writeTo(final TypedStatement.Builder sql) { + for (int index = 0; index < items.size(); index++) { + sql.sql(index == 0 ? "" : ", ").column(items.get(index).alias(), items.get(index).path()); + } + return sql; + } + + List columns() { + return List.copyOf(columns); + } + + private void add( + final String alias, final List path, final OntologyStatementColumn column) { + items.add(new Item(alias, path)); + columns.add(column.withIndex(columns.size())); + } + + private static OntologyStatementColumn plan( + final OntologyStatementColumnKind kind, final MappedClass type) { + return new OntologyStatementColumn().withKind(kind).withClassIri(type.iri()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java new file mode 100644 index 000000000000..042e9f88f9ba --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStatementService.java @@ -0,0 +1,553 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import jakarta.ws.rs.core.SecurityContext; +import java.net.URI; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.api.data.OntologyAggregateStatementRequest; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyExpandStatementRequest; +import org.openmetadata.schema.api.data.OntologyFindStatementRequest; +import org.openmetadata.schema.api.data.OntologyOpenStatementRequest; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyStatementBindingRevision; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.api.data.OntologyStatementEngineFamily; +import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementMeasure; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementRelation; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.RecordStatement; +import org.openmetadata.service.ontology.OntologyMappingReader.Bindings; +import org.openmetadata.service.ontology.OntologyMappingReader.Tables; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedClass; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyRelationPath.End; +import org.openmetadata.service.ontology.OntologyRelationPath.Ends; +import org.openmetadata.service.ontology.OntologyRelationPath.Held; +import org.openmetadata.service.ontology.OntologyShapeCheckReader.Asked; +import org.openmetadata.service.ontology.OntologyShapeCheckReader.Read; +import org.openmetadata.service.ontology.OntologyVersion.Wanted; +import org.openmetadata.service.ontology.sql.FinishedStatement; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.util.FreshReadScope; + +/** + * Answers the four statements about the records of a class: find, open, expand and aggregate + * (ADR:2026-11-22-record-statements-start-from-the-identity-table). Each answer is one SELECT with + * a column plan. A call reads the ontology, the bindings and the catalog. It writes nothing and + * runs nothing. + * + *

A call makes a fixed number of batched reads whatever the class binds: the class and the + * relation, the binding rows between two revision reads, the tables twice (which exist, then the + * ones the reader may view), the bound properties, and the release members when it reads a + * release. + * + *

It also says how the shapes that target a class are checked on the tables the class binds + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered), from the same class and version. + */ +public final class OntologyStatementService { + private static final String CLASS = "Class"; + private static final String RELATION = "Relation"; + private static final String MEASURE_OF_A_RELATION = + "A measure belongs to a relation. A count of the class takes no measure"; + private static final String RELATION_OR_COUNT = + "An aggregate over a relation takes the relation and the direction together. A count of the" + + " class takes neither, and no related class"; + + /** Refuses with a 403 a caller who may not read the working draft of an ontology. */ + @FunctionalInterface + public interface DraftGate { + void require(SecurityContext context, UUID ontologyId); + } + + private final OntologyConceptBindingStore store; + private final CollectionDAO dao; + private final OntologyBindingAccess catalog; + private final OntologyMappingReader mapping; + private final OntologyShapeCheckReader shapes; + private final OntologyCheckProposals proposals; + private final DraftGate draftGate; + + public OntologyStatementService( + final OntologyConceptBindingStore store, + final CollectionDAO dao, + final Authorizer authorizer, + final Function> repositories, + final DraftGate draftGate) { + this.store = store; + this.dao = dao; + this.catalog = new OntologyBindingAccess(authorizer, repositories); + this.mapping = new OntologyMappingReader(store, catalog); + this.shapes = new OntologyShapeCheckReader(store, catalog); + this.proposals = new OntologyCheckProposals(dao, catalog); + this.draftGate = draftGate; + } + + /** + * The class a statement is about, as the version it reads declares it. + * + * @param ontology the ontology of the class, as its working row names it + */ + private record Subject(OntologyConcept type, EntityReference ontology, OntologyVersion version) { + UUID id() { + return type.getId(); + } + + URI iri() { + return type.getIri(); + } + + UUID ontologyId() { + return ontology.getId(); + } + + End end() { + return new End(id(), iri()); + } + } + + /** The relation a request follows from its class. */ + private record Along(UUID relation, OntologyStatementDirection direction, UUID relatedClass) { + boolean isForward() { + return direction == OntologyStatementDirection.FORWARD; + } + } + + /** A relation path with the bindings it was built from. */ + private record Route(OntologyRelationPath path, Bindings bindings) { + OntologyStatementRelation relation() { + return new OntologyStatementRelation() + .withPropertyIri(path.relation().getIri()) + .withDirection(path.direction()) + .withRelatedClassIri(path.related().iri()); + } + + List revisions() { + final Map classes = new LinkedHashMap<>(); + classes.put(path.start().id(), path.start().iri()); + classes.put(path.related().id(), path.related().iri()); + return OntologyStatementService.revisions(bindings, classes); + } + } + + public OntologyStatementPlan find( + final Access access, final UUID classId, final OntologyFindStatementRequest request) { + final OntologyFindStatementRequest asked = + request == null ? new OntologyFindStatementRequest() : request; + try (final var ignored = FreshReadScope.enter()) { + final Subject subject = subject(access, classId, asked.getVersion()); + final Bindings bindings = mapping.bindings(List.of(classId), List.of()); + final Tables tables = mapping.tables(access, bindings.rows()); + final MappedClass type = + mapped(access, subject, identity(subject, bindings, tables), List.of()); + return plan( + OntologyStatementKind.FIND, + OntologyConceptSqlGenerator.find(type, asked.getMatchText())) + .withVersion(subject.version().read()) + .withBindingRevisions(revisions(bindings, Map.of(subject.id(), subject.iri()))); + } + } + + public OntologyStatementPlan open( + final Access access, final UUID classId, final OntologyOpenStatementRequest request) { + try (final var ignored = FreshReadScope.enter()) { + final Subject subject = subject(access, classId, request.getVersion()); + final Bindings bindings = mapping.bindings(List.of(classId), List.of(classId)); + final Tables tables = mapping.tables(access, bindings.rows()); + final MappedTable identity = identity(subject, bindings, tables); + final List contributing = + OntologyMappingReader.contributing( + subject.iri(), bindings.contributing().get(classId), tables) + .stream() + .filter(tables::shows) + .toList(); + final RecordStatement statement = + OntologyConceptSqlGenerator.open( + mapped(access, subject, identity, contributing), + contributing.stream().map(tables::mapped).toList(), + request.getKey()); + return plan(OntologyStatementKind.OPEN, statement) + .withVersion(subject.version().read()) + .withBindingRevisions(revisions(bindings, Map.of(subject.id(), subject.iri()))); + } + } + + public OntologyStatementPlan expand( + final Access access, final UUID classId, final OntologyExpandStatementRequest request) { + try (final var ignored = FreshReadScope.enter()) { + final Subject start = subject(access, classId, request.getVersion()); + final Route route = + route( + access, + start, + new Along(request.getRelation(), request.getDirection(), request.getRelatedClass())); + return plan( + OntologyStatementKind.EXPAND, + OntologyConceptSqlGenerator.expand( + route.path(), request.getKey(), request.getAfter())) + .withRelation(route.relation()) + .withVersion(start.version().read()) + .withBindingRevisions(route.revisions()); + } + } + + /** + * The number of records of the class when the request names no relation. With a relation and a + * direction, the records of the class that relate to the most records along it, or with the + * measure {@code linkCount} the number of links of the relation. + */ + public OntologyStatementPlan aggregate( + final Access access, final UUID classId, final OntologyAggregateStatementRequest request) { + final OntologyAggregateStatementRequest asked = + request == null ? new OntologyAggregateStatementRequest() : request; + final boolean overRelation = asked.getRelation() != null && asked.getDirection() != null; + final boolean overClass = + asked.getRelation() == null + && asked.getDirection() == null + && asked.getRelatedClass() == null; + if (!overRelation && !overClass) { + throw new BadRequestException(RELATION_OR_COUNT); + } + if (overClass && asked.getMeasure() != null) { + throw new BadRequestException(MEASURE_OF_A_RELATION); + } + try (final var ignored = FreshReadScope.enter()) { + final Subject subject = subject(access, classId, asked.getVersion()); + return overRelation ? top(access, subject, asked) : count(access, subject); + } + } + + /** + * How each part of each constraint of the shapes that target the class is checked on the tables + * the class binds. The answer creates no test and runs no statement. + */ + public OntologyShapeChecks shapeChecks( + final Access access, final UUID classId, final OntologyStatementVersion version) { + try (final var ignored = FreshReadScope.enter()) { + final Subject subject = subject(access, classId, version); + final Read read = + shapes.read( + access, + new Asked(subject.id(), subject.iri(), subject.ontologyId(), subject.version())); + return new OntologyShapeChecks() + .withConceptId(subject.id()) + .withClassIri(subject.iri()) + .withVersion(subject.version().read()) + .withShapes(marked(access, subject.id(), read)); + } + } + + private List marked( + final Access access, final UUID classId, final Read read) { + final List answer = + OntologyShapeCheckAnswer.shapes(read.facts(), read.shapes(), read.hidden()); + proposals.mark(access, classId, answer); + return answer; + } + + private OntologyStatementPlan count(final Access access, final Subject subject) { + final Bindings bindings = mapping.bindings(List.of(subject.id()), List.of()); + final Tables tables = mapping.tables(access, bindings.rows()); + final MappedClass type = + new MappedClass(subject.id(), subject.iri(), identity(subject, bindings, tables), Map.of()); + return plan(OntologyStatementKind.AGGREGATE, OntologyConceptSqlGenerator.count(type)) + .withVersion(subject.version().read()) + .withBindingRevisions(revisions(bindings, Map.of(subject.id(), subject.iri()))); + } + + private OntologyStatementPlan top( + final Access access, final Subject start, final OntologyAggregateStatementRequest asked) { + final Route route = + route( + access, + start, + new Along(asked.getRelation(), asked.getDirection(), asked.getRelatedClass())); + final boolean links = asked.getMeasure() == OntologyStatementMeasure.LINK_COUNT; + return plan( + OntologyStatementKind.AGGREGATE, + links + ? OntologyConceptSqlGenerator.links(route.path()) + : OntologyConceptSqlGenerator.top(route.path())) + .withRelation(route.relation()) + .withMeasure( + links ? OntologyStatementMeasure.LINK_COUNT : OntologyStatementMeasure.TOP_RECORDS) + .withVersion(start.version().read()) + .withBindingRevisions(route.revisions()); + } + + private Subject subject( + final Access access, final UUID classId, final OntologyStatementVersion asked) { + return asked == OntologyStatementVersion.DRAFT + ? draftSubject(access, classId) + : releaseSubject(access, classId); + } + + private Subject draftSubject(final Access access, final UUID classId) { + final OntologyConcept working = viewed(access, Entity.ONTOLOGY_CONCEPT, classId); + store.requireLiveOntology(working); + draftGate.require(access.securityContext(), working.getOntology().getId()); + return new Subject( + working, working.getOntology(), OntologyVersion.draft(dao, working.getOntology())); + } + + /** + * The class as the active release declares it. The working row, deleted or not, only says which + * ontology the class belongs to, so the release answers as it was released whatever the draft + * lost since. + */ + private Subject releaseSubject(final Access access, final UUID classId) { + final OntologyConcept row = + (OntologyConcept) catalog.working(access, Entity.ONTOLOGY_CONCEPT, classId); + store.requireLiveOntology(row); + final OntologyVersion version = activeRelease(access, row); + final OntologyConcept declared = + (OntologyConcept) + version.declared( + catalog, + access, + new Wanted( + Entity.ONTOLOGY_CONCEPT, + MemberKind.CONCEPT, + CLASS, + row.getOntology().getId(), + other -> new IllegalStateException("A class belongs to its own ontology")), + classId); + return new Subject(declared, row.getOntology(), version); + } + + /** + * The active release of the ontology of {@code row}. An ontology with none is a 404 for a reader + * who may view the class, and the refusal of the right comes first for one who may not. + */ + private OntologyVersion activeRelease(final Access access, final OntologyConcept row) { + try { + return OntologyVersion.release(dao, row.getOntology()); + } catch (final EntityNotFoundException noRelease) { + catalog.authorizedWorking( + access, Entity.ONTOLOGY_CONCEPT, row.getId(), MetadataOperation.VIEW_BASIC); + throw noRelease; + } + } + + private static MappedTable identity( + final Subject subject, final Bindings bindings, final Tables tables) { + return OntologyMappingReader.identity( + subject.iri(), bindings.identity().get(subject.id()), tables); + } + + /** The class with the properties that the columns of its identity and other tables may name. */ + private MappedClass mapped( + final Access access, + final Subject subject, + final MappedTable identity, + final List contributing) { + final List read = new ArrayList<>(List.of(identity.row())); + read.addAll(contributing); + return new MappedClass( + subject.id(), subject.iri(), identity, properties(access, subject.version(), read)); + } + + /** + * The path of a relation between the identity tables of two classes. The class that binds the + * relation stores the join, on its identity table or on a contributing table that links the two + * classes, and only a confirmed join is followed. + */ + private Route route(final Access access, final Subject start, final Along along) { + final OntologyProperty relation = relation(access, start, along.relation()); + final Subject related = + new Subject( + relatedClass(access, start, relation, along), start.ontology(), start.version()); + final Subject subject = along.isForward() ? start : related; + final Subject object = along.isForward() ? related : start; + final Bindings bindings = + mapping.bindings( + Stream.of(start.id(), related.id()).distinct().toList(), List.of(subject.id())); + final Tables tables = mapping.tables(access, bindings.rows()); + final MappedTable startTable = identity(start, bindings, tables); + final MappedTable relatedTable = identity(related, bindings, tables); + final Held held = + OntologyMappingReader.join( + new Ends(relation.getId(), relation.getIri(), subject.end(), object.end()), + bindings, + tables); + final Map properties = + properties(access, start.version(), List.of(startTable.row(), relatedTable.row())); + return new Route( + OntologyRelationPath.of( + relation, + along.direction(), + new MappedClass(start.id(), start.iri(), startTable, properties), + new MappedClass(related.id(), related.iri(), relatedTable, properties), + held), + bindings); + } + + private OntologyProperty relation( + final Access access, final Subject start, final UUID relationId) { + final OntologyProperty declared = + (OntologyProperty) + start + .version() + .declared( + catalog, + access, + new Wanted( + Entity.ONTOLOGY_PROPERTY, + MemberKind.PROPERTY, + RELATION, + start.ontologyId(), + other -> notAnObjectProperty(((OntologyProperty) other).getIri(), start)), + relationId); + if (declared.getKind() != OntologyPropertyKind.OBJECT) { + throw notAnObjectProperty(declared.getIri(), start); + } + return declared; + } + + private static BadRequestException notAnObjectProperty(final URI iri, final Subject start) { + return new BadRequestException( + String.format( + "Relation %s is not an object property of the ontology of class %s", iri, start.iri())); + } + + private OntologyConcept relatedClass( + final Access access, + final Subject start, + final OntologyProperty relation, + final Along along) { + final UUID id = + along.relatedClass() == null ? namedClass(start, relation, along) : along.relatedClass(); + return (OntologyConcept) + start + .version() + .declared( + catalog, + access, + new Wanted( + Entity.ONTOLOGY_CONCEPT, + MemberKind.CONCEPT, + CLASS, + start.ontologyId(), + other -> + new BadRequestException( + String.format( + "Class %s is not a class of the ontology of class %s", + ((OntologyConcept) other).getIri(), start.iri()))), + id); + } + + /** The one class a relation names at its far end: its range forward, its domain going back. */ + private UUID namedClass(final Subject start, final OntologyProperty relation, final Along along) { + final List named = + listOrEmpty(along.isForward() ? relation.getRange() : relation.getDomain()); + if (named.size() != 1) { + throw new BadRequestException( + String.format( + "Relation %s names %d classes in its %s, so the request must name the related class", + relation.getIri(), named.size(), along.isForward() ? "range" : "domain")); + } + return start + .version() + .classNamed(store, start.ontologyId(), named) + .orElseThrow( + () -> + EntityNotFoundException.byMessage( + String.format( + "Class %s is not a class of ontology %s", + named.getFirst(), start.ontology().getFullyQualifiedName()))); + } + + /** + * The properties that the rows bind, as the version declares them. A property the reader may + * not view is left out, so no plan names it. + */ + private Map properties( + final Access access, final OntologyVersion version, final List rows) { + final Set ids = + rows.stream() + .flatMap(row -> listOrEmpty(row.columns()).stream()) + .map(OntologyColumnBinding::getPropertyId) + .collect(Collectors.toSet()); + return version.viewableProperties(catalog, access, ids); + } + + @SuppressWarnings("unchecked") + private > T viewed( + final Access access, final String type, final UUID id) { + return (T) catalog.authorized(access, type, id, MetadataOperation.VIEW_BASIC); + } + + private static OntologyStatementPlan plan( + final OntologyStatementKind kind, final RecordStatement statement) { + final FinishedStatement text = statement.family().finish(statement.text()); + final MappedTable first = statement.read().getFirst(); + return new OntologyStatementPlan() + .withStatement(kind) + .withSql(text.sql()) + .withEscapedSql(text.escapedSql()) + .withFamily( + OntologyStatementEngineFamily.fromValue( + statement.family().name().toLowerCase(Locale.ROOT))) + .withDialect(statement.family().dialect()) + .withService(first.database().getFirst()) + .withServiceType(first.serviceType()) + .withTables(statement.read().stream().map(MappedTable::fullyQualifiedName).toList()) + .withColumns(statement.columns()) + .withRowCap(statement.rowCap()) + .withExtraRow(statement.extraRow()) + .withOrderedBy(statement.orderedBy()); + } + + private static List revisions( + final Bindings bindings, final Map classes) { + return classes.entrySet().stream() + .map( + type -> + new OntologyStatementBindingRevision() + .withConceptId(type.getKey()) + .withClassIri(type.getValue()) + .withRevision(bindings.revisions().get(type.getKey()))) + .toList(); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java index f02aea4ad94e..df4d031f3e0e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyStructureValidator.java @@ -23,6 +23,7 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyAxiomType; import org.openmetadata.schema.type.OntologyProfileViolation; @@ -35,6 +36,7 @@ import org.openmetadata.schema.type.OntologyReleaseStructureIssue; import org.openmetadata.service.exception.OntologyValidationException; import org.openmetadata.service.rdf.OwlEntityDeclarations; +import org.openmetadata.service.rdf.OwlEntityDeclarations.EntityKind; /** Structural and OWL 2 DL checks for the supported authoring model; no logical reasoning. */ public final class OntologyStructureValidator { @@ -199,6 +201,7 @@ private static OntologyStructureValidator validateWorkingDefinitions( case OntologyConcept concept -> MemberKind.CONCEPT; case OntologyProperty property -> MemberKind.PROPERTY; case OntologyAxiom axiom -> MemberKind.AXIOM; + case OntologyShape shape -> MemberKind.SHAPE; default -> throw new IllegalArgumentException( "Unsupported ontology definition"); }), @@ -268,6 +271,12 @@ public static OntologyConceptDeleteImpact deletionImpact( blockers.add(other.getEntityReference()); } } + case OntologyShape shape -> { + if (OntologyReferences.collect(shape).stream() + .anyMatch(reference -> reference.getIri().toString().equals(iri))) { + blockers.add(shape.getEntityReference()); + } + } default -> {} } } @@ -307,6 +316,7 @@ private void validate(final Definition definition) { OntologyProfileViolationCode.UNDECLARED_PROPERTY); } case OntologyAxiom axiom -> validateAxiom(definition.member(), axiom); + case OntologyShape shape -> validateShape(definition.member(), shape); default -> {} } } @@ -341,6 +351,41 @@ private void validateAxiom(final OntologyReleaseMember member, final OntologyAxi } } + /** + * A shape holds up only if the class it targets and every class and property it names exist in + * the same release, and its constraints can be satisfied at all. + */ + private void validateShape(final OntologyReleaseMember member, final OntologyShape shape) { + OntologyShapeRules.validate(shape).forEach(violation -> add(member, violation)); + requireClass(member, shape.getTargetConcept(), "/targetConcept"); + final var constraints = listOrEmpty(shape.getConstraints()); + for (int index = 0; index < constraints.size(); index++) { + final var constraint = constraints.get(index); + if (constraint == null) { + continue; + } + final String path = "/constraints/" + index; + if (constraint.getPath() != null) { + requireProperty(member, constraint.getPath(), null, path + "/path"); + } + if (constraint.getClassIri() != null) { + requireClass(member, constraint.getClassIri(), path + "/classIri"); + } + } + } + + private void requireClass(final OntologyReleaseMember member, final URI iri, final String path) { + if (iri != null + && !concepts.contains(iri.toString()) + && OwlEntityDeclarations.vocabularyKind(iri.toString()) != EntityKind.CLASS) { + add( + member, + OntologyProfileViolationCode.UNDECLARED_CLASS, + path, + "Declare or import the referenced class: " + iri); + } + } + private static boolean isIdentityAssertion(final OntologyAxiom axiom) { return axiom.getAxiomType() == OntologyAxiomType.OBJECT_PROPERTY_ASSERTION && axiom.getPropertyIri() != null @@ -371,6 +416,7 @@ private void validateProperty( "/kind", "The closure declares incompatible property kinds for " + property.getIri()); } + validateDisplayName(member, property); if (property.getInverse() != null) { requireProperty(member, property.getInverse(), OntologyPropertyKind.OBJECT, "/inverse"); } @@ -401,6 +447,38 @@ private void validateProperty( } } + /** A class has at most one data property that names its instances. */ + private void validateDisplayName( + final OntologyReleaseMember member, final OntologyProperty property) { + if (!Boolean.TRUE.equals(property.getIsDisplayName())) { + return; + } + final Set domain = + listOrEmpty(property.getDomain()).stream().map(URI::toString).collect(Collectors.toSet()); + properties.values().stream() + .flatMap(List::stream) + .filter(other -> !other.getId().equals(property.getId())) + .filter(other -> Boolean.TRUE.equals(other.getIsDisplayName())) + .filter(other -> !Boolean.TRUE.equals(other.getDeleted())) + .filter( + other -> + listOrEmpty(other.getDomain()).stream() + .map(URI::toString) + .anyMatch(domain::contains)) + .findFirst() + .ifPresent( + other -> + add( + member, + OntologyProfileViolationCode.DUPLICATE_DISPLAY_NAME, + "/isDisplayName", + "A class has at most one display-name property, but " + + property.getIri() + + " and " + + other.getIri() + + " both name the same class")); + } + private void validateSimplePropertyUse( final OntologyReleaseMember member, final OntologyProperty property) { if (propertyHierarchy.isNonSimple(property.getIri()) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableBindingChecks.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableBindingChecks.java new file mode 100644 index 000000000000..5ab2722c94c8 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableBindingChecks.java @@ -0,0 +1,167 @@ +package org.openmetadata.service.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyAssetBinding; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.sql.TypedRowFilter; +import org.openmetadata.service.ontology.sql.TypedValues; + +/** + * What a table binding must satisfy before it is saved. Every check runs under the ontology lock, + * after the rows of deleted assets are gone, so it reads the state the write commits against. + */ +final class OntologyTableBindingChecks { + static final String OUTSIDE_MAPPING_SOURCE = + "Once an ontology names a mapping source, every table binding must sit in that database"; + static final String SECOND_IDENTITY_TABLE = + "A class has at most one identity table. Change the role of the current one or remove its binding first"; + static final String MISSING_KEY_COLUMN = "Every subject key column must exist in the bound table"; + static final String MISSING_FILTER_COLUMN = "A row filter column must exist in the bound table"; + static final String JOIN_OUTSIDE_DATABASE = + "A join target must be a table in the same database as the bound table"; + static final String MISSING_JOIN_COLUMN = + "Join columns must exist: each child in the bound table and each parent in the target table"; + + private final OntologyBindingAccess targets; + + /** One table binding write: the stored row it replaces, if any, and the table it binds. */ + record Write( + Access access, + OntologyConcept concept, + OntologyConceptBindingStore locked, + BindingRow existing, + OntologyAssetBinding asset, + Table table) {} + + OntologyTableBindingChecks(final OntologyBindingAccess targets) { + this.targets = targets; + } + + void check(final Write write) { + requireInsideMappingSource(write); + requireKeyColumns(write); + requireSingleIdentity(write); + requireRowFilter(write); + } + + /** A join added or changed by this write. One already stored is left as it is. */ + void checkJoin(final Write write, final OntologyColumnJoin join) { + final var target = + (Table) + targets.authorized( + write.access(), + Entity.TABLE, + join.getTargetAssetId(), + MetadataOperation.VIEW_BASIC); + if (!databaseOf(target).equals(databaseOf(write.table()))) { + throw new BadRequestException(JOIN_OUTSIDE_DATABASE); + } + final boolean resolved = + join.getOn().stream() + .allMatch( + pair -> + OntologyBindingRules.resolveColumn(write.table(), pair.getChild()) != null + && OntologyBindingRules.resolveColumn(target, pair.getParent()) != null); + if (!resolved) { + throw new BadRequestException(MISSING_JOIN_COLUMN); + } + } + + private static void requireInsideMappingSource(final Write write) { + final UUID source = write.locked().mappingSource(write.concept().getOntology().getId()); + if (source != null && !source.equals(databaseOf(write.table()))) { + throw new BadRequestException(OUTSIDE_MAPPING_SOURCE); + } + } + + private static void requireKeyColumns(final Write write) { + final List> key = listOrEmpty(write.asset().getSubjectKey()); + final boolean changed = + write.existing() == null || !key.equals(listOrEmpty(write.existing().subjectKey())); + if (changed + && key.stream() + .anyMatch(path -> OntologyBindingRules.resolveColumn(write.table(), path) == null)) { + throw new BadRequestException(MISSING_KEY_COLUMN); + } + } + + private static void requireSingleIdentity(final Write write) { + if (write.asset().getRole() != OntologyBindingRole.IDENTITY) { + return; + } + final boolean taken = + write.locked().identityRows(List.of(write.concept().getId())).stream() + .anyMatch(row -> !row.assetId().equals(write.asset().getAssetId())); + if (taken) { + throw new BadRequestException(SECOND_IDENTITY_TABLE); + } + } + + /** + * A row filter is a question about the rows of a table, so setting or changing one takes the + * right that reads those rows. Its column must exist and each value must parse as the data type + * of that column. Removing a filter, or sending the stored one back, asks nothing. + */ + private void requireRowFilter(final Write write) { + final var filter = write.asset().getRowFilter(); + final boolean unchanged = + write.existing() != null && Objects.equals(filter, write.existing().rowFilter()); + if (filter == null || unchanged) { + return; + } + typedRowFilter(write.table(), filter); + targets.require( + write.access(), Entity.TABLE, write.table(), MetadataOperation.VIEW_SAMPLE_DATA); + } + + /** + * The filter with each value parsed as the data type of its column, or a 400 that names what + * fails. A write runs it, and so does every statement built over the binding, because the column + * can change after the binding is saved. + */ + static TypedRowFilter typedRowFilter(final Table table, final OntologyRowFilter filter) { + final Column column = OntologyBindingRules.resolveColumn(table, filter.getColumn()); + if (column == null) { + throw new BadRequestException(MISSING_FILTER_COLUMN); + } + return TypedValues.rowFilter(column, filter); + } + + /** + * The stored row filter of a binding, parsed again for a statement that reads the table, or null + * when the binding has none. The filter column may have changed its data type or left the table + * since the binding was saved, and a filter that no longer applies is a 400 that names the table. + */ + static TypedRowFilter storedRowFilter(final Table table, final OntologyRowFilter filter) { + if (filter == null) { + return null; + } + try { + return typedRowFilter(table, filter); + } catch (final BadRequestException refused) { + throw new BadRequestException( + String.format( + "The row filter of %s no longer applies. %s", + table.getFullyQualifiedName(), refused.getMessage())); + } + } + + private static UUID databaseOf(final Table table) { + return table.getDatabase().getId(); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMapping.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMapping.java new file mode 100644 index 000000000000..dc827ca96afa --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMapping.java @@ -0,0 +1,156 @@ +/* + * 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.ontology; + +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.service.ontology.sql.TypedRowFilter; + +/** + * The table mapping of one version of an ontology, as one caller may see it: every class of the + * version that binds an existing table, with the tables, keys, row filters, data columns and + * relation joins of its bindings. + * + *

Parts the caller may not view are left out and counted. A caller that needs the whole mapping + * checks the three counts, and a mapping with any count above zero is not the whole mapping. No + * field names, identifies or points at a part that is hidden from the caller. + * + * @param version the version that was read + * @param classes the classes the caller may view, by IRI + * @param hiddenTables the number of distinct existing tables that the classes of the version bind, + * or that a relation column of a listed binding joins, and that the caller may not view + * @param hiddenClasses the number of classes of the version that bind an existing table and that + * the caller may not view + * @param hiddenProperties the number of properties of the version that a column of a listed + * binding binds and that the caller may not view + */ +public record OntologyTableMapping( + OntologyStatementVersionRead version, + List classes, + int hiddenTables, + int hiddenClasses, + int hiddenProperties) { + + /** + * One class and the tables it binds that the caller may view. + * + * @param iri the IRI of the class in the version + * @param id the id of the class + * @param tables identity table first, then contributing tables by name, then tables with no role + * by name. Empty when the caller may view none of the tables the class binds. + */ + public record ClassMapping(URI iri, UUID id, List tables) {} + + /** + * One table of a class, with how the class reads it. + * + * @param table the table + * @param role the role of the binding, or null for a binding with no role + * @param subjectKey the column paths that identify one record, in key order. Empty when the + * binding names none. + * @param rowFilter the row filter of the binding, or null when it has none + * @param dataColumns the columns bound to data properties, in binding order + * @param relationColumns the columns bound to relations, in binding order + * @param absentFromVersion the paths of the columns whose property the version does not declare, + * in binding order + * @param missingColumns the paths of the binding's columns that the table no longer has, in + * binding order + */ + public record TableBinding( + TableRef table, + OntologyBindingRole role, + List> subjectKey, + RowFilterState rowFilter, + List dataColumns, + List relationColumns, + List> absentFromVersion, + List> missingColumns) {} + + /** + * A table the caller may view. + * + * @param id the id of the table + * @param fullyQualifiedName the fully qualified name of the table + * @param serviceType the value of the service type of the table, or null when it has none + * @param columns the columns of the table as the catalog holds them + */ + public record TableRef( + UUID id, String fullyQualifiedName, String serviceType, List columns) {} + + /** What a stored row filter is now: a filter that applies, or the reason it does not. */ + public sealed interface RowFilterState {} + + /** + * A row filter whose column exists and whose values parse as the data type of that column. + * + * @param filter the parsed filter + */ + public record Applies(TypedRowFilter filter) implements RowFilterState {} + + /** + * A row filter that no longer applies. + * + * @param reason one sentence in the style of a 409 that says why. It holds no value of the + * filter. + */ + public record Broken(String reason) implements RowFilterState {} + + /** + * A column that holds the values of a data property. + * + * @param propertyIri the IRI of the property + * @param columnPath the path of the column + */ + public record DataColumn(URI propertyIri, List columnPath) {} + + /** + * A column bound to a relation. + * + * @param relationIri the IRI of the relation + * @param columnPath the path of the column + * @param join where the column leads, or null when the binding stores no join. Columns bound + * before joins existed store none. + */ + public record RelationColumn(URI relationIri, List columnPath, Join join) {} + + /** + * The join of a relation column onto the table that holds the related records. A join onto a + * table the caller may not view, or onto a table that no longer exists, is not listed. + * + * @param status whether a person confirmed the join + * @param targetTableId the id of the target table, which the caller may view + * @param on the pairs of the join, in stored order + * @param objectClasses the IRIs of the classes the caller may view whose identity table is the + * target table, by IRI. When the relation declares a range, only the classes that are in the + * range or are subclasses of a class in it, in that version. Empty when no class qualifies. + */ + public record Join( + OntologyJoinStatus status, + UUID targetTableId, + List on, + List objectClasses) {} + + /** + * One equality of a join. + * + * @param child the path of a column of the table that holds the relation column + * @param parent the path of a column of the target table + */ + public record ColumnPair(List child, List parent) {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java new file mode 100644 index 000000000000..186c585c45b2 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappingRules.java @@ -0,0 +1,291 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyTableMapping.Applies; +import org.openmetadata.service.ontology.OntologyTableMapping.Broken; +import org.openmetadata.service.ontology.OntologyTableMapping.ClassMapping; +import org.openmetadata.service.ontology.OntologyTableMapping.ColumnPair; +import org.openmetadata.service.ontology.OntologyTableMapping.DataColumn; +import org.openmetadata.service.ontology.OntologyTableMapping.Join; +import org.openmetadata.service.ontology.OntologyTableMapping.RelationColumn; +import org.openmetadata.service.ontology.OntologyTableMapping.RowFilterState; +import org.openmetadata.service.ontology.OntologyTableMapping.TableBinding; +import org.openmetadata.service.ontology.OntologyTableMapping.TableRef; +import org.openmetadata.service.ontology.sql.TypedValues; + +/** + * Turns what one read found into the table mapping a caller may see. Nothing here reads a database + * or a policy. The caller passes what exists and which of it the reader may view, and this decides + * what is listed and what is counted. + */ +final class OntologyTableMappingRules { + private static final String FILTER_COLUMN_GONE = + "The row filter of table %s names a column that the table no longer has"; + private static final String FILTER_VALUE_UNPARSED = + "A value of the row filter of table %s no longer parses as the data type of column %s"; + + private OntologyTableMappingRules() {} + + /** + * What one read found. + * + * @param rows the table rows of the classes, whether or not their tables exist + * @param tables every existing table that a row binds or a column joins, by id + * @param viewableTables the ids among {@code tables} that the reader may view + * @param classes the classes that the version declares, by id + * @param viewableClasses the ids among {@code classes} that the reader may view + * @param properties the properties that the version declares, by id + * @param viewableProperties the ids among {@code properties} that the reader may view + * @param parents the named parents of each class by IRI, as far up as the version declares them + */ + record Facts( + OntologyStatementVersionRead version, + List rows, + Map tables, + Set viewableTables, + Map classes, + Set viewableClasses, + Map properties, + Set viewableProperties, + Map> parents) {} + + /** What a build leaves out, collected as it goes. */ + private static final class Hidden { + private final Set tables = new HashSet<>(); + private final Set properties = new HashSet<>(); + } + + static OntologyTableMapping build(final Facts facts) { + final List bound = + facts.rows().stream() + .filter(row -> facts.tables().containsKey(row.assetId())) + .filter(row -> facts.classes().containsKey(row.conceptId())) + .toList(); + final Map> byClass = + bound.stream().collect(Collectors.groupingBy(BindingRow::conceptId)); + final Hidden hidden = new Hidden(); + bound.stream() + .map(BindingRow::assetId) + .filter(id -> !facts.viewableTables().contains(id)) + .forEach(hidden.tables::add); + bound.stream() + .filter(row -> facts.viewableTables().contains(row.assetId())) + .flatMap(row -> listOrEmpty(row.columns()).stream()) + .map(column -> facts.properties().get(column.getPropertyId())) + .filter( + property -> property != null && !facts.viewableProperties().contains(property.getId())) + .forEach(property -> hidden.properties.add(property.getId())); + final Map> identityClasses = identityClasses(facts, bound); + final List classes = + byClass.entrySet().stream() + .filter(entry -> facts.viewableClasses().contains(entry.getKey())) + .map(entry -> mapped(facts, entry, identityClasses, hidden)) + .sorted(Comparator.comparing(mapping -> mapping.iri().toString())) + .toList(); + final int hiddenClasses = + (int) byClass.keySet().stream().filter(id -> !facts.viewableClasses().contains(id)).count(); + return new OntologyTableMapping( + facts.version(), classes, hidden.tables.size(), hiddenClasses, hidden.properties.size()); + } + + /** The viewable classes whose identity table is each table, in IRI order. */ + private static Map> identityClasses( + final Facts facts, final List bound) { + return bound.stream() + .filter(row -> row.role() == OntologyBindingRole.IDENTITY) + .filter(row -> facts.viewableClasses().contains(row.conceptId())) + .collect( + Collectors.groupingBy( + BindingRow::assetId, + Collectors.mapping( + row -> facts.classes().get(row.conceptId()).getIri(), + Collectors.collectingAndThen( + Collectors.toList(), + iris -> + iris.stream().sorted(Comparator.comparing(URI::toString)).toList())))); + } + + private static ClassMapping mapped( + final Facts facts, + final Map.Entry> entry, + final Map> identityClasses, + final Hidden hidden) { + final OntologyConcept type = facts.classes().get(entry.getKey()); + final List tables = + entry.getValue().stream() + .filter(row -> facts.viewableTables().contains(row.assetId())) + .sorted(byRoleThenName(facts)) + .map(row -> binding(facts, row, identityClasses, hidden)) + .toList(); + return new ClassMapping(type.getIri(), type.getId(), tables); + } + + private static Comparator byRoleThenName(final Facts facts) { + return Comparator.comparingInt((BindingRow row) -> rank(row.role())) + .thenComparing(row -> facts.tables().get(row.assetId()).getFullyQualifiedName()); + } + + private static int rank(final OntologyBindingRole role) { + if (role == OntologyBindingRole.IDENTITY) { + return 0; + } + return role == OntologyBindingRole.CONTRIBUTING ? 1 : 2; + } + + private static TableBinding binding( + final Facts facts, + final BindingRow row, + final Map> identityClasses, + final Hidden hidden) { + final Table table = facts.tables().get(row.assetId()); + final List data = new ArrayList<>(); + final List relations = new ArrayList<>(); + final List> absent = new ArrayList<>(); + final List> missing = new ArrayList<>(); + for (final OntologyColumnBinding column : listOrEmpty(row.columns())) { + final OntologyProperty property = facts.properties().get(column.getPropertyId()); + if (OntologyBindingRules.resolveColumn(table, column.getColumnPath()) == null) { + if (property == null || facts.viewableProperties().contains(property.getId())) { + missing.add(column.getColumnPath()); + } + } else if (property == null) { + absent.add(column.getColumnPath()); + } else if (facts.viewableProperties().contains(property.getId())) { + listed(facts, column, property, identityClasses, hidden, data, relations); + } + } + return new TableBinding( + new TableRef( + table.getId(), + table.getFullyQualifiedName(), + table.getServiceType() == null ? null : table.getServiceType().value(), + listOrEmpty(table.getColumns())), + row.role(), + listOrEmpty(row.subjectKey()), + filterState(table, row.rowFilter()), + List.copyOf(data), + List.copyOf(relations), + List.copyOf(absent), + List.copyOf(missing)); + } + + private static void listed( + final Facts facts, + final OntologyColumnBinding column, + final OntologyProperty property, + final Map> identityClasses, + final Hidden hidden, + final List data, + final List relations) { + if (property.getKind() == OntologyPropertyKind.DATA) { + data.add(new DataColumn(property.getIri(), column.getColumnPath())); + } else if (property.getKind() == OntologyPropertyKind.OBJECT) { + relation(facts, column, property, identityClasses, hidden).ifPresent(relations::add); + } + } + + private static Optional relation( + final Facts facts, + final OntologyColumnBinding column, + final OntologyProperty property, + final Map> identityClasses, + final Hidden hidden) { + final OntologyColumnJoin join = column.getJoin(); + if (join == null) { + return Optional.of(new RelationColumn(property.getIri(), column.getColumnPath(), null)); + } + final UUID target = join.getTargetAssetId(); + if (!facts.tables().containsKey(target)) { + return Optional.empty(); + } + if (!facts.viewableTables().contains(target)) { + hidden.tables.add(target); + return Optional.empty(); + } + final List objects = + identityClasses.getOrDefault(target, List.of()).stream() + .filter(iri -> inRange(facts, property, iri)) + .toList(); + return Optional.of( + new RelationColumn( + property.getIri(), + column.getColumnPath(), + new Join( + join.getStatus(), + target, + join.getOn().stream() + .map(pair -> new ColumnPair(pair.getChild(), pair.getParent())) + .toList(), + objects))); + } + + /** A class is in the range of a relation when it is named there or sits below a named class. */ + private static boolean inRange( + final Facts facts, final OntologyProperty relation, final URI iri) { + final List range = listOrEmpty(relation.getRange()); + if (range.isEmpty()) { + return true; + } + final Set above = + OntologyClassHierarchy.reachable(facts.parents(), Set.of(iri.toString())); + return range.stream().map(URI::toString).anyMatch(above::contains); + } + + /** + * The filter as a statement would parse it now, or why it no longer applies. The reason names + * the table and the column and never a value. + */ + static RowFilterState filterState(final Table table, final OntologyRowFilter filter) { + if (filter == null) { + return null; + } + final var column = OntologyBindingRules.resolveColumn(table, filter.getColumn()); + if (column == null) { + return new Broken(String.format(FILTER_COLUMN_GONE, table.getFullyQualifiedName())); + } + try { + return new Applies(TypedValues.rowFilter(column, filter)); + } catch (final BadRequestException unparsed) { + return new Broken( + String.format( + FILTER_VALUE_UNPARSED, + table.getFullyQualifiedName(), + String.join(".", filter.getColumn()))); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappings.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappings.java new file mode 100644 index 000000000000..51e249bb5cfc --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyTableMappings.java @@ -0,0 +1,216 @@ +/* + * 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.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.service.ontology.OntologyRecordMapping.conflict; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyBindingAccess.TableViews; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyStatementService.DraftGate; +import org.openmetadata.service.ontology.OntologyTableMappingRules.Facts; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.util.FreshReadScope; + +/** + * Reads the table mapping of a whole version of an ontology as one value, for code in this server + * (ADR:2026-12-04-the-table-mapping-of-a-version-is-one-read). There is no endpoint. A caller that + * needs the whole mapping checks the three counts of the answer: a part the caller may not view is + * counted, never named, and never makes the read fail. + * + *

A call makes a fixed number of batched reads whatever the version holds: the ontology, its + * state and release, the ids of the classes, the binding revisions twice around the binding rows, + * the tables, the classes, the properties and, when a relation declares a range, the class + * hierarchy. A list of ids longer than one IN list is read in chunks. + */ +@Slf4j +public final class OntologyTableMappings { + private static final String CHANGED = + "The table bindings changed while the mapping was read. Ask again"; + + private final OntologyConceptBindingStore store; + private final CollectionDAO dao; + private final OntologyBindingAccess catalog; + private final OntologyMappingReader mapping; + private final DraftGate draftGate; + + public OntologyTableMappings( + final OntologyConceptBindingStore store, + final CollectionDAO dao, + final Authorizer authorizer, + final Function> repositories, + final DraftGate draftGate) { + this.store = store; + this.dao = dao; + this.catalog = new OntologyBindingAccess(authorizer, repositories); + this.mapping = new OntologyMappingReader(store, catalog); + this.draftGate = draftGate; + } + + /** + * The table mapping of {@code version} of an ontology as {@code access} may see it. + * + * @param version the version to read. Null means the active release, which a 404 refuses when + * the ontology has none. The draft needs the right to read the working draft, and a 403 + * refuses a caller without it. + * @throws jakarta.ws.rs.ClientErrorException with 409 when the bindings keep changing while they + * are read + */ + public OntologyTableMapping read( + final Access access, final UUID ontologyId, final OntologyStatementVersion version) { + try (final var ignored = FreshReadScope.enter()) { + final EntityReference ontology = ontology(access, ontologyId); + final OntologyVersion read = + version == OntologyStatementVersion.DRAFT + ? draft(access, ontology) + : OntologyVersion.release(dao, ontology); + final OntologyTableMapping mapped = mapped(access, ontologyId, read); + LOG.debug( + "Read the table mapping of ontology {}: {} classes, {} hidden tables, {} hidden classes," + + " {} hidden properties", + ontologyId, + mapped.classes().size(), + mapped.hiddenTables(), + mapped.hiddenClasses(), + mapped.hiddenProperties()); + return mapped; + } + } + + private EntityReference ontology(final Access access, final UUID ontologyId) { + return ((Ontology) + catalog.authorized(access, Entity.ONTOLOGY, ontologyId, MetadataOperation.VIEW_BASIC)) + .getEntityReference(); + } + + private OntologyVersion draft(final Access access, final EntityReference ontology) { + draftGate.require(access.securityContext(), ontology.getId()); + return OntologyVersion.draft(dao, ontology); + } + + private OntologyTableMapping mapped( + final Access access, final UUID ontologyId, final OntologyVersion version) { + final List rows = rows(version, ontologyId); + final TableViews tables = catalog.tableViews(access, tableIds(rows)); + final Set bound = + rows.stream() + .filter(row -> tables.live().containsKey(row.assetId())) + .map(BindingRow::conceptId) + .collect(Collectors.toSet()); + final Map classes = + byId(version.classes(store, ontologyId, bound), OntologyConcept::getId); + final Map properties = + byId( + version.properties(store, ontologyId, propertyIds(rows, tables)), + OntologyProperty::getId); + return OntologyTableMappingRules.build( + new Facts( + version.read(), + rows, + tables.live(), + tables.viewable(), + classes, + version.viewable( + catalog, access, Entity.ONTOLOGY_CONCEPT, List.copyOf(classes.values())), + properties, + version.viewable( + catalog, access, Entity.ONTOLOGY_PROPERTY, List.copyOf(properties.values())), + parents(version, ontologyId, classes, properties))); + } + + /** + * The table rows of the classes that bind tables. A class set that moves while the rows are read + * is read again, as a binding revision that moves is, so the rows and the set are one state. + */ + private List rows(final OntologyVersion version, final UUID ontologyId) { + for (int attempt = 0; attempt < OntologyMappingReader.BINDING_READ_ATTEMPTS; attempt++) { + final Set candidates = version.boundClassIds(store, ontologyId); + final List rows = + mapping.between(candidates, CHANGED, revisions -> store.allTableRows(candidates)); + if (version.fixedClassSet() || candidates.equals(version.boundClassIds(store, ontologyId))) { + return rows; + } + } + throw conflict(CHANGED); + } + + /** The tables that the rows bind and that their columns join. */ + private static Set tableIds(final List rows) { + final Set ids = new HashSet<>(); + for (final BindingRow row : rows) { + ids.add(row.assetId()); + listOrEmpty(row.columns()).stream() + .filter(column -> column.getJoin() != null) + .forEach(column -> ids.add(column.getJoin().getTargetAssetId())); + } + return ids; + } + + private static Set propertyIds(final List rows, final TableViews tables) { + return rows.stream() + .filter(row -> tables.live().containsKey(row.assetId())) + .flatMap(row -> listOrEmpty(row.columns()).stream()) + .map(OntologyColumnBinding::getPropertyId) + .collect(Collectors.toSet()); + } + + /** The class hierarchy, read only when a relation of the mapping declares a range. */ + private Map> parents( + final OntologyVersion version, + final UUID ontologyId, + final Map classes, + final Map properties) { + final boolean ranged = + properties.values().stream() + .anyMatch( + property -> + property.getKind() == OntologyPropertyKind.OBJECT + && !listOrEmpty(property.getRange()).isEmpty()); + if (!ranged) { + return Map.of(); + } + return version.namedParents( + store, + ontologyId, + classes.values().stream().map(type -> type.getIri().toString()).toList()); + } + + private static Map byId( + final List definitions, final Function id) { + return definitions.stream() + .collect(Collectors.toMap(id, Function.identity(), (first, second) -> first)); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyUnpublishedChanges.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyUnpublishedChanges.java index 88c8641f78d2..f9e6db342b46 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyUnpublishedChanges.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyUnpublishedChanges.java @@ -33,7 +33,8 @@ private record Member(MemberKind kind, UUID id) {} new Source(MemberKind.ONTOLOGY, "ontology_entity", "id"), new Source(MemberKind.CONCEPT, "ontology_concept_entity", "ontologyId"), new Source(MemberKind.PROPERTY, "ontology_property_entity", "ontologyId"), - new Source(MemberKind.AXIOM, "ontology_axiom_entity", "ontologyId")); + new Source(MemberKind.AXIOM, "ontology_axiom_entity", "ontologyId"), + new Source(MemberKind.SHAPE, "ontology_shape_entity", "ontologyId")); private final CollectionDAO dao; @@ -163,6 +164,7 @@ private List workingDefinitions( case CONCEPT -> dao.ontologyConceptDAO().findEntitiesByIds(ids, Include.NON_DELETED); case PROPERTY -> dao.ontologyPropertyDAO().findEntitiesByIds(ids, Include.NON_DELETED); case AXIOM -> dao.ontologyAxiomDAO().findEntitiesByIds(ids, Include.NON_DELETED); + case SHAPE -> dao.ontologyShapeDAO().findEntitiesByIds(ids, Include.NON_DELETED); default -> throw new IllegalArgumentException("Unsupported working member kind " + kind); }; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java new file mode 100644 index 000000000000..65e562f502f8 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyVersion.java @@ -0,0 +1,566 @@ +/* + * 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.ontology; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +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.stream.Collectors; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyReleaseMember; +import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; +import org.openmetadata.schema.type.OntologyState; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.EntityDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.ConceptAssetCount; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; + +/** + * The version of an ontology that a statement reads: its active release, or its working draft. The + * class, its properties, the display name flag and the relations come from that version. Table + * bindings sit outside versions (ADR:2026-11-22-record-statements-start-from-the-identity-table). + * + *

A release keeps the id of the working row it was captured from, and it answers as it was + * released: a definition is found among the members of the release by id, and a later delete of + * its working row changes nothing. The caller's right to a released definition is checked on the + * definition itself, with the policy inputs the catalog holds now for its id. The working draft + * is read through the working rows, which must be live. + */ +sealed interface OntologyVersion { + /** One statement reads at most this many of the shapes of a draft that name one class. */ + int MOST_SHAPES_NAMING_A_CLASS = 1000; + + /** The shape members of a release are read this many at a time. */ + int SHAPE_MEMBERS_READ = 1000; + + /** The definition a statement looks for, and what to do when it belongs to another ontology. */ + record Wanted( + String entityType, + MemberKind kind, + String noun, + UUID ontologyId, + Function otherOntology) {} + + /** What a plan says about the version it read. */ + OntologyStatementVersionRead read(); + + /** + * The definition as this version declares it, after the caller's right to view it is checked. A + * definition of another ontology is refused with {@code otherOntology}, and one that the version + * lacks is a 404 that names its IRI. + */ + OntologyDefinition declared(OntologyBindingAccess catalog, Access access, Wanted wanted, UUID id); + + /** The properties among {@code ids} that this version declares and the caller may view. */ + Map viewableProperties( + OntologyBindingAccess catalog, Access access, Collection ids); + + /** + * The ids of the definitions among {@code read} that the caller may view. They are definitions + * of one type, read from this version whoever asks, and they are authorized as they were read, + * with no second read. A row that changed between a second read and the first would be compiled + * from one and authorized from the other. The rows of a release are the definitions as released, + * so one whose working row is deleted since is still found. The rows of the working draft are + * the live working rows. The caller's right is the policy input that the catalog holds now for + * the id: owners, domains and reviewers, loaded onto the rows. + */ + default Set viewable( + final OntologyBindingAccess catalog, + final Access access, + final String entityType, + final List read) { + return read.isEmpty() + ? Set.of() + : Set.copyOf(catalog.viewable(access, entityType, read).keySet()); + } + + /** + * The id of the one class this version declares with one of {@code iris}, empty when it has + * none. + */ + Optional classNamed(OntologyConceptBindingStore store, UUID ontologyId, List iris); + + /** The shapes this version holds whose target is the class {@code iri}, in any order. */ + List shapesTargeting(OntologyConceptBindingStore store, UUID ontologyId, URI iri); + + /** The properties this version declares with one of {@code iris}. */ + List propertiesNamed( + OntologyConceptBindingStore store, UUID ontologyId, Collection iris); + + /** The classes this version declares with one of {@code iris}. */ + List classesNamed( + OntologyConceptBindingStore store, UUID ontologyId, Collection iris); + + /** + * The IRIs among the keys of {@code candidatesByIri} for which this version declares one of the + * classes in the entry as a subclass of the class with that IRI, however many named subclass + * steps apart. All the entries are answered together, so the statements do not grow with them. + */ + Set withSubclassAmong( + OntologyConceptBindingStore store, + UUID ontologyId, + Map> candidatesByIri); + + /** + * The ids of the classes of this version that may bind tables: for a release, every class it + * holds, and for the working draft, the live classes that bind any asset. + */ + Set boundClassIds(OntologyConceptBindingStore store, UUID ontologyId); + + /** Whether {@link #boundClassIds} always answers the same: true for a release, false for the draft. */ + boolean fixedClassSet(); + + /** The classes among {@code ids} that this version declares, as it declares them. */ + List classes( + OntologyConceptBindingStore store, UUID ontologyId, Collection ids); + + /** The properties among {@code ids} that this version declares, as it declares them. */ + List properties( + OntologyConceptBindingStore store, UUID ontologyId, Collection ids); + + /** + * The named parents, by IRI, of the classes that a walk up from {@code iris} reaches in this + * version. + */ + Map> namedParents( + OntologyConceptBindingStore store, UUID ontologyId, Collection iris); + + /** The active release of {@code ontology}, or a 404 that says it has none. */ + static OntologyVersion release(final CollectionDAO dao, final EntityReference ontology) { + final OntologyState state = dao.ontologyStateDAO().get(ontology.getId()); + if (state == null || state.getActiveReleaseId() == null) { + throw EntityNotFoundException.byMessage( + String.format("Ontology %s has no active release", ontology.getFullyQualifiedName())); + } + return new Release( + dao, + dao.ontologyReleaseDAO().findEntityById(state.getActiveReleaseId()), + ontology.getFullyQualifiedName()); + } + + /** The working draft of {@code ontology}. The caller has checked the right to read it. */ + static OntologyVersion draft(final CollectionDAO dao, final EntityReference ontology) { + final OntologyState state = dao.ontologyStateDAO().get(ontology.getId()); + return new Draft(state == null ? 0L : state.getWorkingRevision()); + } + + /** The working draft, whose definitions are the working rows themselves. */ + record Draft(long workingRevision) implements OntologyVersion { + @Override + public boolean fixedClassSet() { + return false; + } + + @Override + public OntologyStatementVersionRead read() { + return new OntologyStatementVersionRead() + .withKind(OntologyStatementVersion.DRAFT) + .withWorkingRevision(workingRevision); + } + + @Override + public OntologyDefinition declared( + final OntologyBindingAccess catalog, + final Access access, + final Wanted wanted, + final UUID id) { + final var working = + (OntologyDefinition) + catalog.authorized(access, wanted.entityType(), id, MetadataOperation.VIEW_BASIC); + if (!wanted.ontologyId().equals(working.getOntology().getId())) { + throw wanted.otherOntology().apply(working); + } + return working; + } + + @Override + public Map viewableProperties( + final OntologyBindingAccess catalog, final Access access, final Collection ids) { + return catalog.viewable(access, Entity.ONTOLOGY_PROPERTY, ids).values().stream() + .map(OntologyProperty.class::cast) + .collect(Collectors.toMap(OntologyProperty::getId, Function.identity())); + } + + @Override + public Optional classNamed( + final OntologyConceptBindingStore store, final UUID ontologyId, final List iris) { + return store.liveConcepts(ontologyId, iris).stream().findFirst().map(OntologyConcept::getId); + } + + /** + * One statement reads the live shapes that name the class, as a target or in a constraint. A + * class that more shapes name than one statement reads gets no answer, because a shape left + * out would be a constraint left unchecked. + */ + @Override + public List shapesTargeting( + final OntologyConceptBindingStore store, final UUID ontologyId, final URI iri) { + final List naming = + store.shapesNamingClass(ontologyId, iri, MOST_SHAPES_NAMING_A_CLASS + 1); + if (naming.size() > MOST_SHAPES_NAMING_A_CLASS) { + throw OntologyRecordMapping.conflict( + "More than %d shapes name class %s", MOST_SHAPES_NAMING_A_CLASS, iri); + } + return naming.stream().filter(shape -> iri.equals(shape.getTargetConcept())).toList(); + } + + @Override + public List propertiesNamed( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection iris) { + return store.liveProperties(ontologyId, iris); + } + + @Override + public List classesNamed( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection iris) { + return store.liveConcepts(ontologyId, iris); + } + + @Override + public Set boundClassIds(final OntologyConceptBindingStore store, final UUID ontologyId) { + return store.boundConcepts(ontologyId, Integer.MAX_VALUE, 0).stream() + .map(ConceptAssetCount::conceptId) + .collect(Collectors.toSet()); + } + + @Override + public List classes( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection ids) { + return store.liveConcepts(ids).stream() + .filter(concept -> ontologyId.equals(concept.getOntology().getId())) + .toList(); + } + + @Override + public List properties( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection ids) { + return store.liveProperties(ids).stream() + .filter(property -> ontologyId.equals(property.getOntology().getId())) + .toList(); + } + + @Override + public Map> namedParents( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection iris) { + return store.namedParentsAbove(ontologyId, iris); + } + + @Override + public Set withSubclassAmong( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Map> candidatesByIri) { + final Map iriById = new HashMap<>(); + store + .liveConcepts( + candidatesByIri.values().stream().flatMap(Collection::stream).distinct().toList()) + .stream() + .filter(candidate -> ontologyId.equals(candidate.getOntology().getId())) + .forEach(candidate -> iriById.put(candidate.getId(), candidate.getIri().toString())); + final Map> parents = + store.namedParentsAbove(ontologyId, Set.copyOf(iriById.values())); + return candidatesByIri.entrySet().stream() + .filter( + entry -> + OntologyClassHierarchy.reachable( + parents, + entry.getValue().stream() + .map(iriById::get) + .filter(Objects::nonNull) + .toList()) + .contains(entry.getKey().toString())) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + } + } + + /** A sealed release, whose members are stored payloads that never change. */ + record Release(CollectionDAO dao, OntologyRelease release, String ontologyName) + implements OntologyVersion { + @Override + public boolean fixedClassSet() { + return true; + } + + @Override + public OntologyStatementVersionRead read() { + return new OntologyStatementVersionRead() + .withKind(OntologyStatementVersion.RELEASE) + .withReleaseId(release.getId()) + .withReleaseRevision(release.getReleaseRevision()) + .withSemanticVersion(release.getSemanticVersion()); + } + + /** + * A class is found by IRI through the working rows, deleted ones too, and kept only when the + * release holds a member with that id and that IRI. A class deleted for good and made again + * with the same IRI has a new id, which the release lacks, so it is not found. + */ + @Override + public Optional classNamed( + final OntologyConceptBindingStore store, final UUID ontologyId, final List iris) { + return store.workingConcepts(ontologyId, iris).stream() + .filter( + row -> + member(MemberKind.CONCEPT, row.getId()) + .map(held -> ((OntologyConcept) held).getIri().equals(row.getIri())) + .orElse(false)) + .findFirst() + .map(OntologyConcept::getId); + } + + /** The shape members of the release, read a page at a time, since no index names a target. */ + @Override + public List shapesTargeting( + final OntologyConceptBindingStore store, final UUID ontologyId, final URI iri) { + final List targeting = new ArrayList<>(); + String after = ""; + List page; + do { + page = + dao.ontologyReleaseDAO() + .listMembers(release.getId(), MemberKind.SHAPE.value(), after, SHAPE_MEMBERS_READ); + for (final OntologyReleaseMember member : page) { + final OntologyShape shape = + (OntologyShape) OntologyReleaseReader.definition(release, member); + if (iri.equals(shape.getTargetConcept())) { + targeting.add(shape); + } + after = member.getMemberId().toString(); + } + } while (page.size() == SHAPE_MEMBERS_READ); + return List.copyOf(targeting); + } + + @Override + public List propertiesNamed( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection iris) { + return released( + MemberKind.PROPERTY, + store.workingProperties(ontologyId, iris).stream().map(OntologyProperty::getId).toList(), + OntologyProperty.class, + property -> iris.contains(property.getIri())); + } + + @Override + public List classesNamed( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection iris) { + return released( + MemberKind.CONCEPT, + store.workingConcepts(ontologyId, iris).stream().map(OntologyConcept::getId).toList(), + OntologyConcept.class, + concept -> iris.contains(concept.getIri())); + } + + @Override + public Set boundClassIds(final OntologyConceptBindingStore store, final UUID ontologyId) { + return dao + .ontologyReleaseDAO() + .listAllMemberVersions(List.of(release.getId().toString())) + .stream() + .filter(member -> MemberKind.CONCEPT.value().equals(member.memberKind())) + .map(member -> UUID.fromString(member.memberId())) + .collect(Collectors.toSet()); + } + + @Override + public List classes( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection ids) { + return released(MemberKind.CONCEPT, List.copyOf(ids), OntologyConcept.class, concept -> true); + } + + @Override + public List properties( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection ids) { + return released( + MemberKind.PROPERTY, List.copyOf(ids), OntologyProperty.class, property -> true); + } + + @Override + public Map> namedParents( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Collection iris) { + return OntologyClassHierarchy.namedEdges( + new OntologyReleaseReader(dao) + .read(release, unchecked -> {}).stream() + .map(member -> OntologyReleaseReader.definition(release, member)) + .toList()); + } + + /** + * The subclass steps come from the axioms of the release, so the answer is the released one + * whatever the draft changed since. The release is read whole, through the cache that every + * whole read of a sealed release shares. + */ + @Override + public Set withSubclassAmong( + final OntologyConceptBindingStore store, + final UUID ontologyId, + final Map> candidatesByIri) { + final List members = + new OntologyReleaseReader(dao) + .read(release, unchecked -> {}).stream() + .map(member -> OntologyReleaseReader.definition(release, member)) + .toList(); + final List classes = + members.stream() + .filter(OntologyConcept.class::isInstance) + .map(OntologyConcept.class::cast) + .toList(); + final Map> parents = OntologyClassHierarchy.namedEdges(members); + return candidatesByIri.entrySet().stream() + .filter( + entry -> + OntologyClassHierarchy.reachable( + parents, + classes.stream() + .filter(type -> entry.getValue().contains(type.getId())) + .map(type -> type.getIri().toString()) + .toList()) + .contains(entry.getKey().toString())) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + } + + /** + * The members of one kind with these ids that the release declares with a wanted IRI, in one + * statement. The ids come from the working rows, deleted ones too, so a definition is found + * as it was released whatever the draft lost since. + */ + private List released( + final MemberKind kind, + final List ids, + final Class type, + final Predicate wanted) { + final List memberIds = ids.stream().distinct().map(UUID::toString).toList(); + final List releaseIds = List.of(release.getId().toString()); + final List members = + memberIds.isEmpty() + ? List.of() + : EntityDAO.queryInChunks( + memberIds, + chunk -> + dao.ontologyReleaseDAO().listMemberPayloads(releaseIds, kind.value(), chunk)); + return members.stream() + .map(member -> type.cast(OntologyReleaseReader.definition(release, member))) + .filter(wanted) + .toList(); + } + + /** The member of this release with the id, or empty when the release lacks it. */ + Optional member(final MemberKind kind, final UUID id) { + return Optional.ofNullable( + dao.ontologyReleaseDAO().getMember(release.getId(), kind.value(), id)) + .map(member -> OntologyReleaseReader.definition(release, member)); + } + + @Override + public OntologyDefinition declared( + final OntologyBindingAccess catalog, + final Access access, + final Wanted wanted, + final UUID id) { + final Optional held = member(wanted.kind(), id); + if (held.isPresent()) { + return (OntologyDefinition) + catalog.authorized( + access, wanted.entityType(), held.get(), MetadataOperation.VIEW_BASIC); + } + // The release lacks it. The working row, deleted or not, says which refusal fits: a + // definition of another ontology is a 400, and one of this ontology is a 404. + final var working = + (OntologyDefinition) + catalog.authorizedWorking( + access, wanted.entityType(), id, MetadataOperation.VIEW_BASIC); + if (!wanted.ontologyId().equals(working.getOntology().getId())) { + throw wanted.otherOntology().apply(working); + } + throw lacks(wanted.noun(), iriOf(working)); + } + + private static URI iriOf(final OntologyDefinition definition) { + return definition instanceof OntologyConcept concept + ? concept.getIri() + : ((OntologyProperty) definition).getIri(); + } + + /** The 404 for a class or relation that this release does not hold. */ + EntityNotFoundException lacks(final String noun, final URI iri) { + return EntityNotFoundException.byMessage( + String.format( + "%s %s is not in the active release of ontology %s", noun, iri, ontologyName)); + } + + @Override + public Map viewableProperties( + final OntologyBindingAccess catalog, final Access access, final Collection ids) { + final List memberIds = ids.stream().map(UUID::toString).toList(); + final List releaseIds = List.of(release.getId().toString()); + final List members = + memberIds.isEmpty() + ? List.of() + : EntityDAO.queryInChunks( + memberIds, + chunk -> + dao.ontologyReleaseDAO() + .listMemberPayloads(releaseIds, MemberKind.PROPERTY.value(), chunk)); + final List released = + members.stream() + .map(member -> (OntologyProperty) OntologyReleaseReader.definition(release, member)) + .toList(); + return catalog.viewable(access, Entity.ONTOLOGY_PROPERTY, released).values().stream() + .map(OntologyProperty.class::cast) + .collect(Collectors.toMap(OntologyProperty::getId, Function.identity())); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyWorkingSnapshot.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyWorkingSnapshot.java index 03ddd274ad0b..70a107b96e78 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyWorkingSnapshot.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologyWorkingSnapshot.java @@ -57,7 +57,9 @@ public static OntologyWorkingSnapshot production() { MemberKind.PROPERTY, (OntologyEntityRepository) Entity.getEntityRepository(Entity.ONTOLOGY_PROPERTY), MemberKind.AXIOM, - (OntologyEntityRepository) Entity.getEntityRepository(Entity.ONTOLOGY_AXIOM))); + (OntologyEntityRepository) Entity.getEntityRepository(Entity.ONTOLOGY_AXIOM), + MemberKind.SHAPE, + (OntologyEntityRepository) Entity.getEntityRepository(Entity.ONTOLOGY_SHAPE))); } /** Reads under the `ontology_state` row lock, so the callback runs with every writer excluded. */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/TableProfileFacts.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/TableProfileFacts.java new file mode 100644 index 000000000000..8781aebbebb1 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/TableProfileFacts.java @@ -0,0 +1,71 @@ +/* + * 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.ontology; + +import java.util.Comparator; +import org.openmetadata.schema.type.TableProfile; + +/** + * What a stored table profile states about the table: its row count when that is an exact + * non-negative whole number, when it was taken, and whether its column metrics were computed on a + * sample. Sampling is read from the profile's own sample fields, never from the table's current + * profiler settings, which may have changed since. + */ +record TableProfileFacts(Long rowCount, long profiledAt, boolean sampled) { + private static final double FULL_PERCENTAGE = 100d; + private static final Comparator RECENCY = + Comparator.comparingLong(TableProfileFacts::profiledAt) + .thenComparing( + TableProfileFacts::rowCount, Comparator.nullsFirst(Comparator.naturalOrder())) + .thenComparing(TableProfileFacts::sampled); + + /** + * The later of two profiles of one table. Equal timestamps, which differing operations can + * produce, are broken by the larger row count (absent is smallest), then by sampled over whole, + * so the outcome never depends on the order rows are read in. + */ + static TableProfileFacts latest(final TableProfileFacts first, final TableProfileFacts second) { + return RECENCY.compare(second, first) > 0 ? second : first; + } + + /** Null when the profile carries no timestamp, since such a profile cannot be placed in time. */ + static TableProfileFacts from(final TableProfile profile) { + if (profile == null || profile.getTimestamp() == null) { + return null; + } + final Long rowCount = exactRowCount(profile.getRowCount()); + return new TableProfileFacts(rowCount, profile.getTimestamp(), sampled(profile)); + } + + private static Long exactRowCount(final Number rowCount) { + if (rowCount == null) { + return null; + } + final double value = rowCount.doubleValue(); + final boolean wholeAndNonNegative = value >= 0 && value == Math.rint(value); + return wholeAndNonNegative && value < Long.MAX_VALUE ? (long) value : null; + } + + private static boolean sampled(final TableProfile profile) { + final Number sample = profile.getProfileSample(); + if (sample == null) { + return false; + } + if (profile.getProfileSampleType() == TableProfile.ProfileSampleType.ROWS) { + final Number rowCount = profile.getRowCount(); + return rowCount == null || sample.doubleValue() < rowCount.doubleValue(); + } + return sample.doubleValue() < FULL_PERCENTAGE; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/BoundStatement.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/BoundStatement.java new file mode 100644 index 000000000000..3dcd2169d4bd --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/BoundStatement.java @@ -0,0 +1,26 @@ +/* + * 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.ontology.sql; + +import java.util.List; + +/** + * The form of a statement that a driver binds. + * + * @param text the statement with a named parameter where each value goes: {@code :p0}, {@code :p1} + * and so on. Every other colon is written {@code \:}, so no name in the text reads as a + * parameter + * @param parameters the value of each parameter, in the order the text names them + */ +public record BoundStatement(String text, List parameters) {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/FinishedStatement.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/FinishedStatement.java new file mode 100644 index 000000000000..a017fd3a7025 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/FinishedStatement.java @@ -0,0 +1,23 @@ +/* + * 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.ontology.sql; + +/** + * One statement in its two finished forms, which only {@link SqlEngineFamily#finish} writes. + * + * @param sql the form a person reads, with every colon written as a colon + * @param escapedSql the form a reader of {@code :name} parameters runs, with every colon written + * {@code \:} + */ +public record FinishedStatement(String sql, String escapedSql) {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySqlReservedWords.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/OntologySqlReservedWords.java similarity index 97% rename from openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySqlReservedWords.java rename to openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/OntologySqlReservedWords.java index 44129bf5c378..7d1a49127771 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/OntologySqlReservedWords.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/OntologySqlReservedWords.java @@ -11,13 +11,13 @@ * limitations under the License. */ -package org.openmetadata.service.ontology; +package org.openmetadata.service.ontology.sql; import java.util.Set; /** * Words the ANSI dialect cannot read as a plain column or table name. Every other dialect quotes - * every identifier, so it needs no list. + * every name, so it needs no list. */ final class OntologySqlReservedWords { /** Vendor lists of the ANSI engines: PostgreSQL 14, Redshift, Trino, Presto, Athena SELECT. */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/ParsedValue.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/ParsedValue.java new file mode 100644 index 000000000000..422e1aad4947 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/ParsedValue.java @@ -0,0 +1,44 @@ +/* + * 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.ontology.sql; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.UUID; + +/** + * A value in the Java type its column's data type calls for. An engine family writes each variant + * from this parsed form, never from the text the value arrived as, and a driver binds it as it is. + */ +public sealed interface ParsedValue { + record WholeNumber(BigInteger value) implements ParsedValue {} + + record DecimalNumber(BigDecimal value) implements ParsedValue {} + + record Text(String value) implements ParsedValue {} + + record Bool(boolean value) implements ParsedValue {} + + record CalendarDate(LocalDate value) implements ParsedValue {} + + record TimeOfDay(LocalTime value) implements ParsedValue {} + + /** A date and a time of day with no offset. */ + record Timestamp(LocalDateTime value) implements ParsedValue {} + + record Uuid(UUID value) implements ParsedValue {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/SqlEngineFamily.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/SqlEngineFamily.java new file mode 100644 index 000000000000..02b88e964403 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/SqlEngineFamily.java @@ -0,0 +1,364 @@ +/* + * 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.ontology.sql; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import org.openmetadata.schema.api.data.OntologyConceptQueryDialect; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.ontology.sql.TypedStatement.Part; + +/** + * The engines that read a name, a string and a search pattern the same way. Two engines of one + * dialect can still read a backslash differently, so the family writes them, not the dialect. + * + *

{@link #finish} is the one place where a value becomes statement text. A service type is + * listed only when its engine reads what its family writes; any other type is a named 400 + * (ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text). + */ +public enum SqlEngineFamily { + POSTGRES( + OntologyConceptQueryDialect.ANSI, + Names.QUOTED_WHEN_NEEDED, + Strings.E_WHEN_BACKSLASHED, + Wildcards.BANG, + "Postgres", + "Timescale"), + REDSHIFT( + OntologyConceptQueryDialect.ANSI, + Names.QUOTED_WHEN_NEEDED, + Strings.DOUBLED_BACKSLASH, + Wildcards.BANG, + "Redshift"), + TRINO( + OntologyConceptQueryDialect.ANSI, + Names.QUOTED_WHEN_NEEDED, + Strings.STANDARD, + Wildcards.BANG, + "Trino", + "Presto", + "Athena"), + MYSQL( + OntologyConceptQueryDialect.MYSQL, + Names.BACKTICKS, + Strings.DOUBLED_BACKSLASH, + Wildcards.BACKSLASH, + "Mysql", + "MariaDB", + "SingleStore", + "Doris", + "StarRocks"), + CLICKHOUSE( + OntologyConceptQueryDialect.MYSQL, + Names.ESCAPED_BACKTICKS, + Strings.DOUBLED_BACKSLASH, + Wildcards.BACKSLASH, + "Clickhouse"), + BIGQUERY( + OntologyConceptQueryDialect.BIGQUERY, + Names.ESCAPED_BACKTICKS, + Strings.BACKSLASHED_QUOTE, + Wildcards.BACKSLASH, + "BigQuery"), + SNOWFLAKE( + OntologyConceptQueryDialect.SNOWFLAKE, + Names.DOUBLE_QUOTED, + Strings.DOUBLED_BACKSLASH, + Wildcards.BANG, + "Snowflake"), + SPARK( + OntologyConceptQueryDialect.SPARK, + Names.BACKTICKS, + Strings.BACKSLASHED_QUOTE, + Wildcards.BACKSLASH, + "Databricks", + "UnityCatalog", + "Hive", + "Impala", + "Iomete"), + TSQL( + OntologyConceptQueryDialect.TSQL, + Names.BRACKETS, + Strings.NATIONAL, + Wildcards.BANG_AND_BRACKET, + "Mssql", + "AzureSQL", + "Synapse", + "MicrosoftFabric"); + + private static final Map BY_SERVICE_TYPE = + Arrays.stream(values()) + .flatMap(family -> family.serviceTypes.stream().map(type -> Map.entry(type, family))) + .collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue)); + + private final OntologyConceptQueryDialect dialect; + private final Names names; + private final Strings strings; + private final Wildcards wildcards; + private final Set serviceTypes; + + SqlEngineFamily( + final OntologyConceptQueryDialect dialect, + final Names names, + final Strings strings, + final Wildcards wildcards, + final String... serviceTypes) { + this.dialect = dialect; + this.names = names; + this.strings = strings; + this.wildcards = wildcards; + this.serviceTypes = Set.of(serviceTypes); + } + + public static SqlEngineFamily ofServiceType(final String serviceType) { + return forServiceType(serviceType) + .orElseThrow( + () -> + new BadRequestException( + String.format("SQL generation does not support %s", serviceType))); + } + + /** The family that writes for the service type, or empty when no statement is written for it. */ + public static Optional forServiceType(final String serviceType) { + return Optional.ofNullable(serviceType).map(BY_SERVICE_TYPE::get); + } + + public OntologyConceptQueryDialect dialect() { + return dialect; + } + + /** + * The finished text of {@code statement}, for a consumer that takes one SQL string and no + * parameters. Every colon is written {@code \:}, in a name and in a string too, so a consumer + * that looks for {@code :name} parameters in the text finds none and reads back the colon. + */ + public String inline(final TypedStatement statement) { + return finish(statement).escapedSql(); + } + + /** + * Both finished forms of {@code statement}, written once: the text a person reads, and that text + * with every colon written {@code \:}. The second form is the one to run through a reader of + * {@code :name} parameters. The first would start a parameter at each colon there. + */ + public FinishedStatement finish(final TypedStatement statement) { + final StringBuilder text = new StringBuilder(); + for (final Part part : statement.parts()) { + text.append( + switch (part) { + case Part.Sql sql -> sql.text(); + case Part.Name name -> names.quote(name.name()); + case Part.Value value -> literal(value.value()); + case Part.Contains contains -> strings.literal(pattern(contains.text())) + + wildcards.clause(); + }); + } + return new FinishedStatement(text.toString(), escapeColons(text.toString())); + } + + /** The form of {@code statement} that a driver binds, with each value as a parameter. */ + public BoundStatement bind(final TypedStatement statement) { + final StringBuilder text = new StringBuilder(); + final List parameters = new ArrayList<>(); + for (final Part part : statement.parts()) { + text.append( + switch (part) { + case Part.Sql sql -> sql.text(); + case Part.Name name -> escapeColons(names.quote(name.name())); + case Part.Value value -> parameter(parameters, value.value()); + case Part.Contains contains -> parameter(parameters, bindable(contains.text())) + + wildcards.clause(); + }); + } + return new BoundStatement(text.toString(), List.copyOf(parameters)); + } + + private static String parameter(final List parameters, final TypedValue value) { + parameters.add(value); + return ":p" + (parameters.size() - 1); + } + + /** The pattern a driver binds for a search. Its wildcards are escaped and the driver quotes it. */ + private TypedValue bindable(final TypedValue searched) { + return TypedValues.pattern(searched, pattern(searched)); + } + + private String pattern(final TypedValue searched) { + return wildcards.containing(((ParsedValue.Text) searched.parsed()).value()); + } + + private static String escapeColons(final String text) { + return text.replace(":", "\\:"); + } + + private String literal(final TypedValue value) { + return switch (value.parsed()) { + case ParsedValue.WholeNumber number -> number.value().toString(); + case ParsedValue.DecimalNumber number -> number.value().toPlainString(); + case ParsedValue.Text text -> strings.literal(text.value()); + case ParsedValue.Bool bool -> bool(bool.value()); + case ParsedValue.CalendarDate date -> typed( + "DATE", "date", TypedValues.DATE.format(date.value())); + case ParsedValue.TimeOfDay time -> typed( + "TIME", "time", TypedValues.TIME.format(time.value())); + case ParsedValue.Timestamp timestamp -> timestamp(value.type(), timestamp.value()); + case ParsedValue.Uuid uuid -> uuid(uuid.value().toString()); + }; + } + + private String bool(final boolean value) { + if (this == TSQL) { + return value ? "1" : "0"; + } + return value ? "TRUE" : "FALSE"; + } + + /** A typed literal, or on T-SQL, which has none, a cast of a Unicode string. */ + private String typed(final String keyword, final String castType, final String text) { + return this == TSQL + ? "CAST(" + strings.literal(text) + " AS " + castType + ")" + : keyword + " " + strings.literal(text); + } + + /** + * BigQuery compares a DATETIME column with a DATETIME literal only. T-SQL reads the form with a + * {@code T} the same way under every session date format. + */ + private String timestamp(final ColumnDataType type, final LocalDateTime value) { + final String date = TypedValues.DATE.format(value); + final String time = TypedValues.TIME.format(value); + final boolean datetime = this == BIGQUERY && type == ColumnDataType.DATETIME; + return typed( + datetime ? "DATETIME" : "TIMESTAMP", "datetime2", date + (this == TSQL ? "T" : " ") + time); + } + + /** Trino compares a UUID column with a UUID literal only. The others read a string. */ + private String uuid(final String text) { + return this == TRINO ? "UUID " + strings.literal(text) : strings.literal(text); + } + + /** + * How a family writes a name the catalog holds. Quoting never changes how the backtick and + * bracket engines resolve a name, so they quote every name. + */ + private enum Names { + /** + * These engines store and fold names in lowercase, so only a name that folding or a reserved + * word would misread is quoted. + */ + QUOTED_WHEN_NEEDED, + /** + * The catalog holds each name in the case the engine reports, so the quoted name always + * resolves to the stored object, while an unquoted lowercase name would fold to upper case. + */ + DOUBLE_QUOTED, + BACKTICKS, + /** These engines read backslash escapes inside a backtick name. */ + ESCAPED_BACKTICKS, + BRACKETS; + + private static final Pattern PLAIN = Pattern.compile("[a-z_][a-z0-9_]*"); + + String quote(final String name) { + return switch (this) { + case QUOTED_WHEN_NEEDED -> readsPlain(name) ? name : doubleQuoted(name); + case DOUBLE_QUOTED -> doubleQuoted(name); + case BACKTICKS -> "`" + name.replace("`", "``") + "`"; + case ESCAPED_BACKTICKS -> "`" + name.replace("\\", "\\\\").replace("`", "\\`") + "`"; + case BRACKETS -> "[" + name.replace("]", "]]") + "]"; + }; + } + + private static boolean readsPlain(final String name) { + return PLAIN.matcher(name).matches() && !OntologySqlReservedWords.ANSI.contains(name); + } + + private static String doubleQuoted(final String name) { + return "\"" + name.replace("\"", "\"\"") + "\""; + } + } + + /** How a family writes character data as a string literal. */ + private enum Strings { + /** The quote doubled and a backslash as it is. */ + STANDARD, + /** A Unicode string, {@code N'…'}, with the quote doubled. */ + NATIONAL, + /** The backslash and the quote doubled. These engines read a backslash as an escape. */ + DOUBLED_BACKSLASH, + /** The backslash doubled and the quote written {@code \'}. These engines read no doubled quote. */ + BACKSLASHED_QUOTE, + /** + * {@code E'…'} with the backslash doubled when the text holds a backslash, the standard form + * otherwise. Both read the same whether or not the server reads backslash escapes in an + * ordinary string. + */ + E_WHEN_BACKSLASHED; + + String literal(final String text) { + return switch (this) { + case STANDARD -> "'" + text.replace("'", "''") + "'"; + case NATIONAL -> "N" + STANDARD.literal(text); + case DOUBLED_BACKSLASH -> STANDARD.literal(text.replace("\\", "\\\\")); + case BACKSLASHED_QUOTE -> "'" + text.replace("\\", "\\\\").replace("'", "\\'") + "'"; + case E_WHEN_BACKSLASHED -> text.contains("\\") + ? "E" + DOUBLED_BACKSLASH.literal(text) + : STANDARD.literal(text); + }; + } + } + + /** How a family makes {@code %} and {@code _} plain in the operand of {@code LIKE}. */ + private enum Wildcards { + BANG("!%_", '!', " ESCAPE '!'"), + /** T-SQL also reads {@code [} as the start of a character class. */ + BANG_AND_BRACKET("!%_[", '!', " ESCAPE '!'"), + /** These engines escape with a backslash and take no other escape character. */ + BACKSLASH("\\%_", '\\', ""); + + private final String special; + private final char escape; + private final String clause; + + Wildcards(final String special, final char escape, final String clause) { + this.special = special; + this.escape = escape; + this.clause = clause; + } + + String clause() { + return clause; + } + + /** The pattern that matches any text containing {@code text} as it is written. */ + String containing(final String text) { + final StringBuilder pattern = new StringBuilder("%"); + for (final char character : text.toCharArray()) { + if (special.indexOf(character) >= 0) { + pattern.append(escape); + } + pattern.append(character); + } + return pattern.append('%').toString(); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedRowFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedRowFilter.java new file mode 100644 index 000000000000..a4e854c8d1f0 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedRowFilter.java @@ -0,0 +1,85 @@ +/* + * 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.ontology.sql; + +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Objects; +import org.openmetadata.schema.type.OntologyRowFilterOperator; + +/** + * A table binding's row filter with each value parsed as the data type of the column it compares. + * Only {@link TypedValues#rowFilter} makes one, so a null test holds no value, a comparison holds + * one, and {@code in} holds 1 to 100. + */ +public final class TypedRowFilter { + private final List column; + private final OntologyRowFilterOperator operator; + private final List values; + + TypedRowFilter( + final List column, + final OntologyRowFilterOperator operator, + final List values) { + this.column = List.copyOf(column); + this.operator = operator; + this.values = List.copyOf(values); + } + + /** The path of the compared column. */ + @JsonProperty("column") + public List column() { + return column; + } + + @JsonProperty("operator") + public OntologyRowFilterOperator operator() { + return operator; + } + + @JsonProperty("values") + public List values() { + return values; + } + + /** Writes the filter as a predicate, with the column under {@code alias} when one is given. */ + public TypedStatement.Builder appendTo( + final TypedStatement.Builder statement, final String alias) { + final TypedStatement.Builder sql = statement.column(alias, column); + return switch (operator) { + case IS_NULL -> sql.sql(" IS NULL"); + case IS_NOT_NULL -> sql.sql(" IS NOT NULL"); + case IN -> sql.sql(" IN ").values(values); + case EQUALS -> sql.sql(" = ").value(values.getFirst()); + case NOT_EQUALS -> sql.sql(" <> ").value(values.getFirst()); + case LESS_THAN -> sql.sql(" < ").value(values.getFirst()); + case LESS_THAN_OR_EQUALS -> sql.sql(" <= ").value(values.getFirst()); + case GREATER_THAN -> sql.sql(" > ").value(values.getFirst()); + case GREATER_THAN_OR_EQUALS -> sql.sql(" >= ").value(values.getFirst()); + }; + } + + @Override + public boolean equals(final Object other) { + return other instanceof TypedRowFilter filter + && column.equals(filter.column) + && operator == filter.operator + && values.equals(filter.values); + } + + @Override + public int hashCode() { + return Objects.hash(column, operator, values); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedStatement.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedStatement.java new file mode 100644 index 000000000000..36ee5b7fd808 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedStatement.java @@ -0,0 +1,139 @@ +/* + * 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.ontology.sql; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; +import org.openmetadata.service.exception.BadRequestException; + +/** + * A SQL statement whose values stay apart from its text. It is an ordered list of parts of four + * kinds: text the code wrote, names the catalog holds, typed values, and text to search for. A + * statement never holds a value as text. An {@link SqlEngineFamily} turns it into finished text or + * into the form a driver binds (ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text). + */ +public final class TypedStatement { + sealed interface Part { + record Sql(String text) implements Part {} + + record Name(String name) implements Part {} + + record Value(TypedValue value) implements Part {} + + record Contains(TypedValue text) implements Part {} + } + + private final List parts; + + private TypedStatement(final List parts) { + this.parts = List.copyOf(parts); + } + + public static Builder builder() { + return new Builder(); + } + + List parts() { + return parts; + } + + public static final class Builder { + /** + * What statement text may hold. It has no quote, backslash, colon, semicolon, minus or slash, + * so text can open no string, quoted name, bind parameter or comment and can end no statement. + * A string or a quoted name reaches a statement only through {@link #value} and {@link #name}. + * The tilde is the match operator of a regular expression. + */ + private static final Pattern WRITTEN_TEXT = Pattern.compile("[A-Za-z0-9_ ,.()*=<>~\n]*"); + + private final List parts = new ArrayList<>(); + + private Builder() {} + + /** Text the code wrote: keywords, operators, aliases and numbers the code chose. */ + public Builder sql(final String text) { + if (!WRITTEN_TEXT.matcher(text).matches()) { + throw new IllegalArgumentException( + "Statement text takes letters, digits, spaces, line breaks and _ , . ( ) * = < > ~." + + " Pass a name to name() and a value to value()"); + } + parts.add(new Part.Sql(text)); + return this; + } + + /** A name the catalog holds, which the engine family quotes. */ + public Builder name(final String name) { + if (TypedValues.holdsControlCharacter(name)) { + throw new BadRequestException( + "SQL generation does not support a name that holds a control character"); + } + parts.add(new Part.Name(name)); + return this; + } + + /** A column: the alias when one is given, then each segment of the path as a name. */ + public Builder column(final String alias, final List path) { + if (alias != null) { + sql(alias + "."); + } + name(path.getFirst()); + path.subList(1, path.size()).forEach(segment -> sql(".").name(segment)); + return this; + } + + public Builder value(final TypedValue value) { + parts.add(new Part.Value(value)); + return this; + } + + /** The values in parentheses, separated by commas, as {@code IN} takes them. */ + public Builder values(final List values) { + sql("(").value(values.getFirst()); + values.subList(1, values.size()).forEach(value -> sql(", ").value(value)); + return sql(")"); + } + + /** + * The operand of {@code LIKE} that matches text containing {@code text}. The engine family + * escapes the wildcards and adds the escape clause its engines need. + */ + public Builder contains(final TypedValue text) { + if (!(text.parsed() instanceof ParsedValue.Text)) { + throw new IllegalArgumentException("LIKE searches character data only"); + } + parts.add(new Part.Contains(text)); + return this; + } + + /** + * Every part of {@code inner}, as a statement inside this one. Each line of the inner + * statement starts where {@code lineBreak} ends, so a nested statement reads as nested. + */ + public Builder nested(final TypedStatement inner, final String lineBreak) { + for (final Part part : inner.parts) { + if (part instanceof Part.Sql written) { + sql(written.text().replace("\n", lineBreak)); + } else { + parts.add(part); + } + } + return this; + } + + public TypedStatement build() { + return new TypedStatement(parts); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValue.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValue.java new file mode 100644 index 000000000000..e1dc7cdedb89 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValue.java @@ -0,0 +1,77 @@ +/* + * 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.ontology.sql; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Objects; +import org.openmetadata.schema.type.ColumnDataType; + +/** + * One value for one column, parsed as that column's data type. Only {@link TypedValues} makes one, + * so holding a typed value means the value parsed: a string is within the length cap and holds no + * control character, a number is in its canonical form and inside its column's range. + */ +public final class TypedValue { + private final ColumnDataType type; + private final ParsedValue parsed; + private final String source; + + TypedValue(final ColumnDataType type, final ParsedValue parsed, final String source) { + this.type = type; + this.parsed = parsed; + this.source = source; + } + + /** The column's data type as the catalog records it. */ + @JsonProperty("type") + public ColumnDataType type() { + return type; + } + + /** The value as its data type holds it. An engine family writes SQL from this and nothing else. */ + @JsonIgnore + public ParsedValue parsed() { + return parsed; + } + + /** + * The text the value arrived as: a string as it was written, a number in plain decimal form, and + * a boolean as {@code true} or {@code false}. It can differ from the parsed value, as {@code -0} + * differs from zero. + */ + @JsonProperty("source") + public String source() { + return source; + } + + @Override + public boolean equals(final Object other) { + return other instanceof TypedValue value + && type == value.type + && parsed.equals(value.parsed) + && source.equals(value.source); + } + + @Override + public int hashCode() { + return Objects.hash(type, parsed, source); + } + + /** Names the type only, so a log line never shows a filter value. */ + @Override + public String toString() { + return "TypedValue[" + type + "]"; + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java new file mode 100644 index 000000000000..f2216c08d0e7 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/ontology/sql/TypedValues.java @@ -0,0 +1,395 @@ +/* + * 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.ontology.sql; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.time.DateTimeException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.time.format.ResolverStyle; +import java.time.temporal.ChronoField; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import java.util.stream.IntStream; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.service.exception.BadRequestException; + +/** + * Parses every value that generated SQL compares a column with. A value parses as the data type of + * its column or is refused with a 400 that names the column, the type and what the type expects. + * Nothing else makes a {@link TypedValue} + * (ADR:2026-11-22-generated-sql-keeps-typed-values-apart-from-its-text). + */ +public final class TypedValues { + public static final int MAX_TEXT_LENGTH = 1024; + public static final int MAX_LIST_VALUES = 100; + public static final int MAX_SEARCH_TEXT_LENGTH = 256; + + static final DateTimeFormatter DATE = + DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ROOT) + .withResolverStyle(ResolverStyle.STRICT); + static final DateTimeFormatter TIME = + new DateTimeFormatterBuilder() + .appendPattern("HH:mm:ss") + .appendFraction(ChronoField.NANO_OF_SECOND, 0, 6, true) + .toFormatter(Locale.ROOT) + .withResolverStyle(ResolverStyle.STRICT); + + private static final Pattern WHOLE_FORM = Pattern.compile("-?(0|[1-9][0-9]*)"); + private static final Pattern DECIMAL_FORM = Pattern.compile("-?(0|[1-9][0-9]*)(\\.[0-9]+)?"); + private static final Pattern DATE_FORM = Pattern.compile("(?!0000)[0-9]{4}-[0-9]{2}-[0-9]{2}"); + private static final Pattern TIME_FORM = + Pattern.compile("[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{1,6})?"); + private static final Pattern TIMESTAMP_FORM = + Pattern.compile(DATE_FORM.pattern() + "[T ]" + TIME_FORM.pattern()); + private static final Pattern UUID_FORM = + Pattern.compile("[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"); + private static final int DATE_LENGTH = 10; + + private static final String WHOLE_EXPECTED = + "a whole number is written in ASCII digits, with a leading minus sign when negative and no" + + " leading zeros"; + private static final String DECIMAL_EXPECTED = + "a decimal number is written in ASCII digits with at most one decimal point, a leading" + + " minus sign when negative, and no exponent or leading zeros"; + private static final String TEXT_EXPECTED = "a string or a number is expected"; + private static final String BOOLEAN_EXPECTED = "a boolean is the JSON value true or false"; + private static final String DATE_EXPECTED = + "a date is written YYYY-MM-DD and names a real calendar day"; + private static final String TIME_EXPECTED = + "a time is written hh:mm:ss with at most six fraction digits"; + private static final String TIMESTAMP_EXPECTED = + "a timestamp is written YYYY-MM-DD hh:mm:ss with at most six fraction digits and no offset"; + private static final String UUID_EXPECTED = + "a UUID is written as 32 hexadecimal digits in groups of 8, 4, 4, 4 and 12"; + + /** How the values of a data type are written. A data type with no kind takes no value. */ + public enum Kind { + WHOLE, + DECIMAL, + TEXT, + BOOL, + DATE, + TIME, + TIMESTAMP, + UUID + } + + private record Range(BigInteger min, BigInteger max) { + static Range of(final long min, final long max) { + return new Range(BigInteger.valueOf(min), BigInteger.valueOf(max)); + } + + boolean holds(final BigInteger value) { + return value.compareTo(min) >= 0 && value.compareTo(max) <= 0; + } + } + + /** + * The values each whole-number type holds. TINYINT is signed on some engines and unsigned on + * others, so it takes both ranges. + */ + private static final Map WHOLE_RANGES = + Map.of( + ColumnDataType.TINYINT, + Range.of(Byte.MIN_VALUE, 255), + ColumnDataType.BYTEINT, + Range.of(Byte.MIN_VALUE, Byte.MAX_VALUE), + ColumnDataType.SMALLINT, + Range.of(Short.MIN_VALUE, Short.MAX_VALUE), + ColumnDataType.INT, + Range.of(Integer.MIN_VALUE, Integer.MAX_VALUE), + ColumnDataType.BIGINT, + Range.of(Long.MIN_VALUE, Long.MAX_VALUE), + ColumnDataType.LARGEINT, + new Range( + BigInteger.TWO.pow(127).negate(), BigInteger.TWO.pow(127).subtract(BigInteger.ONE))); + + private TypedValues() {} + + /** One value for one column, such as a part of a record key or the operand of a comparison. */ + public static TypedValue value(final Column column, final Object raw) { + final Kind kind = kindOf(column); + if (raw == null) { + throw new BadRequestException( + String.format("The value for column %s is null", column.getName())); + } + final String text = textOf(column, raw); + final ParsedValue parsed = parse(kind, column, raw, text); + // Only a boolean parses without a text form. + return new TypedValue(column.getDataType(), parsed, text == null ? raw.toString() : text); + } + + /** A record key: one value for each key column, in the order of the key. */ + public static List key(final List columns, final List values) { + return key(columns, values, "key"); + } + + /** A key that the request calls {@code name}, such as the key of the record to start after. */ + public static List key( + final List columns, final List values, final String name) { + if (columns.size() != values.size()) { + throw new BadRequestException( + String.format( + "The %s has %s but the request gives %s", + name, counted(columns.size(), "column"), counted(values.size(), "value"))); + } + return IntStream.range(0, columns.size()) + .mapToObj(index -> value(columns.get(index), values.get(index))) + .toList(); + } + + /** Text to search a character column for. {@link TypedStatement.Builder#contains} takes it. */ + public static TypedValue searchText(final Column column, final String text) { + if (kindOf(column) != Kind.TEXT) { + throw new BadRequestException( + String.format( + "A search reads character data, and column %s has data type %s", + column.getName(), column.getDataType().value())); + } + if (text == null) { + throw new BadRequestException("Search text is null"); + } + if (text.length() > MAX_SEARCH_TEXT_LENGTH) { + throw new BadRequestException( + String.format("Search text must have at most %d characters", MAX_SEARCH_TEXT_LENGTH)); + } + if (holdsControlCharacter(text)) { + throw new BadRequestException("Search text must not hold a control character"); + } + return new TypedValue(column.getDataType(), new ParsedValue.Text(text), text); + } + + /** + * A row filter with each value parsed as the type of {@code column}, the column its path names. + * A null test takes no value, so it applies to a column of any type. + */ + public static TypedRowFilter rowFilter(final Column column, final OntologyRowFilter filter) { + final List values = + switch (filter.getOperator()) { + case IS_NULL, IS_NOT_NULL -> List.of(); + case IN -> members(column, filter.getValue()); + case EQUALS, + NOT_EQUALS, + LESS_THAN, + LESS_THAN_OR_EQUALS, + GREATER_THAN, + GREATER_THAN_OR_EQUALS -> List.of(value(column, filter.getValue())); + }; + return new TypedRowFilter(filter.getColumn(), filter.getOperator(), values); + } + + /** The search text of {@code searched} as the pattern a driver binds, its wildcards escaped. */ + static TypedValue pattern(final TypedValue searched, final String escaped) { + return new TypedValue(searched.type(), new ParsedValue.Text(escaped), searched.source()); + } + + static boolean holdsControlCharacter(final String text) { + return text.codePoints().anyMatch(Character::isISOControl); + } + + private static List members(final Column column, final Object raw) { + if (!(raw instanceof List list) || list.isEmpty() || list.size() > MAX_LIST_VALUES) { + throw new BadRequestException( + String.format( + "A row filter on column %s with `in` takes a list of 1 to %d values", + column.getName(), MAX_LIST_VALUES)); + } + return list.stream().map(member -> value(column, member)).toList(); + } + + /** + * Whether every column of {@code columns} has a data type whose values the generator writes. + * {@link #value} refuses a column for which this is false, so a statement can ask it before it + * orders by a key whose values it could never write. + */ + public static boolean takeValues(final List columns) { + return columns.stream().allMatch(column -> kind(column).isPresent()); + } + + /** How the values of the column's data type are written, or empty when it takes no value. */ + public static Optional kind(final Column column) { + return Optional.ofNullable( + switch (column.getDataType()) { + case TINYINT, BYTEINT, SMALLINT, INT, BIGINT, LARGEINT -> Kind.WHOLE; + case DECIMAL, NUMERIC, NUMBER, FLOAT, DOUBLE -> Kind.DECIMAL; + case VARCHAR, CHAR, STRING, TEXT, MEDIUMTEXT, ENUM -> Kind.TEXT; + case BOOLEAN, BIT -> Kind.BOOL; + case DATE -> Kind.DATE; + case TIME -> Kind.TIME; + case TIMESTAMP, TIMESTAMPZ, DATETIME -> Kind.TIMESTAMP; + case UUID -> Kind.UUID; + default -> null; + }); + } + + private static Kind kindOf(final Column column) { + return kind(column).orElseThrow(() -> unsupported(column)); + } + + /** + * The text a value arrives as: a string as written, a JSON number in plain decimal form, and + * null for anything else. A number takes the length cap of a string. + */ + private static String textOf(final Column column, final Object raw) { + final String text = + switch (raw) { + case String string -> string; + case BigDecimal number -> plain(column, number); + case Double number -> floating(column, number, number.toString()); + case Float number -> floating(column, number, number.toString()); + case Number number -> number.toString(); + default -> null; + }; + return text == null ? null : bounded(column, text); + } + + private static String floating(final Column column, final double number, final String written) { + return Double.isFinite(number) ? plain(column, new BigDecimal(written)) : written; + } + + /** + * Plain decimal form. An exponent writes one digit for each power of ten, so a number whose + * exponent passes the length cap is refused before its digits are written out. + */ + private static String plain(final Column column, final BigDecimal number) { + if (Math.abs((long) number.scale()) > MAX_TEXT_LENGTH) { + throw tooLong(column); + } + return number.toPlainString(); + } + + private static String bounded(final Column column, final String text) { + if (text.length() > MAX_TEXT_LENGTH) { + throw tooLong(column); + } + if (holdsControlCharacter(text)) { + throw new BadRequestException( + String.format( + "The value for column %s must not hold a control character", column.getName())); + } + return text; + } + + /** + * @param text the value as text, or null when it arrived as neither a string nor a number + */ + private static ParsedValue parse( + final Kind kind, final Column column, final Object raw, final String text) { + final String written = raw instanceof String ? text : null; + return switch (kind) { + case WHOLE -> new ParsedValue.WholeNumber(whole(column, text)); + case DECIMAL -> new ParsedValue.DecimalNumber( + new BigDecimal(matching(column, text, DECIMAL_FORM, DECIMAL_EXPECTED))); + case TEXT -> new ParsedValue.Text(present(column, text, TEXT_EXPECTED)); + case BOOL -> new ParsedValue.Bool(bool(column, raw)); + case DATE -> new ParsedValue.CalendarDate(date(column, written, DATE_EXPECTED)); + case TIME -> new ParsedValue.TimeOfDay(time(column, written, TIME_EXPECTED)); + case TIMESTAMP -> new ParsedValue.Timestamp(timestamp(column, written)); + case UUID -> new ParsedValue.Uuid( + UUID.fromString(matching(column, written, UUID_FORM, UUID_EXPECTED))); + }; + } + + private static String present(final Column column, final String text, final String expected) { + if (text == null) { + throw unparsed(column, expected); + } + return text; + } + + private static String matching( + final Column column, final String text, final Pattern form, final String expected) { + if (!form.matcher(present(column, text, expected)).matches()) { + throw unparsed(column, expected); + } + return text; + } + + private static BigInteger whole(final Column column, final String text) { + final BigInteger value = new BigInteger(matching(column, text, WHOLE_FORM, WHOLE_EXPECTED)); + final Range range = WHOLE_RANGES.get(column.getDataType()); + if (!range.holds(value)) { + throw unparsed( + column, + String.format("the type holds whole numbers from %s to %s", range.min(), range.max())); + } + return value; + } + + private static boolean bool(final Column column, final Object raw) { + if (!(raw instanceof Boolean value)) { + throw unparsed(column, BOOLEAN_EXPECTED); + } + return value; + } + + private static LocalDate date(final Column column, final String text, final String expected) { + try { + return LocalDate.parse(matching(column, text, DATE_FORM, expected), DATE); + } catch (final DateTimeException invalid) { + throw unparsed(column, expected); + } + } + + private static LocalTime time(final Column column, final String text, final String expected) { + try { + return LocalTime.parse(matching(column, text, TIME_FORM, expected), TIME); + } catch (final DateTimeException invalid) { + throw unparsed(column, expected); + } + } + + private static LocalDateTime timestamp(final Column column, final String text) { + matching(column, text, TIMESTAMP_FORM, TIMESTAMP_EXPECTED); + return LocalDateTime.of( + date(column, text.substring(0, DATE_LENGTH), TIMESTAMP_EXPECTED), + time(column, text.substring(DATE_LENGTH + 1), TIMESTAMP_EXPECTED)); + } + + private static String counted(final int count, final String noun) { + return count + " " + noun + (count == 1 ? "" : "s"); + } + + private static BadRequestException tooLong(final Column column) { + return new BadRequestException( + String.format( + "The value for column %s must have at most %d characters", + column.getName(), MAX_TEXT_LENGTH)); + } + + private static BadRequestException unparsed(final Column column, final String expected) { + return new BadRequestException( + String.format( + "The value for column %s does not parse as %s: %s", + column.getName(), column.getDataType().value(), expected)); + } + + private static BadRequestException unsupported(final Column column) { + return new BadRequestException( + String.format( + "SQL generation does not support column type %s of column %s", + column.getDataType().value(), column.getName())); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java index c3c590f5c2dd..4ae9b453dacb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfImporter.java @@ -147,7 +147,10 @@ private NativeOntologyImportPreview preview( requireApplicable(source.document(), stored, source.propertyRows()); final RdfSkipLedger dropped = RdfSkipLedger.continuing(source.document().skipped()); final Outcomes outcomes = - reject(classify(source.document(), stored, maxChanged), stored, dropped); + reject( + classify(source.document(), stored, maxChanged, SourceFamily.of(source.format())), + stored, + dropped); final Plan plan = new Plan(stored, working, SourceFamily.of(source.format())); final CreateOntologyChangeSet changeSet = plan.of(outcomes); return new NativeOntologyImportPreview() @@ -172,7 +175,10 @@ NativeOntologyImportSummary summarize(final Source source, final int maxChanged) requireApplicable(source.document(), Stored.EMPTY, source.propertyRows()); final RdfSkipLedger dropped = RdfSkipLedger.continuing(source.document().skipped()); final Outcomes outcomes = - reject(classify(source.document(), Stored.EMPTY, maxChanged), Stored.EMPTY, dropped); + reject( + classify(source.document(), Stored.EMPTY, maxChanged, SourceFamily.of(source.format())), + Stored.EMPTY, + dropped); final Plan plan = new Plan(Stored.EMPTY, PREVIEW_TARGET, SourceFamily.of(source.format())); plan.of(outcomes); final List items = plan.itemsWithClashes(); @@ -239,7 +245,10 @@ public CreateOntologyChangeSet reconcileUnbounded( final Stored stored = Stored.index(working); requireApplicable(document, stored, Map.of()); return plan( - reject(classify(document, stored, Integer.MAX_VALUE), stored, new RdfSkipLedger()), + reject( + classify(document, stored, Integer.MAX_VALUE, SourceFamily.RDF), + stored, + new RdfSkipLedger()), stored, working, SourceFamily.RDF); @@ -381,11 +390,14 @@ static SourceFamily of(final NativeOntologyImportFormat format) { } private static Outcomes classify(final NativeOntologyDocument document, final Stored stored) { - return classify(document, stored, MAX_CHANGED_DEFINITIONS); + return classify(document, stored, MAX_CHANGED_DEFINITIONS, SourceFamily.RDF); } private static Outcomes classify( - final NativeOntologyDocument document, final Stored stored, final int maxChanged) { + final NativeOntologyDocument document, + final Stored stored, + final int maxChanged, + final SourceFamily family) { final Outcomes outcomes = new Outcomes( firstOccurrences( @@ -398,7 +410,7 @@ private static Outcomes classify( property -> property.getIri().toString(), property -> classifyProperty( - property, stored.properties().get(property.getIri().toString()))), + property, stored.properties().get(property.getIri().toString()), family)), classifyAxioms(document.axioms(), stored.axioms())); if (outcomes.changed() > maxChanged) { throw new BadRequestException("A native import accepts at most 1000 changed definitions"); @@ -437,8 +449,20 @@ private static Outcome classifyConcept( : new Updated<>(current, proposed); } + /** + * A CSV has no column for the flag, so a row keeps the stored one, but only while the row leaves + * the property a data property: no other kind can hold it. + */ + private static Boolean displayNameFlag( + final OntologyProperty parsed, final OntologyProperty current, final SourceFamily family) { + if (family != SourceFamily.CSV) { + return parsed.getIsDisplayName(); + } + return parsed.getKind() == OntologyPropertyKind.DATA ? current.getIsDisplayName() : null; + } + private static Outcome classifyProperty( - final OntologyProperty parsed, final OntologyProperty current) { + final OntologyProperty parsed, final OntologyProperty current, final SourceFamily family) { if (current == null) { return new Added<>(parsed, parsed.getIri().toString()); } @@ -450,6 +474,7 @@ private static Outcome classifyProperty( .withEnumValues(parsed.getEnumValues()) .withUnit(parsed.getUnit()) .withIsIdentifier(parsed.getIsIdentifier()) + .withIsDisplayName(displayNameFlag(parsed, current, family)) .withInverse(parsed.getInverse()) .withCharacteristics(parsed.getCharacteristics()) .withPropertyChain(parsed.getPropertyChain()) @@ -1329,6 +1354,7 @@ && listOrEmpty(a.getEnumValues()).stream() .toList()) && Objects.equals(a.getUnit(), b.getUnit()) && Objects.equals(a.getIsIdentifier(), b.getIsIdentifier()) + && Boolean.TRUE.equals(a.getIsDisplayName()) == Boolean.TRUE.equals(b.getIsDisplayName()) && Objects.equals(iriText(a.getInverse()), iriText(b.getInverse())) && setOrEmpty(a.getCharacteristics()).equals(setOrEmpty(b.getCharacteristics())) && listOrEmpty(a.getPropertyChain()).stream() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfReader.java index 61d5b36bd6a8..d9a0d0924067 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfReader.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/NativeOntologyRdfReader.java @@ -370,7 +370,10 @@ private OntologyProperty property(final Resource subject, final OntologyProperty .withDeprecated(flag(subject, OWL2.deprecated)) .withReplacedBy(annotationIri(subject, DCTerms.isReplacedBy)); final RDFNode identifier = expressions.one(subject, OntologyRdfVocabulary.IDENTIFIER_INTENT); - property.withIsIdentifier(identifier != null && booleanValue(identifier)); + property.withIsIdentifier(identifier != null && booleanValue(identifier, "Identifier intent")); + final RDFNode displayName = expressions.one(subject, OntologyRdfVocabulary.DISPLAY_NAME_INTENT); + property.withIsDisplayName( + displayName != null && booleanValue(displayName, "Display-name intent") ? true : null); property.withCharacteristics(characteristics(subject, kind)); property.withPropertyChain( kind == OntologyPropertyKind.OBJECT ? propertyChain(subject) : List.of()); @@ -957,12 +960,12 @@ private boolean flag(final Resource subject, final Property predicate) { }; } - private static boolean booleanValue(final RDFNode value) { + private static boolean booleanValue(final RDFNode value, final String label) { if (!value.isLiteral() || !value.asLiteral().getLanguage().isEmpty() || !XSD.xboolean.getURI().equals(value.asLiteral().getDatatypeURI()) || !"true".equals(value.asLiteral().getLexicalForm())) { - throw new BadRequestException("Identifier intent must be true"); + throw new BadRequestException(label + " must be true"); } return true; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyExportFormat.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyExportFormat.java index e99be96bebdc..eeb7b9ad962a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyExportFormat.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyExportFormat.java @@ -9,7 +9,8 @@ /** * Every serialization a captured ontology release can be exported as. The RDF graph formats reuse * {@link RdfSerializationFormat}; SKOS and SKOS-XL are concept projections written as Turtle, and - * CSV is the native ontology spreadsheet, which has no RDF serialization. + * CSV is the native ontology spreadsheet, which has no RDF serialization, and SHACL is the + * ontology's shapes written as Turtle. */ public enum OntologyExportFormat { TURTLE(NativeOntologyExportFormat.TURTLE, RdfSerializationFormat.TURTLE), @@ -18,7 +19,8 @@ public enum OntologyExportFormat { JSON_LD(NativeOntologyExportFormat.JSONLD, RdfSerializationFormat.JSON_LD), SKOS(NativeOntologyExportFormat.SKOS, RdfSerializationFormat.TURTLE), SKOS_XL(NativeOntologyExportFormat.SKOS_XL, RdfSerializationFormat.TURTLE), - CSV(NativeOntologyExportFormat.CSV, null); + CSV(NativeOntologyExportFormat.CSV, null), + SHACL(NativeOntologyExportFormat.SHACL, RdfSerializationFormat.TURTLE); private final NativeOntologyExportFormat wire; private final RdfSerializationFormat serialization; @@ -66,6 +68,11 @@ public boolean isGraph() { return serialization != null; } + /** Whether the export is the ontology's concepts, properties and axioms as one RDF graph. */ + public boolean isOntologyGraph() { + return isGraph() && this != SHACL; + } + /** The RDF serialization of a graph format; a CSV export has none. */ public RdfSerializationFormat serialization() { if (serialization == null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyPropertyRdfWriter.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyPropertyRdfWriter.java index 51e9a86151e5..b9d2e2b3eadd 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyPropertyRdfWriter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyPropertyRdfWriter.java @@ -122,6 +122,11 @@ private static void writeDataMetadata( model, OntologyRdfVocabulary.IDENTIFIER_INTENT, EntityKind.ANNOTATION_PROPERTY); property.addLiteral(OntologyRdfVocabulary.IDENTIFIER_INTENT, true); } + if (Boolean.TRUE.equals(definition.getIsDisplayName())) { + OwlEntityDeclarations.declare( + model, OntologyRdfVocabulary.DISPLAY_NAME_INTENT, EntityKind.ANNOTATION_PROPERTY); + property.addLiteral(OntologyRdfVocabulary.DISPLAY_NAME_INTENT, true); + } } private static RDFNode enumLiteral(final Model model, final OntologyLiteral value) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyRdfVocabulary.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyRdfVocabulary.java index e9e53a9cdd0b..3dd88ad0784c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyRdfVocabulary.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyRdfVocabulary.java @@ -16,10 +16,19 @@ final class OntologyRdfVocabulary { ResourceFactory.createProperty("https://open-metadata.org/ontology/unitAnnotation"); static final Property IDENTIFIER_INTENT = ResourceFactory.createProperty("https://open-metadata.org/ontology/identifierIntent"); + static final Property DISPLAY_NAME_INTENT = + ResourceFactory.createProperty(NAMESPACE + "displayNameIntent"); static final Property ABSTRACT = ResourceFactory.createProperty(NAMESPACE + "abstract"); static final Property BOUND_ASSET = ResourceFactory.createProperty(NAMESPACE + "boundAsset"); static final Set ANNOTATIONS = - Set.of(DCTerms.source, DCTerms.isReplacedBy, UNIT, IDENTIFIER_INTENT, ABSTRACT, BOUND_ASSET); + Set.of( + DCTerms.source, + DCTerms.isReplacedBy, + UNIT, + IDENTIFIER_INTENT, + DISPLAY_NAME_INTENT, + ABSTRACT, + BOUND_ASSET); private OntologyRdfVocabulary() {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseExporter.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseExporter.java index 11607f8408e3..bb4dbd008ff1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseExporter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseExporter.java @@ -11,6 +11,7 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; import org.openmetadata.service.exception.BadRequestException; @@ -57,6 +58,9 @@ static String render( final OntologyReleaseExportOptions options, final BoundAssetLinks assetLinks) { requireSupported(format, options); + if (format == OntologyExportFormat.SHACL) { + return shacl(release, members); + } return format.isGraph() ? graph(release, members, format, options, assetLinks) : csv(release, members, options); @@ -64,7 +68,7 @@ static String render( private static void requireSupported( final OntologyExportFormat format, final OntologyReleaseExportOptions options) { - if (!format.isGraph() && options.getIncludeBoundAssets()) { + if (!format.isOntologyGraph() && options.getIncludeBoundAssets()) { throw new BadRequestException( "Bound asset links cannot be written to " + format.wire().value()); } @@ -124,6 +128,22 @@ private static void linkAssets( OntologyRdfVocabulary.BOUND_ASSET, model.createResource(asset.toString()))); } + private static String shacl( + final OntologyRelease release, final List members) { + final List shapes = + members.stream() + .filter(member -> member.getMemberKind() == MemberKind.SHAPE) + .map(member -> (OntologyShape) OntologyReleaseReader.definition(release, member)) + .toList(); + final Model model = + OntologyShaclWriter.write(OntologyReleaseReader.root(release, members), shapes); + try { + return RdfGraphSerializer.asString(model, RdfSerializationFormat.TURTLE); + } finally { + model.close(); + } + } + private static String csv( final OntologyRelease release, final List members, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseProjection.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseProjection.java index 38d8767aa6b8..6db2a8b186ee 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseProjection.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyReleaseProjection.java @@ -25,6 +25,7 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyConceptType; import org.openmetadata.schema.type.OntologyPropertyKind; import org.openmetadata.schema.type.OntologyReleaseMember; @@ -69,6 +70,7 @@ public Model build( members.stream() .map( member -> new Definition(member, OntologyReleaseReader.definition(release, member))) + .filter(definition -> !(definition.value() instanceof OntologyShape)) .toList(); if (!includeInverses) { withoutInverses(definitions); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclReader.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclReader.java new file mode 100644 index 000000000000..540b891e2dcb --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclReader.java @@ -0,0 +1,620 @@ +/* + * 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.rdf; + +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import org.apache.jena.rdf.model.Literal; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.rdf.model.Property; +import org.apache.jena.rdf.model.RDFNode; +import org.apache.jena.rdf.model.Resource; +import org.apache.jena.rdf.model.Statement; +import org.apache.jena.vocabulary.RDF; +import org.apache.jena.vocabulary.RDFS; +import org.apache.jena.vocabulary.XSD; +import org.openmetadata.schema.api.data.OntologyShapeUnsupportedConstruct; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.exception.BadRequestException; + +/** + * Reads the SHACL node shapes of a Turtle document. A shape is an {@code sh:NodeShape} with one + * {@code sh:targetClass} and {@code sh:property} nodes whose {@code sh:path} is a single IRI. A + * property node holds the constraints the shape model has: {@code sh:minCount}, {@code + * sh:maxCount}, {@code sh:class}, {@code sh:datatype}, {@code sh:minInclusive}, {@code + * sh:maxInclusive}, {@code sh:in} and {@code sh:pattern}. Every other SHACL construct is + * reported by name and left out; the rest of the file is still read. + */ +public final class OntologyShaclReader { + /** Shapes one file may hold, as many as the native import allows changed definitions. */ + public static final int MAX_SHAPES = 1_000; + + /** Cells of one {@code sh:in} list that are read before the list counts as malformed. */ + static final int MAX_LIST_CELLS = 1_000; + + private static final int MAX_NAME_LENGTH = 256; + private static final Pattern CONSTRAINT_ID = Pattern.compile("^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$"); + private static final Set NODE_CONSUMED = + Set.of( + OntologyShaclVocabulary.NAME, + OntologyShaclVocabulary.TARGET_CLASS, + OntologyShaclVocabulary.SEVERITY, + OntologyShaclVocabulary.PROPERTY); + private static final Set PROPERTY_CONSUMED = + Set.of( + OntologyShaclVocabulary.PATH, + OntologyShaclVocabulary.ORDER, + OntologyShaclVocabulary.MIN_COUNT, + OntologyShaclVocabulary.MAX_COUNT, + OntologyShaclVocabulary.CLASS, + OntologyShaclVocabulary.DATATYPE, + OntologyShaclVocabulary.MIN_INCLUSIVE, + OntologyShaclVocabulary.MAX_INCLUSIVE, + OntologyShaclVocabulary.IN, + OntologyShaclVocabulary.PATTERN); + + /** A node shape as the file states it; the caller turns it into a stored shape. */ + public record ParsedShape( + String name, + String displayName, + String description, + URI targetConcept, + OntologyShapeSeverity severity, + List constraints) {} + + public record Parsed( + List shapes, List unsupported) {} + + private final List unsupported = new ArrayList<>(); + + private OntologyShaclReader() {} + + /** + * Parses with the bounds of the native import: at most 10 MiB, 100,000 statements and 30 seconds, + * and no relative identifiers or named graphs. + */ + public static Parsed read(final String turtle) { + final Model model = new SafeRdfModelParser().parse(turtle, RdfSerializationFormat.TURTLE); + try { + return new OntologyShaclReader().parse(model); + } finally { + model.close(); + } + } + + private Parsed parse(final Model model) { + final Set attached = + new HashSet<>( + model + .listObjectsOfProperty(OntologyShaclVocabulary.PROPERTY) + .filterKeep(RDFNode::isResource) + .mapWith(RDFNode::asResource) + .toList()); + final List nodes = nodeShapes(model, attached); + if (nodes.size() > MAX_SHAPES) { + throw new BadRequestException("A file holds at most " + MAX_SHAPES + " shapes"); + } + reportDetachedPropertyShapes(model, attached, nodes); + final Set taken = new HashSet<>(); + final List shapes = new ArrayList<>(); + for (final Resource node : nodes) { + final ParsedShape shape = shape(node, taken); + if (shape != null) { + shapes.add(shape); + } + } + shapes.sort(Comparator.comparing(ParsedShape::name)); + return new Parsed(List.copyOf(shapes), List.copyOf(unsupported)); + } + + private static List nodeShapes(final Model model, final Set attached) { + final Map nodes = new LinkedHashMap<>(); + final List candidates = new ArrayList<>(); + candidates.addAll( + model.listSubjectsWithProperty(RDF.type, OntologyShaclVocabulary.NODE_SHAPE).toList()); + candidates.addAll( + model.listSubjectsWithProperty(OntologyShaclVocabulary.TARGET_CLASS).toList()); + for (final Resource candidate : candidates) { + final boolean typed = candidate.hasProperty(RDF.type, OntologyShaclVocabulary.NODE_SHAPE); + if (typed || !attached.contains(candidate)) { + nodes.putIfAbsent(key(candidate), candidate); + } + } + return nodes.values().stream().sorted(Comparator.comparing(OntologyShaclReader::key)).toList(); + } + + private static String key(final RDFNode node) { + return node.isURIResource() ? node.asResource().getURI() : "_:" + node.asResource().getId(); + } + + private void reportDetachedPropertyShapes( + final Model model, final Set attached, final List nodes) { + model + .listSubjectsWithProperty(OntologyShaclVocabulary.PATH) + .filterDrop(attached::contains) + .filterDrop(nodes::contains) + .toList() + .stream() + .sorted(Comparator.comparing(OntologyShaclReader::key)) + .forEach( + node -> + report( + "sh:PropertyShape", + null, + pathOf(node), + "A property shape that no node shape holds through sh:property was left out")); + } + + private ParsedShape shape(final Resource node, final Set taken) { + final List targets = + node.listProperties(OntologyShaclVocabulary.TARGET_CLASS) + .mapWith(Statement::getObject) + .toList(); + final String label = label(node); + final List classes = targets.stream().filter(RDFNode::isURIResource).toList(); + if (classes.size() != 1 || classes.size() != targets.size()) { + report( + "sh:targetClass", + label, + null, + "A node shape needs exactly one sh:targetClass that is an IRI; the shape was left out"); + reportUnconsumed(node, NODE_CONSUMED, label, null); + return null; + } + final String name = uniqueName(node, classes.getFirst().asResource(), taken); + reportUnconsumed(node, NODE_CONSUMED, name, null); + final List constraints = constraints(node, name); + return new ParsedShape( + name, + text(node, RDFS.label, name), + text(node, RDFS.comment, ""), + URI.create(classes.getFirst().asResource().getURI()), + severity(node, name), + constraints); + } + + private static String label(final Resource node) { + return node.isURIResource() ? node.getURI() : "_:" + node.getId(); + } + + /** + * A name is kept as the file states it, so the caller can refuse one the name rules do not allow. + * Only the suffix that tells two equal names apart is fitted to the length limit. + */ + private String uniqueName(final Resource node, final Resource target, final Set taken) { + final RDFNode named = single(node, OntologyShaclVocabulary.NAME, label(node), null); + final String base = + named != null && named.isLiteral() + ? named.asLiteral().getString() + : node.isURIResource() + ? localName(node.getURI()) + : localName(target.getURI()) + "Shape"; + final String clean = base.isBlank() ? "Shape" : base.strip().replace("::", ":_"); + String candidate = clean; + for (int suffix = 2; !taken.add(candidate); suffix++) { + final String tail = Integer.toString(suffix); + candidate = truncate(clean, MAX_NAME_LENGTH - tail.length()) + tail; + } + return candidate; + } + + private static String truncate(final String value, final int length) { + return value.length() > length ? value.substring(0, length) : value; + } + + private static String localName(final String iri) { + final int cut = + Math.max(Math.max(iri.lastIndexOf('#'), iri.lastIndexOf('/')), iri.lastIndexOf(':')); + final String local = cut < 0 ? iri : iri.substring(cut + 1); + try { + return URLDecoder.decode(local.replace("+", "%2B"), StandardCharsets.UTF_8); + } catch (IllegalArgumentException undecodable) { + return local; + } + } + + private static String text(final Resource node, final Property property, final String fallback) { + final Statement statement = node.getProperty(property); + return statement != null && statement.getObject().isLiteral() + ? statement.getString() + : fallback; + } + + private OntologyShapeSeverity severity(final Resource node, final String name) { + final RDFNode value = single(node, OntologyShaclVocabulary.SEVERITY, name, null); + if (value == null) { + return OntologyShapeSeverity.VIOLATION; + } + if (OntologyShaclVocabulary.VIOLATION.equals(value)) { + return OntologyShapeSeverity.VIOLATION; + } + if (OntologyShaclVocabulary.WARNING.equals(value)) { + return OntologyShapeSeverity.WARNING; + } + if (OntologyShaclVocabulary.INFO.equals(value)) { + return OntologyShapeSeverity.INFO; + } + report( + "sh:severity", + name, + null, + "Only sh:Violation, sh:Warning and sh:Info are held; Violation was used"); + return OntologyShapeSeverity.VIOLATION; + } + + private List constraints(final Resource node, final String shapeName) { + final List properties = new ArrayList<>(); + for (final Statement statement : + node.listProperties(OntologyShaclVocabulary.PROPERTY).toList()) { + final RDFNode object = statement.getObject(); + if (!object.isResource()) { + report( + "sh:property", shapeName, null, "A sh:property value that is not a node was left out"); + continue; + } + final PropertyNode property = propertyNode(object.asResource(), shapeName); + if (property != null) { + properties.add(property); + } + } + properties.sort( + Comparator.comparingLong(PropertyNode::order) + .thenComparing(property -> property.constraint().getPath().toString()) + .thenComparing(property -> JsonUtils.pojoToJson(property.constraint()))); + return assignIds(node, properties); + } + + private PropertyNode propertyNode(final Resource node, final String shapeName) { + final List paths = + node.listProperties(OntologyShaclVocabulary.PATH).mapWith(Statement::getObject).toList(); + if (paths.size() != 1 || !paths.getFirst().isURIResource()) { + report( + "sh:path", + shapeName, + null, + "A property path that is not a single IRI is not held; the property shape was left out"); + return null; + } + final URI path = URI.create(paths.getFirst().asResource().getURI()); + reportUnconsumed(node, PROPERTY_CONSUMED, shapeName, path); + final OntologyShapeConstraint constraint = new OntologyShapeConstraint().withPath(path); + final boolean any = + count(node, OntologyShaclVocabulary.MIN_COUNT, shapeName, path, constraint::setMinCount) + | count( + node, OntologyShaclVocabulary.MAX_COUNT, shapeName, path, constraint::setMaxCount) + | iri(node, OntologyShaclVocabulary.CLASS, shapeName, path, constraint::setClassIri) + | iri( + node, OntologyShaclVocabulary.DATATYPE, shapeName, path, constraint::setDatatypeIri) + | bound( + node, + OntologyShaclVocabulary.MIN_INCLUSIVE, + shapeName, + path, + constraint::setMinInclusive) + | bound( + node, + OntologyShaclVocabulary.MAX_INCLUSIVE, + shapeName, + path, + constraint::setMaxInclusive) + | values(node, shapeName, path, constraint) + | pattern(node, shapeName, path, constraint); + if (!any) { + report( + "sh:property", + shapeName, + path, + "A property shape with no supported constraint was left out"); + return null; + } + return new PropertyNode(node, order(node), constraint); + } + + private static long order(final Resource node) { + final Statement statement = node.getProperty(OntologyShaclVocabulary.ORDER); + if (statement != null && statement.getObject().isLiteral()) { + try { + return Long.parseLong(statement.getLiteral().getLexicalForm().strip()); + } catch (NumberFormatException ignored) { + return Long.MAX_VALUE; + } + } + return Long.MAX_VALUE; + } + + private boolean count( + final Resource node, + final Property predicate, + final String shapeName, + final URI path, + final java.util.function.Consumer setter) { + final RDFNode object = single(node, predicate, shapeName, path); + if (object == null) { + return false; + } + final Integer value = nonNegative(object); + if (value == null) { + report( + "sh:" + predicate.getLocalName(), + shapeName, + path, + "The value is not a non-negative integer; the constraint was left out"); + return false; + } + setter.accept(value); + return true; + } + + private static Integer nonNegative(final RDFNode object) { + if (!object.isLiteral()) { + return null; + } + try { + final int value = Integer.parseInt(object.asLiteral().getLexicalForm().strip()); + return value < 0 ? null : value; + } catch (NumberFormatException invalid) { + return null; + } + } + + private boolean iri( + final Resource node, + final Property predicate, + final String shapeName, + final URI path, + final java.util.function.Consumer setter) { + final RDFNode object = single(node, predicate, shapeName, path); + if (object == null) { + return false; + } + if (!object.isURIResource()) { + report( + "sh:" + predicate.getLocalName(), + shapeName, + path, + "The value is not an IRI; the constraint was left out"); + return false; + } + setter.accept(URI.create(object.asResource().getURI())); + return true; + } + + private boolean bound( + final Resource node, + final Property predicate, + final String shapeName, + final URI path, + final java.util.function.Consumer setter) { + final RDFNode object = single(node, predicate, shapeName, path); + if (object == null) { + return false; + } + if (!object.isLiteral() || !object.asLiteral().getLanguage().isEmpty()) { + report( + "sh:" + predicate.getLocalName(), + shapeName, + path, + object.isLiteral() + ? "A language-tagged literal is not held; the constraint was left out" + : "The value is not a literal; the constraint was left out"); + return false; + } + setter.accept(literal(object.asLiteral())); + return true; + } + + private boolean values( + final Resource node, + final String shapeName, + final URI path, + final OntologyShapeConstraint constraint) { + final RDFNode head = single(node, OntologyShaclVocabulary.IN, shapeName, path); + if (head == null) { + return false; + } + final List elements = items(head); + final List values = elements == null ? null : values(elements); + if (values == null) { + report( + "sh:in", + shapeName, + path, + elements == null + ? "The value is not a well-formed list of at most " + + MAX_LIST_CELLS + + " IRIs and literals; the constraint was left out" + : "A list value that is not an IRI or a plain or typed literal is not held; " + + "the constraint was left out"); + return false; + } + constraint.setIn(values); + return true; + } + + /** Null when a value is a blank node or a language-tagged literal. */ + private static List values(final List elements) { + final List values = new ArrayList<>(); + for (final RDFNode element : elements) { + if (element.isURIResource()) { + values.add(new OntologyShapeValue().withIri(URI.create(element.asResource().getURI()))); + } else if (element.isLiteral() && element.asLiteral().getLanguage().isEmpty()) { + values.add(new OntologyShapeValue().withLiteral(literal(element.asLiteral()))); + } else { + return null; + } + } + return values; + } + + /** + * Walks {@code rdf:first} and {@code rdf:rest} itself, because a list that loops back on itself + * never ends. Null when the list repeats a cell, lacks or doubles a link, ends in anything but + * {@code rdf:nil}, or has more than {@link #MAX_LIST_CELLS} cells. + */ + private static List items(final RDFNode head) { + final List items = new ArrayList<>(); + final Set visited = new HashSet<>(); + RDFNode cell = head; + while (!RDF.nil.equals(cell)) { + if (!cell.isResource() || !visited.add(cell.asResource()) || items.size() >= MAX_LIST_CELLS) { + return null; + } + final List first = objects(cell.asResource(), RDF.first); + final List rest = objects(cell.asResource(), RDF.rest); + if (first.size() != 1 || rest.size() != 1) { + return null; + } + items.add(first.getFirst()); + cell = rest.getFirst(); + } + return items; + } + + private static List objects(final Resource node, final Property predicate) { + return node.listProperties(predicate).mapWith(Statement::getObject).toList(); + } + + /** + * The value of a predicate. A second value is reported and the first in lexical order is kept, so + * the same file always reads the same. + */ + private RDFNode single( + final Resource node, final Property predicate, final String shapeName, final URI path) { + final List values = new ArrayList<>(objects(node, predicate)); + if (values.isEmpty()) { + return null; + } + if (values.size() > 1) { + values.sort(Comparator.comparing(RDFNode::toString)); + report( + "sh:" + predicate.getLocalName(), + shapeName, + path, + "Only one value is held; the first in lexical order was used"); + } + return values.getFirst(); + } + + private boolean pattern( + final Resource node, + final String shapeName, + final URI path, + final OntologyShapeConstraint constraint) { + final RDFNode value = single(node, OntologyShaclVocabulary.PATTERN, shapeName, path); + if (value == null) { + return false; + } + if (!value.isLiteral()) { + report( + "sh:pattern", shapeName, path, "The value is not a string; the constraint was left out"); + return false; + } + constraint.setPattern(value.asLiteral().getString()); + return true; + } + + private static OntologyLiteral literal(final Literal literal) { + final String datatype = literal.getDatatypeURI(); + final boolean plain = datatype == null || XSD.xstring.getURI().equals(datatype); + return new OntologyLiteral() + .withValue(literal.getLexicalForm()) + .withDatatypeIri(plain ? null : URI.create(datatype)); + } + + /** + * A property node written by {@link OntologyShaclWriter} carries its id after the {@code #} of + * its IRI, under its shape's own IRI. Any other node, such as a blank node, gets {@code c1}, + * {@code c2}, in the order the constraints are held. + */ + private static List assignIds( + final Resource shape, final List properties) { + final Set used = new HashSet<>(); + final Map explicit = new LinkedHashMap<>(); + for (final PropertyNode property : properties) { + final String id = explicitId(shape, property.node()); + if (id != null && used.add(id)) { + explicit.put(property, id); + } + } + final List constraints = new ArrayList<>(); + int serial = 0; + for (final PropertyNode property : properties) { + String id = explicit.get(property); + while (id == null) { + final String candidate = "c" + ++serial; + id = used.add(candidate) ? candidate : null; + } + constraints.add(property.constraint().withId(id)); + } + return constraints; + } + + private static String explicitId(final Resource shape, final Resource property) { + if (!shape.isURIResource() || !property.isURIResource()) { + return null; + } + final String prefix = shape.getURI() + "#"; + final String uri = property.getURI(); + if (!uri.startsWith(prefix)) { + return null; + } + final String id = uri.substring(prefix.length()); + return CONSTRAINT_ID.matcher(id).matches() ? id : null; + } + + private void reportUnconsumed( + final Resource node, final Set consumed, final String shapeName, final URI path) { + final Set reported = new HashSet<>(); + for (final Statement statement : node.listProperties().toList()) { + final Property predicate = statement.getPredicate(); + if (OntologyShaclVocabulary.isShacl(predicate) + && !consumed.contains(predicate) + && reported.add(predicate.getLocalName())) { + report("sh:" + predicate.getLocalName(), shapeName, path, "Not held by the shape model"); + } + } + } + + private static URI pathOf(final Resource node) { + final Statement path = node.getProperty(OntologyShaclVocabulary.PATH); + return path != null && path.getObject().isURIResource() + ? URI.create(path.getResource().getURI()) + : null; + } + + private void report( + final String construct, final String shape, final URI path, final String message) { + unsupported.add( + new OntologyShapeUnsupportedConstruct() + .withConstruct(construct) + .withShape(shape) + .withPath(path) + .withMessage(message)); + } + + private record PropertyNode(Resource node, long order, OntologyShapeConstraint constraint) {} +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclVocabulary.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclVocabulary.java new file mode 100644 index 000000000000..5a6b59c51026 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclVocabulary.java @@ -0,0 +1,85 @@ +/* + * 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.rdf; + +import org.apache.jena.rdf.model.Property; +import org.apache.jena.rdf.model.Resource; +import org.apache.jena.rdf.model.ResourceFactory; +import org.apache.jena.shacl.vocabulary.SHACL; + +/** The SHACL terms a shape is written with and read from, and the IRIs that carry its identity. */ +final class OntologyShaclVocabulary { + static final String SHAPE_IRI_PREFIX = "urn:openmetadata:ontology-shape:"; + static final Resource NODE_SHAPE = resource("NodeShape"); + static final Resource VIOLATION = resource("Violation"); + static final Resource WARNING = resource("Warning"); + static final Resource INFO = resource("Info"); + static final Property NAME = property("name"); + static final Property TARGET_CLASS = property("targetClass"); + static final Property SEVERITY = property("severity"); + static final Property PROPERTY = property("property"); + static final Property PATH = property("path"); + static final Property ORDER = property("order"); + static final Property MIN_COUNT = property("minCount"); + static final Property MAX_COUNT = property("maxCount"); + static final Property CLASS = property("class"); + static final Property DATATYPE = property("datatype"); + static final Property MIN_INCLUSIVE = property("minInclusive"); + static final Property MAX_INCLUSIVE = property("maxInclusive"); + static final Property IN = property("in"); + static final Property PATTERN = property("pattern"); + + private OntologyShaclVocabulary() {} + + static boolean isShacl(final Property predicate) { + return SHACL.NS.equals(predicate.getNameSpace()); + } + + /** The IRI a shape is written under: its name, percent-encoded so distinct names stay distinct. */ + static String shapeIri(final String name) { + final StringBuilder encoded = new StringBuilder(SHAPE_IRI_PREFIX); + for (final byte value : name.getBytes(java.nio.charset.StandardCharsets.UTF_8)) { + final char character = (char) (value & 0xff); + if (isUnreserved(character)) { + encoded.append(character); + } else { + encoded.append('%').append(String.format("%02X", value & 0xff)); + } + } + return encoded.toString(); + } + + /** The IRI a constraint is written under, so the importer can read its id back. */ + static String constraintIri(final String shapeIri, final String constraintId) { + return shapeIri + "#" + constraintId; + } + + private static boolean isUnreserved(final char character) { + return (character >= 'a' && character <= 'z') + || (character >= 'A' && character <= 'Z') + || (character >= '0' && character <= '9') + || character == '-' + || character == '.' + || character == '_' + || character == '~'; + } + + private static Resource resource(final String name) { + return ResourceFactory.createResource(SHACL.NS + name); + } + + private static Property property(final String name) { + return ResourceFactory.createProperty(SHACL.NS + name); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclWriter.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclWriter.java new file mode 100644 index 000000000000..477ba07da5d4 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/OntologyShaclWriter.java @@ -0,0 +1,147 @@ +/* + * 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.rdf; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import java.util.Comparator; +import java.util.List; +import org.apache.jena.rdf.model.Literal; +import org.apache.jena.rdf.model.Model; +import org.apache.jena.rdf.model.ModelFactory; +import org.apache.jena.rdf.model.RDFNode; +import org.apache.jena.rdf.model.Resource; +import org.apache.jena.shacl.vocabulary.SHACL; +import org.apache.jena.vocabulary.RDF; +import org.apache.jena.vocabulary.RDFS; +import org.apache.jena.vocabulary.XSD; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; + +/** + * Writes shapes as SHACL. Each shape is an {@code sh:NodeShape} named by {@code sh:name} and + * written under an IRI made from its name; each constraint is an {@code sh:property} node whose IRI + * is its shape's IRI, {@code #} and its constraint id, and whose {@code sh:order} is its authored + * position. {@link OntologyShaclReader} reads the id and the order back from those. + */ +public final class OntologyShaclWriter { + private OntologyShaclWriter() {} + + public static Model write(final Ontology root, final List shapes) { + final Model model = ModelFactory.createDefaultModel(); + model.setNsPrefix("sh", SHACL.NS); + model.setNsPrefix("rdfs", RDFS.uri); + model.setNsPrefix("xsd", XSD.NS); + listOrEmpty(root.getPrefixes()) + .forEach(prefix -> model.setNsPrefix(prefix.getPrefix(), prefix.getNamespace().toString())); + shapes.stream() + .sorted(Comparator.comparing(OntologyShape::getName)) + .forEach(shape -> write(model, shape)); + return model; + } + + private static void write(final Model model, final OntologyShape shape) { + final String shapeIri = OntologyShaclVocabulary.shapeIri(shape.getName()); + final Resource node = model.createResource(shapeIri); + node.addProperty(RDF.type, OntologyShaclVocabulary.NODE_SHAPE); + node.addProperty(OntologyShaclVocabulary.NAME, shape.getName()); + if (!nullOrEmpty(shape.getDisplayName())) { + node.addProperty(RDFS.label, shape.getDisplayName()); + } + if (!nullOrEmpty(shape.getDescription())) { + node.addProperty(RDFS.comment, shape.getDescription()); + } + node.addProperty( + OntologyShaclVocabulary.TARGET_CLASS, + model.createResource(shape.getTargetConcept().toString())); + node.addProperty(OntologyShaclVocabulary.SEVERITY, severity(shape.getSeverity())); + final List constraints = listOrEmpty(shape.getConstraints()); + for (int index = 0; index < constraints.size(); index++) { + final OntologyShapeConstraint constraint = constraints.get(index); + final Resource property = + model.createResource(OntologyShaclVocabulary.constraintIri(shapeIri, constraint.getId())); + node.addProperty(OntologyShaclVocabulary.PROPERTY, property); + write(model, property, constraint, index); + } + } + + private static Resource severity(final OntologyShapeSeverity severity) { + return switch (severity == null ? OntologyShapeSeverity.VIOLATION : severity) { + case VIOLATION -> OntologyShaclVocabulary.VIOLATION; + case WARNING -> OntologyShaclVocabulary.WARNING; + case INFO -> OntologyShaclVocabulary.INFO; + }; + } + + private static void write( + final Model model, + final Resource property, + final OntologyShapeConstraint constraint, + final int position) { + property.addProperty( + OntologyShaclVocabulary.PATH, model.createResource(constraint.getPath().toString())); + property.addLiteral(OntologyShaclVocabulary.ORDER, model.createTypedLiteral(position)); + if (constraint.getMinCount() != null) { + property.addLiteral( + OntologyShaclVocabulary.MIN_COUNT, model.createTypedLiteral(constraint.getMinCount())); + } + if (constraint.getMaxCount() != null) { + property.addLiteral( + OntologyShaclVocabulary.MAX_COUNT, model.createTypedLiteral(constraint.getMaxCount())); + } + if (constraint.getClassIri() != null) { + property.addProperty( + OntologyShaclVocabulary.CLASS, model.createResource(constraint.getClassIri().toString())); + } + if (constraint.getDatatypeIri() != null) { + property.addProperty( + OntologyShaclVocabulary.DATATYPE, + model.createResource(constraint.getDatatypeIri().toString())); + } + if (constraint.getMinInclusive() != null) { + property.addLiteral( + OntologyShaclVocabulary.MIN_INCLUSIVE, literal(model, constraint.getMinInclusive())); + } + if (constraint.getMaxInclusive() != null) { + property.addLiteral( + OntologyShaclVocabulary.MAX_INCLUSIVE, literal(model, constraint.getMaxInclusive())); + } + if (constraint.getIn() != null) { + property.addProperty( + OntologyShaclVocabulary.IN, + model.createList( + constraint.getIn().stream().map(value -> node(model, value)).iterator())); + } + if (constraint.getPattern() != null) { + property.addProperty(OntologyShaclVocabulary.PATTERN, constraint.getPattern()); + } + } + + private static RDFNode node(final Model model, final OntologyShapeValue value) { + return value.getIri() == null + ? literal(model, value.getLiteral()) + : model.createResource(value.getIri().toString()); + } + + private static Literal literal(final Model model, final OntologyLiteral literal) { + return literal.getDatatypeIri() == null + ? model.createLiteral(literal.getValue()) + : model.createTypedLiteral(literal.getValue(), literal.getDatatypeIri().toString()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfExcludedEntities.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfExcludedEntities.java index 4db99314a110..a3203471f76e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfExcludedEntities.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfExcludedEntities.java @@ -35,7 +35,8 @@ public final class RdfExcludedEntities { private static final String AI_CHART = "aiChart"; private static final String BUSINESS_PROCESS = "businessProcess"; - // Native ontology meaning is published only through the active release's dedicated graph. + // Native ontology meaning is published only through the active release's dedicated graph. A + // change set is a draft: its operations and their evidence are read through the draft read right. public static final Set EXCLUDED_ENTITY_TYPES = Set.of( AI_CHART, @@ -44,7 +45,9 @@ public final class RdfExcludedEntities { Entity.ONTOLOGY_CONCEPT, Entity.ONTOLOGY_PROPERTY, Entity.ONTOLOGY_AXIOM, - Entity.ONTOLOGY_RELEASE); + Entity.ONTOLOGY_SHAPE, + Entity.ONTOLOGY_RELEASE, + Entity.ONTOLOGY_CHANGE_SET); private RdfExcludedEntities() {} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfSourceNormalizer.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfSourceNormalizer.java index 8cd373db96cc..cd06f19fb7ec 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfSourceNormalizer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfSourceNormalizer.java @@ -47,7 +47,8 @@ final class RdfSourceNormalizer { OWL2.versionIRI, OntologyRdfVocabulary.ABSTRACT, OntologyRdfVocabulary.UNIT, - OntologyRdfVocabulary.IDENTIFIER_INTENT); + OntologyRdfVocabulary.IDENTIFIER_INTENT, + OntologyRdfVocabulary.DISPLAY_NAME_INTENT); private static final List DESCRIPTIONS = List.of(SKOS.definition, RDFS.comment); private static final Set MARKUP_DATATYPES = Set.of(RDF.HTML.getURI(), RDF.xmlLiteral.getURI()); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/apps/AppResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/apps/AppResource.java index 64d1fa43abd2..b82e4743aec5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/apps/AppResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/apps/AppResource.java @@ -942,6 +942,7 @@ public Response create( securityContext, getResourceContext(), new OperationContext(APPLICATION, MetadataOperation.CREATE)); + validateConfigurationBeforeSave(app); if (SCHEDULED_TYPES.contains(app.getScheduleType())) { ApplicationHandler.getInstance() .installApplication( @@ -998,6 +999,7 @@ public Response patchApplication( if (reschedules) { authorizeAppOperation(securityContext, id, MetadataOperation.EDIT_ALL); } + validatePatchedConfiguration(app, patch); Response response = patchInternal(uriInfo, securityContext, id, patch); App updatedApp = (App) response.getEntity(); if (reschedules) { @@ -1014,8 +1016,26 @@ public Response patchApplication( return response; } + private static final String APP_CONFIGURATION_FIELD = "appConfiguration"; private static final Set SCHEDULE_OR_CONFIG_FIELDS = - Set.of("appSchedule", "appConfiguration"); + Set.of("appSchedule", APP_CONFIGURATION_FIELD); + + static boolean touchesConfiguration(JsonPatch patch) { + return JsonPatchUtils.replacesWholeDocument(patch) + || JsonUtils.extractPatchedFields(patch).contains(APP_CONFIGURATION_FIELD); + } + + /** Check the configuration a patch would store, before the patch is applied to the stored app. */ + private void validatePatchedConfiguration(App stored, JsonPatch patch) { + if (touchesConfiguration(patch)) { + validateConfigurationBeforeSave(JsonUtils.applyPatch(stored, patch, App.class)); + } + } + + private void validateConfigurationBeforeSave(App app) { + ApplicationHandler.getInstance() + .validateConfigurationForSave(app, Entity.getCollectionDAO(), searchRepository); + } /** * Whether a patch changes the schedule or configuration the app is installed with. A whole-document @@ -1069,6 +1089,7 @@ public Response patchApplication( if (reschedules) { authorizeAppOperation(securityContext, fqn, MetadataOperation.EDIT_ALL); } + validatePatchedConfiguration(app, patch); Response response = patchInternal(uriInfo, securityContext, fqn, patch); App updatedApp = (App) response.getEntity(); if (reschedules) { @@ -1119,6 +1140,7 @@ public Response createOrUpdate( : putResourceContext; authorizer.authorize( securityContext, new OperationContext(entityType, putOperation), authorizedContext); + validateConfigurationBeforeSave(app); // The job is deleted and reinstalled before the store validates the request, so a zone the // repository would reject has to fail here first or the stored app ends up unscheduled. if (app.getAppSchedule() != null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java index 2b60d992e525..f2f4f8163b3f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/audit/AuditLogResource.java @@ -28,7 +28,9 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.TagLabel; import org.openmetadata.schema.utils.ResultList; @@ -40,7 +42,10 @@ import org.openmetadata.service.csv.CsvAsyncJobManager; import org.openmetadata.service.csv.CsvExportPayload; import org.openmetadata.service.csv.CsvExportSpool; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.ontology.OntologyChangeSetReadAccess; import org.openmetadata.service.resources.Collection; +import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.DefaultAuthorizer; import org.openmetadata.service.security.policyevaluator.OperationContext; @@ -136,7 +141,7 @@ public ResultList listAuditLogs( String searchTerm) { // Authorization: service-level, entity-level, or global based on filters provided - authorizeAuditLogAccess(securityContext, serviceName, entityType, entityFqn); + UUID changeSetId = authorizeAuditLogAccess(securityContext, serviceName, entityType, entityFqn); return repository.list( userName, @@ -151,7 +156,8 @@ public ResultList listAuditLogs( limit, before, after, - readsUserEmails(securityContext)); + readsUserEmails(securityContext), + changeSetId); } private static boolean readsUserEmails(SecurityContext securityContext) { @@ -411,26 +417,89 @@ private static boolean isLegacySpoolJobId(String jobId) { *

  • If serviceName AND entityType are provided: Check VIEW_BASIC on the service *
  • Otherwise: Require global AUDIT_LOGS permission (admin-only) * + * + * @return the id of the change set whose rows the caller may read through the draft read right, + * or null when the audit-log permission or another entity's right decided the request. Only + * the rows of that change set may be returned, because the name can have been used by a + * change set that no longer exists. */ - private void authorizeAuditLogAccess( + private UUID authorizeAuditLogAccess( SecurityContext securityContext, String serviceName, String entityType, String entityFqn) { + UUID changeSetId = null; if (!nullOrEmpty(entityFqn) && !nullOrEmpty(entityType)) { // Entity-level authorization: user needs VIEW_BASIC on the specific entity ResourceContext entityContext = new ResourceContext<>(entityType, null, entityFqn); OperationContext viewOp = new OperationContext(entityType, MetadataOperation.VIEW_BASIC); authorizer.authorize(securityContext, viewOp, entityContext); + if (Entity.ONTOLOGY_CHANGE_SET.equals(entityType)) { + changeSetId = authorizeChangeSetOperations(securityContext, entityFqn); + } } else if (!nullOrEmpty(serviceName) && !nullOrEmpty(entityType)) { // Service-level authorization: user needs VIEW_BASIC on the service String serviceType = Entity.getServiceType(entityType); ResourceContext serviceContext = new ResourceContext<>(serviceType, null, serviceName); OperationContext viewOp = new OperationContext(serviceType, MetadataOperation.VIEW_BASIC); authorizer.authorize(securityContext, viewOp, serviceContext); + if (Entity.ONTOLOGY_CHANGE_SET.equals(entityType)) { + // A change set has no service, so its events carry its own name as the service name. + changeSetId = authorizeChangeSetOperations(securityContext, serviceName); + } } else { // Global audit log access: requires AUDIT_LOGS permission (admin-only) OperationContext operationContext = new OperationContext(Entity.AUDIT_LOG, MetadataOperation.AUDIT_LOGS); authorizer.authorize(securityContext, operationContext, AuditLogResourceContext.INSTANCE); } + return changeSetId; + } + + /** + * The events of a change set hold its operations, which a draft read returns only to the right + * that edits its scope. Whoever holds the audit-log permission reads every event, so that + * permission decides first and the request is not narrowed. Otherwise the draft read right of + * the change set that holds the name now decides, and the audit-log permission alone decides when + * no change set can be loaded, such as a deleted one. + * + * @return the id of the change set the rows are limited to, which is set only when the draft + * read right decided. A name can have been held by a change set that no longer exists, and + * its rows are not the reader's to see. + */ + private UUID authorizeChangeSetOperations(SecurityContext securityContext, String entityFqn) { + if (holdsAuditLogPermission(securityContext)) { + return null; + } + OntologyChangeSet changeSet = null; + try { + changeSet = + Entity.getEntityByName( + Entity.ONTOLOGY_CHANGE_SET, + entityFqn, + OntologyChangeSetReadAccess.SCOPE_FIELDS, + Include.ALL); + } catch (EntityNotFoundException e) { + LOG.debug("Change set {} cannot be loaded; the audit-log permission applies", entityFqn); + } + if (changeSet == null) { + authorizer.authorize( + securityContext, + new OperationContext(Entity.AUDIT_LOG, MetadataOperation.AUDIT_LOGS), + AuditLogResourceContext.INSTANCE); + return null; + } + OntologyChangeSetReadAccess.requireRead(authorizer, securityContext, changeSet); + return changeSet.getId(); + } + + private boolean holdsAuditLogPermission(SecurityContext securityContext) { + try { + authorizer.authorize( + securityContext, + new OperationContext(Entity.AUDIT_LOG, MetadataOperation.AUDIT_LOGS), + AuditLogResourceContext.INSTANCE); + return true; + } catch (AuthorizationException e) { + return false; + } } /** diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResource.java index 81638b4b1390..827c2e5b77e6 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResource.java @@ -967,11 +967,10 @@ public Response createOrUpdate( TestCase test = mapper.createToEntity(create, securityContext.getUserPrincipal().getName()); // Only the FQN before authorizing: prepare creates the table's test suite if it is missing. repository.setFullyQualifiedName(test); - boolean testCaseExists = - repository.findByNameOrNull(test.getFullyQualifiedName(), Include.ALL) != null; + TestCase stored = repository.findByNameOrNull(test.getFullyQualifiedName(), Include.ALL); authorizer.authorizeRequests( - securityContext, createOrUpdateRequests(test, testCaseExists), AuthorizationLogic.ANY); - repository.prepareInternal(test, testCaseExists); + securityContext, createOrUpdateRequests(test, stored != null), AuthorizationLogic.ANY); + repository.prepareInternal(test, stored); PutResponse response = repository.createOrUpdate(uriInfo, test, securityContext.getUserPrincipal().getName()); addHref(uriInfo, response.getEntity()); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java index db0ff1671005..57ab0899a0fa 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyChangeSetResource.java @@ -42,7 +42,10 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.UUID; +import java.util.function.UnaryOperator; import java.util.stream.Collectors; import org.openmetadata.schema.api.data.ApplyOntologyChangeSet; import org.openmetadata.schema.api.data.CreateOntologyChangeSet; @@ -58,6 +61,7 @@ import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeSetState; import org.openmetadata.schema.type.OntologyEditLeaseToken; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.GlossaryTermRepository; @@ -65,8 +69,14 @@ import org.openmetadata.service.jdbi3.OntologyChangeSetRepository; import org.openmetadata.service.limits.Limits; import org.openmetadata.service.ontology.NativeOntologyChanges; +import org.openmetadata.service.ontology.OntologyBindingChangeExecutor; +import org.openmetadata.service.ontology.OntologyBindingChanges; import org.openmetadata.service.ontology.OntologyChangeApplicationService; +import org.openmetadata.service.ontology.OntologyChangeEvidenceView; +import org.openmetadata.service.ontology.OntologyChangeSetReadAccess; import org.openmetadata.service.ontology.OntologyChangeSetValidator; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.ontology.OntologyDraftPreflight; import org.openmetadata.service.ontology.OntologyEditLeasePolicy; import org.openmetadata.service.ontology.OntologyEditLockService; import org.openmetadata.service.resources.Collection; @@ -90,6 +100,7 @@ public class OntologyChangeSetResource private static final String FIELDS = "operations,applicationResult"; private final OntologyChangeSetMapper mapper = new OntologyChangeSetMapper(); private final OntologyChangeApplicationService applicationService; + private final OntologyDraftPreflight draftPreflight; private final OntologyEditLockService lockService; public OntologyChangeSetResource(final Authorizer authorizer, final Limits limits) { @@ -99,7 +110,9 @@ public OntologyChangeSetResource(final Authorizer authorizer, final Limits limit new OntologyChangeApplicationService( repository, (GlossaryTermRepository) Entity.getEntityRepository(Entity.GLOSSARY_TERM), - clock); + clock, + OntologyBindingChangeExecutor.production(authorizer)); + draftPreflight = OntologyDraftPreflight.production(); lockService = new OntologyEditLockService(Entity.getJdbi(), clock, new OntologyEditLeasePolicy()); } @@ -145,6 +158,7 @@ public ResultList list( if (scopeId == null) { authorizeListedScopes(securityContext, page.getData()); } + evidence(uriInfo, securityContext).applyAll(page.getData()); return page; } @@ -202,7 +216,8 @@ public OntologyChangeSet get( @QueryParam("fields") final String fields, @QueryParam("include") @DefaultValue("non-deleted") final Include include) { authorizeScopeRead(securityContext, readableChangeSet(id)); - return getInternal(uriInfo, securityContext, id, fields, include, null); + return evidence(uriInfo, securityContext) + .apply(getInternal(uriInfo, securityContext, id, fields, include, null)); } @POST @@ -213,7 +228,10 @@ public Response create( @Valid final CreateOntologyChangeSet request) { final OntologyChangeSet entity = mapper.createToEntity(request, user(securityContext)); authorizeScope(securityContext, entity, MetadataOperation.EDIT_ALL); - return create(uriInfo, securityContext, entity); + requireResolved(entity); + final OntologyChangeEvidenceView evidence = evidence(uriInfo, securityContext); + evidence.savedByReader(List.of(), entity.getOperations()); + return masked(evidence, create(uriInfo, securityContext, entity)); } @PUT @@ -226,10 +244,85 @@ public Response replaceOperations( @Valid final UpdateOntologyChangeSet request) { authorizeChangeSet(securityContext, id); requireLease(id, request.getLease(), securityContext); - return repository - .replaceOperations( - uriInfo, user(securityContext), id, request.getOperations(), request.getUndoCursor()) - .toResponse(); + final OntologyChangeEvidenceView evidence = evidence(uriInfo, securityContext); + return masked( + evidence, + repository + .replaceOperations( + uriInfo, + user(securityContext), + id, + savable(evidence, id, request), + request.getUndoCursor()) + .toResponse()); + } + + /** + * The operations a save stores. They pass the rules the repository applies, then name classes, + * properties, tables and columns that exist, and they carry the evidence the writer may write + * beside the evidence the writer was not shown. + */ + private List savable( + final OntologyChangeEvidenceView evidence, + final UUID id, + final UpdateOntologyChangeSet request) { + final OntologyChangeSet draft = scopedChangeSet(id); + final List stored = listOrEmpty(draft.getOperations()); + final Map readWithheld = withheldCountsRead(request.getOperations()); + draft.setOperations(request.getOperations()); + draft.setUndoCursor(request.getUndoCursor()); + OntologyChangeSetValidator.normalizeAndValidate(draft); + requireResolved(draft); + return evidence.savedByReader(stored, draft.getOperations(), readWithheld); + } + + /** What each operation says its writer's read withheld, taken before validation clears it. */ + private static Map withheldCountsRead(final List sent) { + final Map counts = new LinkedHashMap<>(); + listOrEmpty(sent).stream() + .filter(operation -> operation.getId() != null) + .filter(operation -> operation.getWithheldEvidenceCount() != null) + .forEach(operation -> counts.put(operation.getId(), operation.getWithheldEvidenceCount())); + return counts; + } + + private void requireResolved(final OntologyChangeSet draft) { + if (draft.getOntology() != null) { + draftPreflight.validate(draft.getOntology().getId(), draft.getOperations()); + } + } + + private OntologyChangeEvidenceView evidence( + final UriInfo uriInfo, final SecurityContext securityContext) { + return OntologyChangeEvidenceView.of(authorizer, new Access(uriInfo, securityContext)); + } + + /** + * A write answers with the instance the repository stored and passed to its listeners, so the + * reader's view is taken from a copy of it. + */ + private Response masked(final OntologyChangeEvidenceView evidence, final Response response) { + return withRedactedEntity( + response, stored -> evidence.apply(JsonUtils.deepCopy(stored, OntologyChangeSet.class))); + } + + /** A stored version carries every evidence entry, so it is read through the reader's view. */ + @Override + protected Optional> snapshotRedaction( + final SecurityContext securityContext) { + return Optional.of(evidence(null, securityContext)); + } + + /** + * A snapshot is a version of a change set, so it is kept only when its change set may be read + * with the draft read right. The right is asked once for each change set in the page, and a + * refusal, or a change set that cannot be loaded, drops its snapshots and leaves the answer a 200. + */ + @Override + protected List retainReadableHistory( + final SecurityContext securityContext, final List snapshots) { + return OntologyChangeSetReadAccess.readable( + authorizer, securityContext, snapshots, this::readableChangeSet); } @POST @@ -242,7 +335,9 @@ public Response undo( @Valid final OntologyChangeSetCommand request) { authorizeChangeSet(securityContext, id); requireLease(id, request.getLease(), securityContext); - return repository.moveCursor(uriInfo, user(securityContext), id, -1).toResponse(); + return masked( + evidence(uriInfo, securityContext), + repository.moveCursor(uriInfo, user(securityContext), id, -1).toResponse()); } @POST @@ -255,7 +350,9 @@ public Response redo( @Valid final OntologyChangeSetCommand request) { authorizeChangeSet(securityContext, id); requireLease(id, request.getLease(), securityContext); - return repository.moveCursor(uriInfo, user(securityContext), id, 1).toResponse(); + return masked( + evidence(uriInfo, securityContext), + repository.moveCursor(uriInfo, user(securityContext), id, 1).toResponse()); } @POST @@ -269,9 +366,11 @@ public Response submit( final OntologyChangeSet changeSet = scopedChangeSet(id); authorizeScope(securityContext, changeSet, MetadataOperation.EDIT_ALL); requireLease(id, request.getLease(), securityContext); - return repository - .transition(uriInfo, user(securityContext), id, OntologyChangeSetState.SUBMITTED, null) - .toResponse(); + return masked( + evidence(uriInfo, securityContext), + repository + .transition(uriInfo, user(securityContext), id, OntologyChangeSetState.SUBMITTED, null) + .toResponse()); } @POST @@ -286,9 +385,9 @@ public Response apply( authorizeScope(securityContext, changeSet, MetadataOperation.EDIT_ALL); requireLease(id, request.getLease(), securityContext); final PutResponse response = - applicationService.apply(uriInfo, id, user(securityContext)); + applicationService.apply(new Access(uriInfo, securityContext), id); releaseAppliedLease(response.getEntity(), request.getLease(), securityContext); - return response.toResponse(); + return masked(evidence(uriInfo, securityContext), response.toResponse()); } @POST @@ -301,9 +400,11 @@ public Response discard( @Valid final OntologyChangeSetCommand request) { authorizeChangeSet(securityContext, id); requireLease(id, request.getLease(), securityContext); - return repository - .transition(uriInfo, user(securityContext), id, OntologyChangeSetState.DISCARDED, null) - .toResponse(); + return masked( + evidence(uriInfo, securityContext), + repository + .transition(uriInfo, user(securityContext), id, OntologyChangeSetState.DISCARDED, null) + .toResponse()); } @GET @@ -334,7 +435,10 @@ public Response delete( @Context final SecurityContext securityContext, @PathParam("id") final UUID id, @QueryParam("hardDelete") @DefaultValue("false") final boolean hardDelete) { - return delete(uriInfo, securityContext, id, false, hardDelete); + authorizeScopeRead(securityContext, readableChangeSet(id)); + return masked( + evidence(uriInfo, securityContext), + delete(uriInfo, securityContext, id, false, hardDelete)); } @PUT @@ -344,7 +448,10 @@ public Response restore( @Context final UriInfo uriInfo, @Context final SecurityContext securityContext, @Valid final RestoreEntity restore) { - return restoreEntity(uriInfo, securityContext, restore.getId()); + authorizeScopeRead(securityContext, readableChangeSet(restore.getId())); + return masked( + evidence(uriInfo, securityContext), + restoreEntity(uriInfo, securityContext, restore.getId())); } private OntologyChangeSet scopedChangeSet(final UUID id) { @@ -379,7 +486,12 @@ private static String requireStates(final String states) { } } + /** + * A command on a draft answers with its operations and may write them, so it asks the draft read + * right before the edit right on the change set, and before any write. + */ private void authorizeChangeSet(final SecurityContext securityContext, final UUID changeSetId) { + authorizeScopeRead(securityContext, readableChangeSet(changeSetId)); authorizer.authorize( securityContext, new OperationContext(entityType, MetadataOperation.EDIT_ALL), @@ -393,14 +505,7 @@ private void authorizeChangeSet(final SecurityContext securityContext, final UUI */ private void authorizeScopeRead( final SecurityContext securityContext, final OntologyChangeSet changeSet) { - if (changeSet.getOntology() != null) { - OntologyResourceAccess.requireDraftRead( - authorizer, - securityContext, - new ResourceContext<>(Entity.ONTOLOGY, changeSet.getOntology().getId(), null)); - return; - } - authorizeGlossaryScope(securityContext, changeSet, MetadataOperation.EDIT_ALL); + OntologyChangeSetReadAccess.requireRead(authorizer, securityContext, changeSet); } private void authorizeScope( @@ -452,6 +557,11 @@ private void authorizeGlossary( new ResourceContext<>(Entity.GLOSSARY, glossary.getId(), null)); } + /** + * A definition operation is authorized here, when the draft is saved, submitted or applied. A + * binding operation is authorized where it is written, with the rights of the caller who applies + * the draft, whoever saved it. + */ private void authorizeNativeScope( final SecurityContext context, final OntologyChangeSet changeSet) { authorizer.authorize( @@ -460,30 +570,42 @@ private void authorizeNativeScope( new ResourceContext<>(Entity.ONTOLOGY, changeSet.getOntology().getId(), null)); for (final OntologyChangeOperation change : changeSet.getOperations().subList(0, changeSet.getUndoCursor())) { - final String type = NativeOntologyChanges.entityType(change); - if (change.getTargetId() == null) { - authorizer.authorize( - context, - new OperationContext(type, MetadataOperation.CREATE), - new CreateResourceContext<>(type, NativeOntologyChanges.definition(change))); - } else { - final MetadataOperation operation = - NativeOntologyChanges.isDelete(change) - ? MetadataOperation.DELETE - : MetadataOperation.EDIT_ALL; - authorizer.authorize( - context, - new OperationContext(type, operation), - new ResourceContext<>(type, change.getTargetId(), null)); - } - if (change.getSourceMemoryIds() != null) { - for (final UUID memoryId : change.getSourceMemoryIds()) { - authorizer.authorize( - context, - new OperationContext(Entity.CONTEXT_MEMORY, MetadataOperation.VIEW_ALL), - new ResourceContext<>(Entity.CONTEXT_MEMORY, memoryId, null)); - } + if (!OntologyBindingChanges.isBinding(change)) { + authorizeDefinition(context, change); } + authorizeSourceMemories(context, change); + } + } + + private void authorizeDefinition( + final SecurityContext context, final OntologyChangeOperation change) { + final String type = NativeOntologyChanges.entityType(change); + if (change.getTargetId() == null) { + authorizer.authorize( + context, + new OperationContext(type, MetadataOperation.CREATE), + new CreateResourceContext<>(type, NativeOntologyChanges.definition(change))); + return; + } + final MetadataOperation operation = + NativeOntologyChanges.isDelete(change) + ? MetadataOperation.DELETE + : MetadataOperation.EDIT_ALL; + authorizer.authorize( + context, + new OperationContext(type, operation), + new ResourceContext<>(type, change.getTargetId(), null)); + } + + private void authorizeSourceMemories( + final SecurityContext context, final OntologyChangeOperation change) { + final Set memoryIds = + change.getSourceMemoryIds() == null ? Set.of() : change.getSourceMemoryIds(); + for (final UUID memoryId : memoryIds) { + authorizer.authorize( + context, + new OperationContext(Entity.CONTEXT_MEMORY, MetadataOperation.VIEW_ALL), + new ResourceContext<>(Entity.CONTEXT_MEMORY, memoryId, null)); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyConceptResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyConceptResource.java index e3c020a03d21..ab700b3abdc2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyConceptResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyConceptResource.java @@ -14,11 +14,13 @@ package org.openmetadata.service.resources.ontology; import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.json.JsonPatch; import jakarta.validation.Valid; import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.DefaultValue; @@ -39,8 +41,15 @@ import java.util.UUID; import java.util.stream.Stream; import org.openmetadata.schema.api.data.CreateOntologyConcept; +import org.openmetadata.schema.api.data.OntologyAggregateStatementRequest; import org.openmetadata.schema.api.data.OntologyConceptDeleteImpact; import org.openmetadata.schema.api.data.OntologyConceptQuery; +import org.openmetadata.schema.api.data.OntologyExpandStatementRequest; +import org.openmetadata.schema.api.data.OntologyFindStatementRequest; +import org.openmetadata.schema.api.data.OntologyOpenStatementRequest; +import org.openmetadata.schema.api.data.OntologyShapeChecks; +import org.openmetadata.schema.api.data.OntologyStatementPlan; +import org.openmetadata.schema.api.data.OntologyStatementVersion; import org.openmetadata.schema.api.data.RestoreEntity; import org.openmetadata.schema.api.data.UpdateOntologyConceptBinding; import org.openmetadata.schema.entity.data.OntologyConcept; @@ -58,6 +67,7 @@ import org.openmetadata.service.ontology.OntologyConceptBindingService; import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.ontology.OntologyConceptQueryService; +import org.openmetadata.service.ontology.OntologyStatementService; import org.openmetadata.service.resources.Collection; import org.openmetadata.service.resources.EntityResource; import org.openmetadata.service.security.Authorizer; @@ -77,6 +87,7 @@ public class OntologyConceptResource private final OntologyConceptMapper mapper = new OntologyConceptMapper(); private final OntologyConceptBindingService bindings; private final OntologyConceptQueryService queries; + private final OntologyStatementService statements; public OntologyConceptResource(final Authorizer authorizer, final Limits limits) { super(Entity.ONTOLOGY_CONCEPT, authorizer, limits); @@ -86,6 +97,15 @@ public OntologyConceptResource(final Authorizer authorizer, final Limits limits) Entity.getCollectionDAO(), OntologyConceptBindingStore.registeredAssetTables()); bindings = new OntologyConceptBindingService(store, authorizer, Entity::getEntityRepository); queries = new OntologyConceptQueryService(store, authorizer, Entity::getEntityRepository); + statements = + new OntologyStatementService( + store, + Entity.getCollectionDAO(), + authorizer, + Entity::getEntityRepository, + (context, ontologyId) -> + OntologyResourceAccess.requireDraftRead( + authorizer, context, new ResourceContext<>(Entity.ONTOLOGY, ontologyId, null))); } public static class OntologyConceptList extends ResultList {} @@ -236,6 +256,92 @@ public OntologyConceptQuery generateQuery( return queries.generate(new Access(uriInfo, securityContext), id, request); } + @POST + @Path("/{id}/statements/find") + @Operation( + operationId = "generateOntologyFindStatement", + summary = "Generate the SELECT that lists records of a class", + description = + "Returns one SELECT over the identity table of the class, at most 25 rows, with a column" + + " plan. Nothing runs and nothing is stored.") + public OntologyStatementPlan findStatement( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @Valid final OntologyFindStatementRequest request) { + return statements.find(new Access(uriInfo, securityContext), id, request); + } + + @POST + @Path("/{id}/statements/open") + @Operation( + operationId = "generateOntologyOpenStatement", + summary = "Generate the SELECT that reads every bound column of one record", + description = + "Returns one SELECT that joins the contributing tables of the class to its identity" + + " table on the subject key. Nothing runs and nothing is stored.") + public OntologyStatementPlan openStatement( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @Valid @NotNull final OntologyOpenStatementRequest request) { + return statements.open(new Access(uriInfo, securityContext), id, request); + } + + @POST + @Path("/{id}/statements/expand") + @Operation( + operationId = "generateOntologyExpandStatement", + summary = "Generate the SELECT that lists the records one record relates to", + description = + "Returns one SELECT that follows a confirmed join of the relation and asks for one row" + + " more than a page of 25. Nothing runs and nothing is stored.") + public OntologyStatementPlan expandStatement( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @Valid @NotNull final OntologyExpandStatementRequest request) { + return statements.expand(new Access(uriInfo, securityContext), id, request); + } + + @POST + @Path("/{id}/statements/aggregate") + @Operation( + operationId = "generateOntologyAggregateStatement", + summary = "Generate the SELECT that counts records of a class", + description = + "With no relation, returns the SELECT that counts the records of the class. With a" + + " relation and a direction, returns the SELECT that lists the 8 records related to" + + " the most records. Nothing runs and nothing is stored.") + public OntologyStatementPlan aggregateStatement( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @Valid final OntologyAggregateStatementRequest request) { + return statements.aggregate(new Access(uriInfo, securityContext), id, request); + } + + @GET + @Path("/{id}/shapeChecks") + @Operation( + operationId = "getOntologyShapeChecks", + summary = "Say how the shapes of a class are checked on its tables", + description = + "For each part of each constraint of the shapes that target the class, returns the data" + + " quality test that finds exactly the records that break it, or says that the table" + + " bindings already hold it, that the property is not mapped, or why no exact test" + + " exists. Nothing is created, scheduled or run.") + public OntologyShapeChecks shapeChecks( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @Parameter(description = "The ontology version to read: its active release, or its draft") + @QueryParam("version") + @DefaultValue("release") + final OntologyStatementVersion version) { + return statements.shapeChecks(new Access(uriInfo, securityContext), id, version); + } + @GET @Path("/name/{fqn}") @Operation(operationId = "getOntologyConceptByName", summary = "Get an ontology concept by name") diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionEndpoint.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionEndpoint.java new file mode 100644 index 000000000000..205db8566065 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionEndpoint.java @@ -0,0 +1,112 @@ +/* + * 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.resources.ontology; + +import jakarta.ws.rs.BadRequestException; +import jakarta.ws.rs.core.SecurityContext; +import java.time.Clock; +import java.util.UUID; +import org.openmetadata.schema.api.data.DeclineOntologyDefinitions; +import org.openmetadata.schema.api.data.MatchOntologyDeclinedDefinitions; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionMatches; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionPage; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.OntologyChangeSetRepository; +import org.openmetadata.service.ontology.OntologyChangeSetReadAccess; +import org.openmetadata.service.ontology.OntologyDeclinedDefinitions; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; + +/** + * Authorizes and serves the declined-definition endpoints of an ontology. Declining edits the + * change set the operations came from, so it needs the right to edit that change set. Listing and + * matching read what the change sets hold, so they need the right that reads them. + */ +final class OntologyDeclinedDefinitionEndpoint { + private final Authorizer authorizer; + private final OntologyDeclinedDefinitions declined; + + OntologyDeclinedDefinitionEndpoint(final Authorizer authorizer) { + this.authorizer = authorizer; + declined = + new OntologyDeclinedDefinitions( + Entity.getCollectionDAO().ontologyDeclinedDefinitionDAO(), Clock.systemUTC()); + } + + OntologyDeclinedDefinitionPage decline( + final SecurityContext securityContext, + final UUID ontologyId, + final DeclineOntologyDefinitions request) { + authorizer.authorize( + securityContext, + new OperationContext(Entity.ONTOLOGY_CHANGE_SET, MetadataOperation.EDIT_ALL), + new ResourceContext<>(Entity.ONTOLOGY_CHANGE_SET, request.getChangeSetId(), null)); + final OntologyChangeSet changeSet = changeSetOf(request.getChangeSetId()); + OntologyChangeSetReadAccess.requireRead(authorizer, securityContext, changeSet); + requireBelongs(changeSet, ontologyId); + return declined.decline( + changeSet, + request.getOperationIds(), + request.getReason(), + securityContext.getUserPrincipal().getName()); + } + + OntologyDeclinedDefinitionPage list( + final SecurityContext securityContext, + final UUID ontologyId, + final int limit, + final String after) { + requireRead(securityContext, ontologyId); + return declined.list(ontologyId, limit, after); + } + + OntologyDeclinedDefinitionMatches match( + final SecurityContext securityContext, + final UUID ontologyId, + final MatchOntologyDeclinedDefinitions request) { + requireRead(securityContext, ontologyId); + return declined.match(ontologyId, request.getCandidates()); + } + + private void requireRead(final SecurityContext securityContext, final UUID ontologyId) { + OntologyResourceAccess.requireDraftRead( + authorizer, securityContext, new ResourceContext<>(Entity.ONTOLOGY, ontologyId, null)); + } + + private static OntologyChangeSet changeSetOf(final UUID changeSetId) { + final OntologyChangeSetRepository repository = + (OntologyChangeSetRepository) Entity.getEntityRepository(Entity.ONTOLOGY_CHANGE_SET); + return repository.get( + null, + changeSetId, + repository.getFields(OntologyChangeSetReadAccess.SCOPE_FIELDS), + Include.ALL, + false); + } + + private static void requireBelongs(final OntologyChangeSet changeSet, final UUID ontologyId) { + if (changeSet.getOntology() == null || !ontologyId.equals(changeSet.getOntology().getId())) { + throw new BadRequestException( + "Change set '" + + changeSet.getId() + + "' does not belong to ontology '" + + ontologyId + + "'"); + } + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyEditLockResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyEditLockResource.java index a4e735b089fc..d21afeee4a73 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyEditLockResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyEditLockResource.java @@ -32,10 +32,12 @@ import java.time.Clock; import java.util.UUID; import org.openmetadata.schema.api.data.AcquireOntologyEditLock; +import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.OntologyEditLock; import org.openmetadata.service.Entity; import org.openmetadata.service.limits.Limits; +import org.openmetadata.service.ontology.OntologyChangeSetReadAccess; import org.openmetadata.service.ontology.OntologyEditLeasePolicy; import org.openmetadata.service.ontology.OntologyEditLockService; import org.openmetadata.service.resources.Collection; @@ -105,12 +107,32 @@ public Response release( private void authorizeEdit( final SecurityContext securityContext, final String resourceType, final UUID resourceId) { + requireDraftRead(securityContext, resourceType, resourceId); final OperationContext operationContext = new OperationContext(resourceType, editOperation(resourceType)); authorizer.authorize( securityContext, operationContext, new ResourceContext<>(resourceType, resourceId, null)); } + /** + * A lease on a draft is held by someone who edits it, and its holder is named in the answer, so + * taking, renewing, reading or releasing one asks the draft read right first. Without it a user + * who may not read the draft could hold its lease and block the people who edit it. + */ + private void requireDraftRead( + final SecurityContext securityContext, final String resourceType, final UUID resourceId) { + if (Entity.ONTOLOGY_CHANGE_SET.equalsIgnoreCase(resourceType)) { + OntologyChangeSetReadAccess.requireRead( + authorizer, + securityContext, + Entity.getEntity( + Entity.ONTOLOGY_CHANGE_SET, + resourceId, + OntologyChangeSetReadAccess.SCOPE_FIELDS, + Include.ALL)); + } + } + static MetadataOperation editOperation(final String resourceType) { return MetadataOperation.EDIT_ALL; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyMapper.java index f5a6fb262e4e..f5dad6f007fe 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyMapper.java @@ -13,6 +13,7 @@ public Ontology createToEntity(final CreateOntology request, final String user) .withLayer(request.getLayer()) .withPrefixes(request.getPrefixes()) .withApprovalRule(request.getApprovalRule()) + .withMappingSource(request.getMappingSource()) .withProvider(request.getProvider()); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyPropertyMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyPropertyMapper.java index e1e1933c353f..3b437ad97833 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyPropertyMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyPropertyMapper.java @@ -21,6 +21,7 @@ public OntologyProperty createToEntity(final CreateOntologyProperty request, fin .withEnumValues(request.getEnumValues()) .withUnit(request.getUnit()) .withIsIdentifier(request.getIsIdentifier()) + .withIsDisplayName(request.getIsDisplayName()) .withInverse(request.getInverse()) .withCharacteristics(request.getCharacteristics()) .withPropertyChain(request.getPropertyChain()) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyReleaseResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyReleaseResource.java index 95bdd8dbb88d..a5b48bfe63f9 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyReleaseResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyReleaseResource.java @@ -362,12 +362,11 @@ public ResultList listMembers( @QueryParam("limit") @DefaultValue("50") @Min(1) @Max(1000) final int limit, @QueryParam("after") final String after) { get(uriInfo, securityContext, id); - final ResultList members = - repository.listMembers(id, kind, limit, after); - OntologyResourceAccess.requireView( - authorizer, - securityContext, - members.getData().stream().map(OntologyReleaseReader::definition).toList()); - return members; + return repository.listViewableMembers( + id, + kind, + limit, + after, + batch -> OntologyResourceAccess.retainViewable(authorizer, securityContext, batch)); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java index 4acc3dd52a85..bf2811861537 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResource.java @@ -54,7 +54,9 @@ import org.openmetadata.schema.api.data.CaptureOntologyRelease; import org.openmetadata.schema.api.data.CreateOntology; import org.openmetadata.schema.api.data.CreateOntologyChangeSet; +import org.openmetadata.schema.api.data.DeclineOntologyDefinitions; import org.openmetadata.schema.api.data.InstallNativeOntologyPack; +import org.openmetadata.schema.api.data.MatchOntologyDeclinedDefinitions; import org.openmetadata.schema.api.data.NativeOntologyDataGraph; import org.openmetadata.schema.api.data.NativeOntologyDataGraphPage; import org.openmetadata.schema.api.data.NativeOntologyDataGraphPageRequest; @@ -62,6 +64,7 @@ import org.openmetadata.schema.api.data.NativeOntologyImportFormat; import org.openmetadata.schema.api.data.NativeOntologyImportPreview; import org.openmetadata.schema.api.data.NativeOntologyImportSummary; +import org.openmetadata.schema.api.data.OntologyMappingHealth; import org.openmetadata.schema.api.data.OntologyPackInstallJob; import org.openmetadata.schema.api.data.OntologyProfileReport; import org.openmetadata.schema.api.data.OntologyReleaseExportOptions; @@ -76,6 +79,8 @@ import org.openmetadata.schema.type.EntityHistory; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionMatches; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionPage; import org.openmetadata.schema.type.OntologyReference; import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; import org.openmetadata.schema.type.OntologyState; @@ -89,15 +94,18 @@ import org.openmetadata.service.jdbi3.OntologyPropertyRepository; import org.openmetadata.service.jdbi3.OntologyReleaseRepository; import org.openmetadata.service.jdbi3.OntologyRepository; +import org.openmetadata.service.jdbi3.OntologyShapeRepository; import org.openmetadata.service.limits.Limits; import org.openmetadata.service.ontology.NativeOntologyDataGraphPager; import org.openmetadata.service.ontology.NativeOntologyDataGraphService; import org.openmetadata.service.ontology.NativeOntologyDataGraphService.Query; import org.openmetadata.service.ontology.NativeOntologyTopologyCursorCodec; +import org.openmetadata.service.ontology.OntologyCheckReconcileQueue; import org.openmetadata.service.ontology.OntologyConceptBindingService; import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.ontology.OntologyDraftQuery; import org.openmetadata.service.ontology.OntologyFormatDetector; +import org.openmetadata.service.ontology.OntologyMappingHealthService; import org.openmetadata.service.ontology.OntologyPackCatalog; import org.openmetadata.service.ontology.OntologyPackContentLoader; import org.openmetadata.service.ontology.OntologyPackInstallJobManager; @@ -134,6 +142,8 @@ @Collection(name = "ontologies", order = 3) public class OntologyResource extends EntityResource { public static final String COLLECTION_PATH = "/v1/ontologies/"; + private static final String MAPPING_SOURCE = "mappingSource"; + private static final String VIEW_BASIC_FIELDS = "publicationStatus," + MAPPING_SOURCE; private final OntologyMapper mapper = new OntologyMapper(); private final OntologyReleaseCapture releaseCapture; private final OntologyReleaseActivation releaseActivation; @@ -150,7 +160,8 @@ public class OntologyResource extends EntityResource - OntologyResourceAccess.requireView(authorizer, securityContext, definition))); + final OntologyState state = + releaseActivation.activate( + id, + request, + new OntologyReleaseActivation.Access( + user(securityContext), + definition -> + OntologyResourceAccess.requireView(authorizer, securityContext, definition))); + OntologyCheckReconcileQueue.instance().afterActivation(id, user(securityContext)); + return state; + } + + @POST + @Path("/{id}/declinedDefinitions") + @Operation( + operationId = "declineOntologyDefinitions", + summary = "Decline the definitions of operations of a change set") + public OntologyDeclinedDefinitionPage declineDefinitions( + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @Valid final DeclineOntologyDefinitions request) { + return declinedDefinitions.decline(securityContext, id, request); + } + + @GET + @Path("/{id}/declinedDefinitions") + @Operation( + operationId = "listOntologyDeclinedDefinitions", + summary = "List the definitions declined for an ontology") + public OntologyDeclinedDefinitionPage listDeclinedDefinitions( + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @QueryParam("limit") @DefaultValue("50") @Min(1) @Max(1000) final int limit, + @QueryParam("after") final String after) { + return declinedDefinitions.list(securityContext, id, limit, after); + } + + @POST + @Path("/{id}/declinedDefinitions/match") + @Operation( + operationId = "matchOntologyDeclinedDefinitions", + summary = "Match candidate operations against the declined definitions") + public OntologyDeclinedDefinitionMatches matchDeclinedDefinitions( + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @Valid final MatchOntologyDeclinedDefinitions request) { + return declinedDefinitions.match(securityContext, id, request); } @GET @@ -631,6 +688,27 @@ public NativeOntologyDataGraphPage getDataGraphPage( return dataGraphPages.page(new Access(uriInfo, securityContext), id, request); } + @GET + @Path("/{id}/mappingHealth") + @Operation( + operationId = "getOntologyMappingHealth", + summary = + "List what the table bindings of an ontology's classes still need before their rows can be read as records, from catalog metadata alone") + public OntologyMappingHealth getMappingHealth( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @QueryParam("limit") + @DefaultValue("50") + @Min(1) + @Max(OntologyMappingHealthService.MAX_PAGE_SIZE) + final int limit, + @QueryParam("after") final String after) { + final Ontology ontology = + getInternal(uriInfo, securityContext, id, MAPPING_SOURCE, Include.NON_DELETED, null); + return mappingHealth.page(new Access(uriInfo, securityContext), ontology, after, limit); + } + @GET @Path("/reviews") @Operation( @@ -774,7 +852,10 @@ public ResultList list( @QueryParam("after") final String after, @QueryParam("include") @DefaultValue("non-deleted") final Include include) { final ListFilter filter = new ListFilter(include); - return listInternal(uriInfo, securityContext, fields, filter, limit, before, after); + final var page = listInternal(uriInfo, securityContext, fields, filter, limit, before, after); + final Access access = new Access(uriInfo, securityContext); + page.getData().forEach(ontology -> mappingHealth.withViewableMappingSource(access, ontology)); + return page; } @GET @@ -786,7 +867,8 @@ public Ontology get( @PathParam("id") final UUID id, @QueryParam("fields") final String fields, @QueryParam("include") @DefaultValue("non-deleted") final Include include) { - return getInternal(uriInfo, securityContext, id, fields, include, null); + final Ontology ontology = getInternal(uriInfo, securityContext, id, fields, include, null); + return mappingHealth.withViewableMappingSource(new Access(uriInfo, securityContext), ontology); } @GET @@ -798,7 +880,9 @@ public Ontology getByName( @PathParam("fqn") final String fqn, @QueryParam("fields") final String fields, @QueryParam("include") @DefaultValue("non-deleted") final Include include) { - return getByNameInternal(uriInfo, securityContext, fqn, fields, include, null); + final Ontology ontology = + getByNameInternal(uriInfo, securityContext, fqn, fields, include, null); + return mappingHealth.withViewableMappingSource(new Access(uriInfo, securityContext), ontology); } @POST diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResourceAccess.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResourceAccess.java index 5c702fe0fd1d..8b2d2f675302 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResourceAccess.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyResourceAccess.java @@ -5,6 +5,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import java.util.Collection; +import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -20,10 +21,13 @@ import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.jdbi3.OntologyEntityRepository; +import org.openmetadata.service.ontology.OntologyReleaseReader; import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.ViewPermissionFilter; import org.openmetadata.service.security.policyevaluator.CreateResourceContext; import org.openmetadata.service.security.policyevaluator.OperationContext; import org.openmetadata.service.security.policyevaluator.ResourceContext; @@ -206,6 +210,47 @@ static void requireView( requireView(authorizer, context, batch, Entity.getEntityRepository(type))); } + /** The release members whose definitions the caller may view, as a by-id read would decide. */ + static List retainViewable( + final Authorizer authorizer, + final SecurityContext context, + final List members) { + final Set viewable = new HashSet<>(); + members.stream() + .collect( + Collectors.groupingBy( + member -> OntologyReleaseReader.definition(member).getEntityReference().getType())) + .forEach( + (type, batch) -> + viewable.addAll( + viewableIds(authorizer, context, batch, Entity.getEntityRepository(type)))); + return members.stream().filter(member -> viewable.contains(member.getMemberId())).toList(); + } + + private static > Set viewableIds( + final Authorizer authorizer, + final SecurityContext context, + final List members, + final EntityRepository repository) { + final List rows = + members.stream() + .map( + member -> + repository.getEntityClass().cast(OntologyReleaseReader.definition(member))) + .toList(); + repository.setFieldsInBulk(ResourceContext.authorizationFields(repository), rows); + return new ViewPermissionFilter(authorizer) + .retainPermitted( + context, + repository.getEntityType(), + repository, + rows, + List.of(MetadataOperation.VIEW_ALL)) + .stream() + .map(EntityInterface::getId) + .collect(Collectors.toSet()); + } + private static > void requireView( final Authorizer authorizer, final SecurityContext context, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeMapper.java new file mode 100644 index 000000000000..a0ed86edb66f --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeMapper.java @@ -0,0 +1,38 @@ +/* + * 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.resources.ontology; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; + +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.service.Entity; +import org.openmetadata.service.mapper.EntityMapper; + +public final class OntologyShapeMapper implements EntityMapper { + @Override + public OntologyShape createToEntity(final CreateOntologyShape request, final String user) { + return copy(new OntologyShape(), request, user) + .withOntology( + Entity.getEntityReferenceByName( + Entity.ONTOLOGY, request.getOntology(), Include.NON_DELETED)) + .withTargetConcept(request.getTargetConcept()) + .withSeverity( + request.getSeverity() == null ? OntologyShapeSeverity.VIOLATION : request.getSeverity()) + .withConstraints(listOrEmpty(request.getConstraints())) + .withProvider(request.getProvider()); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeResource.java new file mode 100644 index 000000000000..f237981a505a --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/ontology/OntologyShapeResource.java @@ -0,0 +1,324 @@ +/* + * 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.resources.ontology; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.json.JsonPatch; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.DefaultValue; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PATCH; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.SecurityContext; +import jakarta.ws.rs.core.UriInfo; +import java.util.List; +import java.util.UUID; +import org.openmetadata.schema.api.data.CreateOntologyShape; +import org.openmetadata.schema.api.data.ImportOntologyShapes; +import org.openmetadata.schema.api.data.OntologyShapeImportAction; +import org.openmetadata.schema.api.data.OntologyShapeImportResult; +import org.openmetadata.schema.api.data.OntologyShapeImported; +import org.openmetadata.schema.api.data.RestoreEntity; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.EntityHistory; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.utils.ResultList; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.ListFilter; +import org.openmetadata.service.jdbi3.OntologyRepository; +import org.openmetadata.service.jdbi3.OntologyShapeRepository; +import org.openmetadata.service.limits.Limits; +import org.openmetadata.service.ontology.OntologyShapeRules; +import org.openmetadata.service.rdf.OntologyShaclReader; +import org.openmetadata.service.resources.Collection; +import org.openmetadata.service.resources.EntityResource; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.CreateResourceContext; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.util.ValidatorUtil; + +@Path("/v1/ontologyShapes") +@Tag(name = "Ontology Shapes", description = "SHACL node shapes authored in an ontology.") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +@Collection(name = "ontologyShapes", order = 3) +public class OntologyShapeResource extends EntityResource { + public static final String COLLECTION_PATH = "/v1/ontologyShapes/"; + private final OntologyShapeMapper mapper = new OntologyShapeMapper(); + + public OntologyShapeResource(final Authorizer authorizer, final Limits limits) { + super(Entity.ONTOLOGY_SHAPE, authorizer, limits); + } + + public static class OntologyShapeList extends ResultList {} + + @GET + @Operation(operationId = "listOntologyShapes", summary = "List ontology shapes") + public ResultList list( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @QueryParam("fields") final String fields, + @QueryParam("ontologyId") final UUID ontologyId, + @QueryParam("limit") @DefaultValue("50") @Min(0) @Max(1000000) final int limit, + @QueryParam("before") final String before, + @QueryParam("after") final String after, + @QueryParam("include") @DefaultValue("non-deleted") final Include include) { + final ListFilter filter = ontologyFilter(include, ontologyId); + OntologyResourceAccess.requireDraftListRead(authorizer, securityContext, ontologyId); + final ResultList page = + listInternal(uriInfo, securityContext, fields, filter, limit, before, after); + OntologyResourceAccess.requireDraftRowsRead( + authorizer, + securityContext, + ontologyId, + OntologyResourceAccess.ontologyIdsOf(page.getData())); + return page; + } + + private static ListFilter ontologyFilter(final Include include, final UUID ontologyId) { + final ListFilter filter = new ListFilter(include); + if (ontologyId != null) { + filter.addQueryParam("ontologyId", ontologyId.toString()); + } + return filter; + } + + @GET + @Path("/{id}") + @Operation(operationId = "getOntologyShapeById", summary = "Get an ontology shape") + public OntologyShape get( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @QueryParam("fields") final String fields, + @QueryParam("include") @DefaultValue("non-deleted") final Include include) { + return getInternal(uriInfo, securityContext, id, fields, include, null); + } + + @GET + @Path("/name/{fqn}") + @Operation(operationId = "getOntologyShapeByName", summary = "Get an ontology shape by name") + public OntologyShape getByName( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("fqn") final String fqn, + @QueryParam("fields") final String fields, + @QueryParam("include") @DefaultValue("non-deleted") final Include include) { + return getByNameInternal(uriInfo, securityContext, fqn, fields, include, null); + } + + @POST + @Operation(operationId = "createOntologyShape", summary = "Create an ontology shape") + public Response create( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @Valid final CreateOntologyShape request) { + final OntologyShape entity = mapper.createToEntity(request, user(securityContext)); + return OntologyResourceAccess.createOrRecreate( + repository, + entity, + () -> create(uriInfo, securityContext, entity), + () -> createOrUpdate(uriInfo, securityContext, entity)); + } + + @POST + @Path("/import") + @Operation( + operationId = "importOntologyShapes", + summary = "Import SHACL node shapes into an ontology's working draft", + description = + "Reads a Turtle document and creates or updates one shape per sh:NodeShape that has a single sh:targetClass, keyed by name, with the supported constraints of its sh:property nodes. Every other SHACL construct is left out and named in the result; that is a report, not an error. A file holds at most 1,000 shapes, 100,000 statements and 10 MiB, and parses within 30 seconds. A shape whose name or content violates the entity name or shape rules fails the whole request before anything is written, and the writes run in one transaction, so a failing request leaves the draft as it was. With dryRun nothing is written.") + public OntologyShapeImportResult importShapes( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @Valid final ImportOntologyShapes request) { + final EntityReference ontology = + Entity.getEntityReferenceByName( + Entity.ONTOLOGY, request.getOntology(), Include.NON_DELETED); + authorizer.authorize( + securityContext, + new OperationContext(entityType, MetadataOperation.CREATE), + new CreateResourceContext<>(entityType, new OntologyShape().withOntology(ontology))); + final OntologyShaclReader.Parsed parsed = OntologyShaclReader.read(request.getContent()); + final List shapes = + parsed.shapes().stream() + .map(shape -> toEntity(request.getOntology(), shape, user(securityContext))) + .toList(); + shapes.forEach(OntologyShapeRules::requireValid); + final boolean dryRun = Boolean.TRUE.equals(request.getDryRun()); + return new OntologyShapeImportResult() + .withDryRun(dryRun) + .withShapes(dryRun ? planned(shapes) : write(uriInfo, securityContext, ontology, shapes)) + .withUnsupported(parsed.unsupported()); + } + + /** + * Every write runs in one transaction under the ontology's lock: a shape that fails leaves the + * draft as it was. ADR:2026-11-21-ontology-shapes-hold-the-supported-shacl-constraints + */ + private List write( + final UriInfo uriInfo, + final SecurityContext securityContext, + final EntityReference ontology, + final List shapes) { + final OntologyRepository ontologies = + (OntologyRepository) Entity.getEntityRepository(Entity.ONTOLOGY); + return ontologies.writeWorkingDraft( + ontology.getId(), + () -> shapes.stream().map(shape -> write(uriInfo, securityContext, shape)).toList()); + } + + private List planned(final List shapes) { + return shapes.stream().map(this::planned).toList(); + } + + private OntologyShape toEntity( + final String ontology, final OntologyShaclReader.ParsedShape shape, final String user) { + final CreateOntologyShape request = + new CreateOntologyShape() + .withName(shape.name()) + .withDisplayName(shape.displayName()) + .withDescription(shape.description()) + .withOntology(ontology) + .withTargetConcept(shape.targetConcept()) + .withSeverity(shape.severity()) + .withConstraints(shape.constraints()); + final String invalid = ValidatorUtil.validate(request); + if (invalid != null) { + throw new BadRequestException( + "The shape '" + abbreviated(shape.name()) + "' cannot be imported: " + invalid); + } + return mapper.createToEntity(request, user); + } + + private static String abbreviated(final String name) { + return name.length() > 64 ? name.substring(0, 64) + "..." : name; + } + + private OntologyShapeImported planned(final OntologyShape shape) { + repository.setFullyQualifiedName(shape); + final boolean exists = + repository.findByNameOrNull(shape.getFullyQualifiedName(), Include.NON_DELETED) != null; + return imported( + shape, exists ? OntologyShapeImportAction.UPDATED : OntologyShapeImportAction.CREATED); + } + + private OntologyShapeImported write( + final UriInfo uriInfo, final SecurityContext securityContext, final OntologyShape shape) { + final Response response = createOrUpdate(uriInfo, securityContext, shape); + return imported( + shape, + response.getStatus() == Response.Status.CREATED.getStatusCode() + ? OntologyShapeImportAction.CREATED + : OntologyShapeImportAction.UPDATED); + } + + private static OntologyShapeImported imported( + final OntologyShape shape, final OntologyShapeImportAction action) { + return new OntologyShapeImported() + .withName(shape.getName()) + .withAction(action) + .withConstraintIds( + shape.getConstraints().stream().map(OntologyShapeConstraint::getId).toList()); + } + + @PUT + @Operation(operationId = "createOrUpdateOntologyShape", summary = "Create or update a shape") + public Response createOrUpdate( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @Valid final CreateOntologyShape request) { + final OntologyShape entity = mapper.createToEntity(request, user(securityContext)); + return createOrUpdate(uriInfo, securityContext, entity); + } + + @PATCH + @Path("/{id}") + @Consumes(MediaType.APPLICATION_JSON_PATCH_JSON) + @Operation(operationId = "patchOntologyShape", summary = "Patch an ontology shape") + public Response patch( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + final JsonPatch patch) { + OntologyResourceAccess.requireEditForContentPatch( + authorizer, securityContext, Entity.ONTOLOGY_SHAPE, id, patch); + return patchInternal(uriInfo, securityContext, id, patch); + } + + @GET + @Path("/{id}/versions") + @Operation(operationId = "listOntologyShapeVersions", summary = "List shape versions") + public EntityHistory listVersions( + @Context final SecurityContext securityContext, @PathParam("id") final UUID id) { + return listVersionsInternal(securityContext, id); + } + + @GET + @Path("/{id}/versions/{version}") + @Operation(operationId = "getOntologyShapeVersion", summary = "Get a shape version") + public OntologyShape getVersion( + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @PathParam("version") final String version) { + return getVersionInternal(securityContext, id, version); + } + + @DELETE + @Path("/{id}") + @Operation(operationId = "deleteOntologyShape", summary = "Delete an ontology shape") + public Response delete( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @PathParam("id") final UUID id, + @QueryParam("hardDelete") @DefaultValue("false") final boolean hardDelete) { + return delete(uriInfo, securityContext, id, false, hardDelete); + } + + @PUT + @Path("/restore") + @Operation(operationId = "restoreOntologyShape", summary = "Restore an ontology shape") + public Response restore( + @Context final UriInfo uriInfo, + @Context final SecurityContext securityContext, + @Valid final RestoreEntity restore) { + return OntologyResourceAccess.restoreOrKeepLive( + authorizer, + securityContext, + repository, + restore.getId(), + () -> restoreEntity(uriInfo, securityContext, restore.getId())); + } + + private static String user(final SecurityContext securityContext) { + return securityContext.getUserPrincipal().getName(); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfResource.java index da97c0256028..a71538db74af 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfResource.java @@ -1019,6 +1019,11 @@ public Response getEntityAsRdf( @Parameter(description = "Entity id", required = true) @PathParam("id") UUID id, @Parameter(description = "RDF format") @QueryParam("format") @DefaultValue("jsonld") String format) { + if (Entity.ONTOLOGY_CHANGE_SET.equals(entityType)) { + // A change set is a draft read with the draft read right, and its evidence is masked per + // reader. + throw new AuthorizationException("A change set has no RDF view"); + } authorizer.authorize( securityContext, new OperationContext(entityType, MetadataOperation.VIEW_ALL), diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java index 8fc0fd748490..ccf28aae4189 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/tasks/TaskResource.java @@ -78,6 +78,7 @@ import org.openmetadata.schema.type.EventType; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.SuggestionPayload; import org.openmetadata.schema.type.TaskAvailableTransition; import org.openmetadata.schema.type.TaskCategory; import org.openmetadata.schema.type.TaskComment; @@ -115,6 +116,7 @@ import org.openmetadata.service.security.policyevaluator.SubjectContext; import org.openmetadata.service.security.policyevaluator.TaskResourceContext; import org.openmetadata.service.tasks.IncidentWorkflowStages; +import org.openmetadata.service.tasks.TableConstraintSuggestion; import org.openmetadata.service.tasks.TaskWorkflowLifecycleResolver; import org.openmetadata.service.util.EntityUtil; import org.openmetadata.service.util.EntityUtil.Fields; @@ -278,6 +280,12 @@ public ResultList list( @Parameter(description = "Filter by user FQN who was mentioned in task comments") @QueryParam("mentionedUser") String mentionedUser, + @Parameter( + description = + "Comma-separated suggestion types, for example Description,Tag; matches Suggestion tasks" + + " whose payload carries one of them") + @QueryParam("suggestionType") + String suggestionType, @Parameter(description = TASK_SEARCH_DESCRIPTION) @QueryParam("q") String q, @Parameter(description = "Limit the number results", schema = @Schema(type = "integer")) @DefaultValue("10") @@ -370,6 +378,11 @@ public ResultList list( if (mentionedUser != null) { filter.addQueryParam("mentionedUser", mentionedUser); } + if (suggestionType != null) { + validateCsvAgainstEnum( + "suggestionType", suggestionType, SuggestionPayload.SuggestionType.class); + filter.addQueryParam("suggestionType", suggestionType); + } applyTaskSearch(filter, q); TaskListOrder.fromParam(sortOrder).applyTo(filter, sortBy); @@ -1430,6 +1443,14 @@ private void validateTaskPatch(Task original, Task patched, boolean callerIsAdmi rejectPayloadOrAboutEditAfterOpen(original, patched); rejectServerOpenedTaskEdit(original, patched); rejectWorkflowBindingEdits(original, patched); + rejectUndeclaredConstraintKeys(original, patched); + } + + /** A table constraint suggestion's payload holds only the keys the suggestion payload declares. */ + private static void rejectUndeclaredConstraintKeys(Task original, Task patched) { + if (!Objects.equals(original.getPayload(), patched.getPayload())) { + TableConstraintSuggestion.requireDeclaredKeys(patched); + } } /** The type and category of a task decide which resolve rules apply to it. */ @@ -2153,13 +2174,14 @@ private void updateTaskInBulk(UriInfo uriInfo, Task task, String userName) { /** * Per-token validation for a comma-separated enum query param. Surfaces a 400 if any token - * isn't a recognized {@link Enum} value, so callers see a clear error instead of an opaque + * isn't a recognized {@link Enum} value in the form the API takes (the enum's {@code toString()}, + * which is the schema value for generated enums), so callers see a clear error instead of an opaque * empty result set or a downstream SQL surprise. */ private > void validateCsvAgainstEnum( String paramName, String csv, Class enumClass) { Set allowed = - Arrays.stream(enumClass.getEnumConstants()).map(Enum::name).collect(Collectors.toSet()); + Arrays.stream(enumClass.getEnumConstants()).map(Enum::toString).collect(Collectors.toSet()); Arrays.stream(csv.split(",")) .map(String::trim) .filter(s -> !s.isEmpty()) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/DefaultAuthorizer.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/DefaultAuthorizer.java index 16aae0d53316..1b4ac74fb7dd 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/DefaultAuthorizer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/DefaultAuthorizer.java @@ -358,6 +358,7 @@ private SubjectContext changeSubjectContext(String user, SubjectContext loggedIn Entity.ONTOLOGY_PROPERTY, Entity.ONTOLOGY_RELEASE, Entity.ONTOLOGY_AXIOM, + Entity.ONTOLOGY_SHAPE, Entity.ONTOLOGY_CHANGE_SET); private boolean requiresEditRight(String resource) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/ViewPermissionFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/ViewPermissionFilter.java index 3b3e377246ca..ce94ec52722c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/ViewPermissionFilter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/ViewPermissionFilter.java @@ -58,6 +58,14 @@ public Set viewableIds(SecurityContext securityContext, List viewableIds( + SecurityContext securityContext, + MetadataOperation operation, + List references) { + return viewableIds(requestCheck(securityContext, operation), references); + } + /** * Ids of the {@code references} {@code userName} may perform {@code operation} on, for work that * runs without the request's security context (e.g. an asynchronous export). Never throws. diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/mask/PIIMasker.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/mask/PIIMasker.java index fa2ef4cb23ce..9e45e4f64ec3 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/mask/PIIMasker.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/mask/PIIMasker.java @@ -360,6 +360,15 @@ private static String columnPathOf(String[] parts) { .collect(Collectors.joining(Entity.SEPARATOR)); } + /** + * Whether the sample data and profile of the last column of {@code columnPath}, a path from a + * top-level column of {@code table} down to the column, are masked: the table, the column or a + * column above it carries the sensitive tag. + */ + public static boolean isColumnMasked(Table table, List columnPath) { + return hasPiiSensitiveTag(table) || hasPiiSensitiveTagInPath(columnPath); + } + private static boolean hasPiiSensitiveTagInPath(List columnPath) { // The leaf's tag set covers itself and its descendants (getAllTags); ancestors only their own. if (hasPiiSensitiveTag(columnPath.getLast())) { @@ -565,7 +574,9 @@ private static boolean hasPiiSensitiveTag(Column column) { } private static boolean hasPiiSensitiveTag(Table table) { - return table.getTags().stream().map(TagLabel::getTagFQN).anyMatch(SENSITIVE_PII_TAG::equals); + return listOrEmpty(table.getTags()).stream() + .map(TagLabel::getTagFQN) + .anyMatch(SENSITIVE_PII_TAG::equals); } private static boolean hasPiiSensitiveTag(Container container) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java new file mode 100644 index 000000000000..1ef61b1cc266 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TableConstraintSuggestion.java @@ -0,0 +1,398 @@ +/* + * 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.tasks; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.SuggestionPayload; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TableConstraint.ConstraintType; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.TableRepository; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * A suggestion task of type {@code TableConstraint} proposes one primary key, unique or foreign key + * constraint for the table it is about. Its {@code suggestedValue} is that {@link TableConstraint} + * written as JSON, and its field path is {@code tableConstraints}. + * + *

    A task is refused when it is filed, and again when it is approved with the resolver's payload + * laid over it, unless it names a table, a supported constraint type, columns of that table and, for + * a foreign key, referred columns of existing tables. Approving also refuses a second primary key + * (ADR:2026-11-26-a-suggestion-task-can-carry-a-table-constraint). A resolution cannot change a + * task's suggestion type to or from {@code TableConstraint}. + * + *

    Apart from a key that a configured workflow writes, which makes approving the task refused, its + * payload holds only the keys that {@link SuggestionPayload} declares, so no other key can decide + * what approving the task needs or does. + */ +public final class TableConstraintSuggestion { + public static final String TYPE = "TableConstraint"; + public static final String FIELD_PATH = "tableConstraints"; + private static final String SUGGESTION_TYPE = "suggestionType"; + private static final String TABLE_FIELDS = "columns,tableConstraints"; + private static final Set SUPPORTED = + EnumSet.of(ConstraintType.PRIMARY_KEY, ConstraintType.UNIQUE, ConstraintType.FOREIGN_KEY); + + private static final Set DECLARED_KEYS = declaredKeys(); + + private TableConstraintSuggestion() {} + + /** The property names of the generated {@link SuggestionPayload}, which follow its schema. */ + private static Set declaredKeys() { + var mapper = JsonUtils.getObjectMapper(); + return mapper + .getSerializationConfig() + .introspect(mapper.constructType(SuggestionPayload.class)) + .findProperties() + .stream() + .map(BeanPropertyDefinition::getName) + .collect(Collectors.toCollection(TreeSet::new)); + } + + /** + * Refuses a payload that has a top-level key {@link SuggestionPayload} does not declare. Keys are + * compared exactly, so {@code SuggestedValue} is not {@code suggestedValue}. + */ + public static void requireDeclaredKeys(JsonNode payload) { + requireDeclaredKeys(payload, "A table constraint suggestion"); + } + + /** The same refusal for a suggestion type that names itself in the message. */ + static void requireDeclaredKeys(JsonNode payload, String subject) { + Set undeclared = new TreeSet<>(); + payload + .fieldNames() + .forEachRemaining( + key -> { + if (!DECLARED_KEYS.contains(key)) { + undeclared.add(key); + } + }); + if (!undeclared.isEmpty()) { + throw BadRequestException.of( + "%s carries only the keys of the suggestion payload (%s); not allowed: %s" + .formatted(subject, String.join(", ", DECLARED_KEYS), String.join(", ", undeclared))); + } + } + + /** Refuses a payload of a table constraint suggestion that has a key the schema does not declare. */ + public static void requireDeclaredKeys(Task task) { + if (isKeyRestricted(task)) { + requireDeclaredKeys(JsonUtils.valueToTree(task.getPayload()), subjectOf(task)); + } + } + + /** A suggestion type whose payload holds only the declared keys and keeps its type. */ + static boolean isKeyRestricted(Task task) { + return isTableConstraint(task) || TestCaseSuggestion.isTestCase(task); + } + + private static boolean isRestricted(String suggestionType) { + return TYPE.equals(suggestionType) || TestCaseSuggestion.TYPE.equals(suggestionType); + } + + private static String subjectOf(Task task) { + return TestCaseSuggestion.isTestCase(task) + ? "A test case suggestion" + : "A table constraint suggestion"; + } + + /** + * Refuses a resolution that would write a key the suggestion payload does not declare into a + * table constraint suggestion, whatever the resolution is: a key of the request's payload, or the + * form's value field when the request carries a new value. A key the task already stores is not + * the resolution's, so it does not refuse a resolution that adds no key. + */ + public static void requireNoNewKeys(Task task, Object requestPayload, String newValue) { + if (!isKeyRestricted(task)) { + return; + } + ObjectNode added = JsonUtils.getObjectNode(); + if (requestPayload != null) { + JsonUtils.valueToTree(requestPayload) + .fields() + .forEachRemaining(e -> added.set(e.getKey(), e.getValue())); + } + String valueField = TaskFormExecutionResolver.resolve(task).valueField(); + if (newValue != null && valueField != null) { + added.put(valueField, newValue); + } + requireDeclaredKeys(added, subjectOf(task)); + } + + public static boolean isTableConstraint(Task task) { + return task != null + && task.getType() == TaskEntityType.Suggestion + && TYPE.equals(suggestionTypeOf(task.getPayload())); + } + + private static String suggestionTypeOf(Object payload) { + return payload == null ? "" : JsonUtils.valueToTree(payload).path(SUGGESTION_TYPE).asText(""); + } + + /** + * Refuses a resolution whose payload changes the task's suggestion type to or from {@code + * TableConstraint}. Approving is authorized for the task's current type, so a changed type would + * write a table constraint on the right to edit a description. + */ + public static void requireSameSuggestionType(Task task, Object requestPayload) { + if (task == null || task.getType() != TaskEntityType.Suggestion || requestPayload == null) { + return; + } + String stored = suggestionTypeOf(task.getPayload()); + String requested = suggestionTypeOf(requestPayload); + boolean changed = !requested.isEmpty() && !requested.equals(stored); + if (changed && (isRestricted(stored) || isRestricted(requested))) { + throw BadRequestException.of( + "A resolution cannot change the suggestion type of a task to or from %s: the task is '%s', the resolution says '%s'" + .formatted(isRestricted(stored) ? stored : requested, stored, requested)); + } + } + + /** Refuses filing a table constraint suggestion that names no valid constraint of its table. */ + public static void require(Task task) { + if (isTableConstraint(task)) { + requireDeclaredKeys(task); + validate(task, JsonUtils.valueToTree(task.getPayload())); + } + } + + /** + * Refuses approving a table constraint suggestion, with the resolver's payload laid over the + * task's, when it is no longer valid or when the table already has another primary key. + */ + public static void requireToApply(Task task, Object requestPayload, String newValue) { + if (isTableConstraint(task)) { + JsonNode merged = + JsonUtils.valueToTree( + TaskWorkflowHandler.mergeResolutionPayload(task, requestPayload, newValue)); + requireDeclaredKeys(merged); + Table table = loadTable(task); + TableConstraint constraint = validate(task, merged, table); + toAdd(table, constraint) + .ifPresent( + added -> + tableRepository() + .validateTableConstraints(tableWith(table, added), Collections.emptySet())); + } + } + + /** + * The constraint to add to the table: empty when an equal constraint, of the same type, columns + * and referred columns, is already there. + * + * @throws BadRequestException for a primary key when the table has a different one + */ + public static Optional toAdd(Table table, TableConstraint constraint) { + List existing = listOrEmpty(table.getTableConstraints()); + if (existing.stream().anyMatch(present -> sameConstraint(present, constraint))) { + return Optional.empty(); + } + if (constraint.getConstraintType() == ConstraintType.PRIMARY_KEY) { + existing.stream() + .filter(present -> present.getConstraintType() == ConstraintType.PRIMARY_KEY) + .findFirst() + .ifPresent( + present -> { + throw BadRequestException.of( + "Table '%s' already has a primary key on columns %s; a table has one primary key" + .formatted(table.getFullyQualifiedName(), present.getColumns())); + }); + } + return Optional.of(constraint); + } + + private static TableRepository tableRepository() { + return (TableRepository) Entity.getEntityRepository(Entity.TABLE); + } + + /** What the table repository validates on a write: the table's constraints with one added. */ + private static Table tableWith(Table table, TableConstraint added) { + return new Table() + .withName(table.getName()) + .withFullyQualifiedName(table.getFullyQualifiedName()) + .withColumns(table.getColumns()) + .withTableConstraints(withConstraint(table, added)); + } + + /** The table's constraints with {@code constraint} added. */ + public static List withConstraint(Table table, TableConstraint constraint) { + List constraints = new ArrayList<>(listOrEmpty(table.getTableConstraints())); + constraints.add(constraint); + return constraints; + } + + /** + * The comment an approval leaves: the constraint the resolution adds, from the task's payload + * with the resolution's laid over it, or the equal constraint the table already has. A new value + * is not named, because it never changes the constraint. + */ + public static String resolutionComment(Task task, Object requestPayload, String newValue) { + JsonNode merged = + JsonUtils.valueToTree( + TaskWorkflowHandler.mergeResolutionPayload(task, requestPayload, newValue)); + TableConstraint constraint = constraintOf(merged); + boolean added = toAdd(loadTable(task), constraint).isPresent(); + String prefix = added ? "Added table constraint" : "Table already has constraint"; + return "%s: %s".formatted(prefix, describe(constraint)); + } + + private static String describe(TableConstraint constraint) { + String description = + "%s on %s".formatted(constraint.getConstraintType(), listOrEmpty(constraint.getColumns())); + List referred = listOrEmpty(constraint.getReferredColumns()); + return referred.isEmpty() ? description : "%s referring to %s".formatted(description, referred); + } + + /** The constraint a task's {@code suggestedValue} carries. */ + public static TableConstraint constraintOf(JsonNode payload) { + String suggestedValue = payload.path("suggestedValue").asText(""); + try { + TableConstraint constraint = JsonUtils.readValue(suggestedValue, TableConstraint.class); + if (constraint == null || constraint.getConstraintType() == null) { + throw BadRequestException.of( + "Suggested value is not a table constraint: it has no constraintType"); + } + return constraint; + } catch (BadRequestException e) { + throw e; + } catch (RuntimeException e) { + throw BadRequestException.of( + "Suggested value is not a table constraint: %s".formatted(suggestedValue)); + } + } + + private static void validate(Task task, JsonNode payload) { + validate(task, payload, loadTable(task)); + } + + private static TableConstraint validate(Task task, JsonNode payload, Table table) { + String fieldPath = payload.path(TaskFieldTarget.FIELD_PATH).asText(null); + if (!FIELD_PATH.equals(fieldPath)) { + throw BadRequestException.of( + "Field path of a table constraint suggestion must be '%s', not '%s'" + .formatted(FIELD_PATH, fieldPath)); + } + TableConstraint constraint = constraintOf(payload); + if (!SUPPORTED.contains(constraint.getConstraintType())) { + throw BadRequestException.of( + "Table constraint type %s cannot be suggested; use PRIMARY_KEY, UNIQUE or FOREIGN_KEY" + .formatted(constraint.getConstraintType())); + } + requireColumns(table, constraint); + requireReferredColumns(constraint); + return constraint; + } + + private static Table loadTable(Task task) { + if (task.getAbout() == null || !Entity.TABLE.equals(task.getAbout().getType())) { + throw BadRequestException.of( + "A table constraint suggestion must be about a table, not %s" + .formatted(task.getAbout() == null ? "nothing" : task.getAbout().getType())); + } + return Entity.getEntity(task.getAbout(), TABLE_FIELDS, Include.NON_DELETED); + } + + private static void requireColumns(Table table, TableConstraint constraint) { + if (nullOrEmpty(constraint.getColumns())) { + throw BadRequestException.of("A table constraint needs at least one column"); + } + for (String name : constraint.getColumns()) { + if (!hasColumn(table, name)) { + throw BadRequestException.of( + "Column '%s' is not a column of table '%s'" + .formatted(name, table.getFullyQualifiedName())); + } + } + } + + private static void requireReferredColumns(TableConstraint constraint) { + List referred = listOrEmpty(constraint.getReferredColumns()); + if (constraint.getConstraintType() != ConstraintType.FOREIGN_KEY) { + if (!referred.isEmpty()) { + throw BadRequestException.of( + "Only a foreign key has referredColumns, not %s" + .formatted(constraint.getConstraintType())); + } + return; + } + if (referred.size() != constraint.getColumns().size()) { + throw BadRequestException.of( + "A foreign key needs one referred column for each of its %d columns, not %d" + .formatted(constraint.getColumns().size(), referred.size())); + } + referred.forEach(TableConstraintSuggestion::requireReferredColumn); + } + + private static void requireReferredColumn(String columnFqn) { + Table referredTable; + String columnName; + try { + referredTable = + Entity.getEntityByName( + Entity.TABLE, + FullyQualifiedName.getTableFQN(columnFqn), + "columns", + Include.NON_DELETED); + columnName = FullyQualifiedName.getColumnName(columnFqn); + } catch (EntityNotFoundException | IllegalArgumentException e) { + throw unresolved(columnFqn); + } + if (!hasColumn(referredTable, columnName)) { + throw unresolved(columnFqn); + } + } + + private static BadRequestException unresolved(String columnFqn) { + return BadRequestException.of( + "Referred column '%s' does not resolve to a column of an existing table" + .formatted(columnFqn)); + } + + private static boolean hasColumn(Table table, String name) { + return listOrEmpty(table.getColumns()).stream() + .filter(Objects::nonNull) + .map(Column::getName) + .anyMatch(name::equals); + } + + private static boolean sameConstraint(TableConstraint present, TableConstraint suggested) { + return present.getConstraintType() == suggested.getConstraintType() + && listOrEmpty(present.getColumns()).equals(listOrEmpty(suggested.getColumns())) + && listOrEmpty(present.getReferredColumns()) + .equals(listOrEmpty(suggested.getReferredColumns())); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java index 9617d11570a3..093a5c29b8c5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TaskWorkflowHandler.java @@ -41,13 +41,17 @@ import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.entity.tasks.Task; import org.openmetadata.schema.governance.workflows.WorkflowDefinition; import org.openmetadata.schema.governance.workflows.elements.EdgeDefinition; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestSuite; import org.openmetadata.schema.type.ChangeEvent; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.EventType; import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.schema.type.TagLabel; import org.openmetadata.schema.type.TaskAvailableTransition; import org.openmetadata.schema.type.TaskComment; @@ -57,6 +61,7 @@ import org.openmetadata.schema.type.TaskResolutionType; import org.openmetadata.schema.type.TaskReviewVote; import org.openmetadata.schema.type.TaskReviewVoteDecision; +import org.openmetadata.schema.type.TestCaseProposal; import org.openmetadata.schema.type.change.ChangeSource; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; @@ -75,8 +80,11 @@ import org.openmetadata.service.governance.workflows.WorkflowHandler; import org.openmetadata.service.governance.workflows.WorkflowHandler.TaskResolutionOutcome; import org.openmetadata.service.governance.workflows.metadata.MetadataCollectionService; +import org.openmetadata.service.jdbi3.DataContractRepository; import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.GeneratedTestScope; import org.openmetadata.service.jdbi3.TaskRepository; +import org.openmetadata.service.jdbi3.TestCaseRepository; import org.openmetadata.service.jdbi3.WorkflowInstanceRepository; import org.openmetadata.service.resources.tags.TagLabelUtil; import org.openmetadata.service.tasks.TaskFormExecutionResolver.TaskExecutionAction; @@ -198,6 +206,12 @@ public Task resolveTask( effectiveResolutionType, user); TaskFieldTarget.requireToApply(task, effectiveResolutionType, resolvedPayload); + TableConstraintSuggestion.requireNoNewKeys(task, resolvedPayload, newValue); + if (isPositiveResolution(effectiveResolutionType)) { + TableConstraintSuggestion.requireSameSuggestionType(task, resolvedPayload); + TableConstraintSuggestion.requireToApply(task, resolvedPayload, newValue); + TestCaseSuggestion.requireToApply(task, resolvedPayload, newValue); + } ReviewOutcome outcome = ApprovalDecisionService.recordForTask(task, effectiveResolutionType, review, comment, user); @@ -635,10 +649,10 @@ private Task applyTaskResolution( : "null", task.getAbout() != null); - // Add audit comment if assignee provided/modified the value - if (approved && newValue != null && !newValue.isEmpty()) { - addResolutionComment(task, taskRepository, newValue, user); - } + // The text is decided on the entity as it is before the change, and posted only after the + // change returns, so a resolution whose change throws leaves no comment on the open task. + Optional commentMessage = + resolutionCommentOrEmpty(task, approved, resolvedPayload, newValue); // A memory conflict review decides on rejection too, and a refused decision must fail the // resolution. Other types mutate the target entity only on positive resolutions. @@ -657,6 +671,8 @@ private Task applyTaskResolution( task.getAbout() != null); } + postResolutionComment(task, taskRepository, commentMessage, user); + EntityReference resolvedByRef = Entity.getEntityReferenceByName(Entity.USER, user, Include.NON_DELETED); @@ -725,37 +741,37 @@ private void persistEditedWorkflowPayload( } } + private Optional resolutionCommentOrEmpty( + Task task, boolean approved, Object resolvedPayload, String newValue) { + try { + return resolutionComment(task, approved, resolvedPayload, newValue); + } catch (Exception e) { + LOG.warn( + "[TaskWorkflowHandler] Failed to build resolution comment for task '{}': {}", + task.getId(), + e.getMessage()); + return Optional.empty(); + } + } + /** - * Add a comment to the task recording what value was applied by whom. - * This creates an audit trail for task resolution. + * Add the resolution's comment to the task as the resolver. The comment holds the text decided + * before the change: the constraint a table constraint approval adds, or that the table already + * has, or the value an approval of another type carries. It is posted after the change returns + * and before the task is resolved, so a change that throws leaves no comment. A comment that + * cannot be written never fails a resolution that was applied. */ - private void addResolutionComment( - Task task, TaskRepository taskRepository, String newValue, String user) { + private void postResolutionComment( + Task task, TaskRepository taskRepository, Optional commentMessage, String user) { try { - // Check if the newValue differs from the original suggestion - Object payload = task.getPayload(); - String originalSuggestion = null; - if (payload != null) { - JsonNode payloadNode = JsonUtils.valueToTree(payload); - originalSuggestion = payloadNode.path("suggestedValue").asText(null); - } - - // Only add comment if user provided a new value (not just accepting suggestion) - boolean userProvidedValue = - originalSuggestion == null - || originalSuggestion.isEmpty() - || !originalSuggestion.equals(newValue); - - if (userProvidedValue) { - String commentMessage = buildResolutionCommentMessage(task.getType(), newValue); - + if (commentMessage.isPresent()) { EntityReference authorRef = Entity.getEntityReferenceByName(Entity.USER, user, Include.NON_DELETED); TaskComment comment = new TaskComment() .withId(UUID.randomUUID()) - .withMessage(commentMessage) + .withMessage(commentMessage.get()) .withAuthor(authorRef) .withCreatedAt(System.currentTimeMillis()); @@ -773,10 +789,44 @@ private void addResolutionComment( } } + /** + * The audit comment of a resolution, when it has one. A table constraint suggestion's approval + * names the constraint it adds, because a new value never changes that constraint. Every other + * task has a comment only when the approver gave a value that differs from the suggestion. + */ + static Optional resolutionComment( + Task task, boolean approved, Object resolvedPayload, String newValue) { + Optional commentMessage = Optional.empty(); + if (approved && TableConstraintSuggestion.isTableConstraint(task)) { + commentMessage = + Optional.of(TableConstraintSuggestion.resolutionComment(task, resolvedPayload, newValue)); + } else if (approved && TestCaseSuggestion.isTestCase(task)) { + commentMessage = + Optional.of(TestCaseSuggestion.resolutionComment(task, resolvedPayload, newValue)); + } else if (approved && newValue != null && !newValue.isEmpty()) { + commentMessage = + providesNewValue(task, newValue) + ? Optional.of(buildResolutionCommentMessage(task.getType(), newValue)) + : Optional.empty(); + } + return commentMessage; + } + + private static boolean providesNewValue(Task task, String newValue) { + String originalSuggestion = null; + if (task.getPayload() != null) { + originalSuggestion = + JsonUtils.valueToTree(task.getPayload()).path("suggestedValue").asText(null); + } + return originalSuggestion == null + || originalSuggestion.isEmpty() + || !originalSuggestion.equals(newValue); + } + /** * Build a comment message based on task type and the applied value. */ - private String buildResolutionCommentMessage(TaskEntityType taskType, String newValue) { + private static String buildResolutionCommentMessage(TaskEntityType taskType, String newValue) { String truncatedValue = newValue.length() > 200 ? newValue.substring(0, 200) + "..." : newValue; return switch (taskType) { @@ -824,6 +874,15 @@ private void applyEntityChanges( EntityInterface entity = Entity.getEntity(aboutRef, "*", Include.ALL); EntityRepository repository = Entity.getEntityRepository(aboutRef.getType()); + // No task form changes what approving a table constraint does: it adds the constraint and + // nothing else, and rejecting it writes nothing, whatever handler and actions the form names. + if (TableConstraintSuggestion.isKeyRestricted(task)) { + if (approved) { + applySuggestion(task, effectivePayload, entity, repository, user); + } + return; + } + List actions = approved ? executionPlan.approveActions() : executionPlan.rejectActions(); if (actions == null || actions.isEmpty()) { @@ -840,6 +899,10 @@ private void applyEntityChanges( } catch (Exception e) { LOG.error( "[TaskWorkflowHandler] Failed to apply entity changes for task '{}'", task.getId(), e); + if (TableConstraintSuggestion.isKeyRestricted(task)) { + // The task stays open: approving it must not report a constraint that was not added. + throw e; + } } } @@ -1377,14 +1440,79 @@ private void applySuggestion( tags.size(), entity.getName()); } + } else if (TableConstraintSuggestion.isTableConstraint(task) + && TableConstraintSuggestion.TYPE.equals(suggestionType)) { + applyTableConstraint(payloadNode, entity, repository, user); + } else if (TestCaseSuggestion.isTestCase(task) + && TestCaseSuggestion.TYPE.equals(suggestionType)) { + applyTestCase(payloadNode, (Table) entity, user); } else { LOG.debug("[TaskWorkflowHandler] Unknown suggestion type: {}", suggestionType); } } catch (Exception e) { LOG.error("[TaskWorkflowHandler] Failed to apply Suggestion", e); + if (TableConstraintSuggestion.isKeyRestricted(task)) { + throw e; + } } } + /** + * Adds the suggested constraint to the table as the approver, through the table repository's own + * validation. An equal constraint already on the table is left as it is. + */ + private void applyTableConstraint( + JsonNode payloadNode, + EntityInterface entity, + EntityRepository repository, + String user) { + Table table = (Table) entity; + TableConstraint constraint = TableConstraintSuggestion.constraintOf(payloadNode); + Optional toAdd = TableConstraintSuggestion.toAdd(table, constraint); + if (toAdd.isEmpty()) { + LOG.info( + "[TaskWorkflowHandler] Table '{}' already has the suggested {} constraint", + table.getFullyQualifiedName(), + constraint.getConstraintType()); + return; + } + String before = JsonUtils.pojoToJson(table); + table.setTableConstraints(TableConstraintSuggestion.withConstraint(table, toAdd.get())); + saveChange(table, repository, user, before, null); + LOG.info( + "[TaskWorkflowHandler] Applied {} constraint suggestion to table '{}'", + constraint.getConstraintType(), + table.getFullyQualifiedName()); + } + + /** + * Creates the proposed test case as the approver, in the basic test suite of its table. A test + * the table has already is left as it is. The suite gets a pipeline that runs daily at midnight + * when it has none. + */ + private void applyTestCase(JsonNode payloadNode, Table table, String user) { + TestCaseProposal proposal = TestCaseSuggestion.proposalOf(payloadNode); + if (TestCaseSuggestion.exists(table, proposal.getTestCase())) { + LOG.info( + "[TaskWorkflowHandler] Table '{}' already has the suggested test case", + table.getFullyQualifiedName()); + return; + } + TestCaseRepository tests = (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + TestCase created; + try (GeneratedTestScope.Handle ignored = GeneratedTestScope.enter()) { + created = tests.create(null, TestCaseSuggestion.testCaseOf(proposal, user)); + } + TestSuite suite = Entity.getEntity(created.getTestSuite(), "*", Include.NON_DELETED); + DataContractRepository contracts = + (DataContractRepository) Entity.getEntityRepository(Entity.DATA_CONTRACT); + contracts.ensureScheduledPipeline(suite, TestCaseSuggestion.DAILY_AT_MIDNIGHT); + LOG.info( + "[TaskWorkflowHandler] Created test case '{}' on table '{}'", + created.getName(), + table.getFullyQualifiedName()); + } + private void applyEntityLevelTags( EntityInterface entity, EntityRepository repository, String user, List tags) { String before = JsonUtils.pojoToJson(entity); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TestCaseSuggestion.java b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TestCaseSuggestion.java new file mode 100644 index 000000000000..c916bb71fadf --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/tasks/TestCaseSuggestion.java @@ -0,0 +1,263 @@ +/* + * 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.tasks; + +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import org.apache.commons.codec.digest.DigestUtils; +import org.openmetadata.schema.api.tests.CreateTestCase; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestCaseGeneratedBy; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.type.TestCaseProposal; +import org.openmetadata.schema.utils.EntityInterfaceUtil; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.resources.feeds.MessageParser.EntityLink; +import org.openmetadata.service.util.FullyQualifiedName; + +/** + * A suggestion task of type {@code TestCase} proposes one test case for the table it is about. Its + * {@code suggestedValue} is a {@link TestCaseProposal} written as JSON, and its field path is + * {@code testCases}. Approving it creates the test case, and rejecting it creates nothing + * (ADR:2026-12-01-a-shape-check-reaches-its-table-as-a-proposed-test). + * + *

    A proposal is refused when it is filed, and again when it is approved with the resolver's + * payload laid over it, unless it is the test {@code tableCustomSQLQuery} on the table the task is + * about, with the four parameters a shape check has and a content digest that matches them. Like a + * table constraint suggestion, its payload holds only the keys that the suggestion payload + * declares. + */ +public final class TestCaseSuggestion { + public static final String TYPE = "TestCase"; + public static final String FIELD_PATH = "testCases"; + public static final String DAILY_AT_MIDNIGHT = "0 0 * * *"; + public static final String CUSTOM_SQL = "tableCustomSQLQuery"; + public static final String SQL_EXPRESSION = "sqlExpression"; + public static final String STRATEGY = "strategy"; + public static final String OPERATOR = "operator"; + public static final String THRESHOLD = "threshold"; + private static final List PARAMETERS = + List.of(SQL_EXPRESSION, STRATEGY, OPERATOR, THRESHOLD); + private static final String SUGGESTION_TYPE = "suggestionType"; + private static final ObjectMapper CANONICAL = + new ObjectMapper().configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); + + private TestCaseSuggestion() {} + + public static boolean isTestCase(Task task) { + return task != null + && task.getType() == TaskEntityType.Suggestion + && TYPE.equals( + task.getPayload() == null + ? "" + : JsonUtils.valueToTree(task.getPayload()).path(SUGGESTION_TYPE).asText("")); + } + + /** + * Lowercase hex SHA-256 of the canonical JSON of the test definition, the entity link and the + * parameter values. The keys are sorted and the parameters keep their order. + */ + public static String digest( + String testDefinition, String entityLink, List parameters) { + Map content = new TreeMap<>(); + content.put("testDefinition", testDefinition); + content.put("entityLink", entityLink); + List> values = new ArrayList<>(); + for (TestCaseParameterValue parameter : listOrEmpty(parameters)) { + Map value = new TreeMap<>(); + value.put("name", parameter.getName()); + value.put("value", parameter.getValue()); + values.add(value); + } + content.put("parameterValues", values); + try { + return DigestUtils.sha256Hex(CANONICAL.writeValueAsString(content)); + } catch (JsonProcessingException e) { + throw new IllegalStateException("A test case digest is always serializable", e); + } + } + + /** The proposal a task's {@code suggestedValue} carries. */ + public static TestCaseProposal proposalOf(JsonNode payload) { + String suggestedValue = payload.path("suggestedValue").asText(""); + try { + TestCaseProposal proposal = JsonUtils.readValue(suggestedValue, TestCaseProposal.class); + if (proposal == null || proposal.getTestCase() == null) { + throw BadRequestException.of("Suggested value is not a test case proposal: no testCase"); + } + return proposal; + } catch (BadRequestException e) { + throw e; + } catch (RuntimeException e) { + throw BadRequestException.of("Suggested value is not a test case proposal"); + } + } + + /** Refuses filing a test case suggestion that is not a valid proposal for its table. */ + public static void require(Task task) { + if (isTestCase(task)) { + TableConstraintSuggestion.requireDeclaredKeys(task); + validate(task, JsonUtils.valueToTree(task.getPayload())); + } + } + + /** Refuses approving a suggestion that, with the resolver's payload laid over it, is not valid. */ + public static void requireToApply(Task task, Object requestPayload, String newValue) { + if (isTestCase(task)) { + JsonNode merged = + JsonUtils.valueToTree( + TaskWorkflowHandler.mergeResolutionPayload(task, requestPayload, newValue)); + TableConstraintSuggestion.requireDeclaredKeys(merged, "A test case suggestion"); + validate(task, merged); + } + } + + /** + * The comment an approval leaves: the test case it creates and its table, or the test case the + * table already has. A new value is not named, because it never changes the test. + */ + public static String resolutionComment(Task task, Object requestPayload, String newValue) { + JsonNode merged = + JsonUtils.valueToTree( + TaskWorkflowHandler.mergeResolutionPayload(task, requestPayload, newValue)); + CreateTestCase create = proposalOf(merged).getTestCase(); + Table table = loadTable(task); + String prefix = exists(table, create) ? "Test case already exists" : "Created test case"; + return "%s %s on table %s".formatted(prefix, create.getName(), table.getFullyQualifiedName()); + } + + /** True when a test case of that name is on the table already, deleted or not. */ + public static boolean exists(Table table, CreateTestCase create) { + String fqn = + FullyQualifiedName.add( + table.getFullyQualifiedName(), EntityInterfaceUtil.quoteName(create.getName())); + try { + Entity.getEntityByName(Entity.TEST_CASE, fqn, "", Include.ALL); + return true; + } catch (EntityNotFoundException e) { + return false; + } + } + + /** The table a task is about, which a test case suggestion must name. */ + public static Table loadTable(Task task) { + if (task.getAbout() == null || !Entity.TABLE.equals(task.getAbout().getType())) { + throw BadRequestException.of( + "A test case suggestion must be about a table, not %s" + .formatted(task.getAbout() == null ? "nothing" : task.getAbout().getType())); + } + return Entity.getEntity(task.getAbout(), "", Include.NON_DELETED); + } + + private static void validate(Task task, JsonNode payload) { + String fieldPath = payload.path("fieldPath").asText(null); + if (!FIELD_PATH.equals(fieldPath)) { + throw BadRequestException.of( + "Field path of a test case suggestion must be '%s', not '%s'" + .formatted(FIELD_PATH, fieldPath)); + } + Table table = loadTable(task); + TestCaseProposal proposal = proposalOf(payload); + CreateTestCase create = proposal.getTestCase(); + requireTableTest(table, create); + requireParameters(create); + requireGenerated(proposal); + } + + private static void requireTableTest(Table table, CreateTestCase create) { + if (!CUSTOM_SQL.equals(create.getTestDefinition())) { + throw BadRequestException.of( + "A test case suggestion proposes the test %s, not %s" + .formatted(CUSTOM_SQL, create.getTestDefinition())); + } + EntityLink link = EntityLink.parse(create.getEntityLink()); + if (!Entity.TABLE.equals(link.getEntityType()) + || link.getFieldName() != null + || !table.getFullyQualifiedName().equals(link.getEntityFQN())) { + throw BadRequestException.of( + "A test case suggestion proposes a test of the table it is about, %s, not %s" + .formatted(table.getFullyQualifiedName(), create.getEntityLink())); + } + if (nullOrEmpty(create.getName())) { + throw BadRequestException.of("A test case suggestion proposes a test with a name"); + } + if (Boolean.TRUE.equals(create.getComputePassedFailedRowCount())) { + throw BadRequestException.of( + "A test case suggestion proposes a test that does not compute passed and failed rows"); + } + } + + private static void requireParameters(CreateTestCase create) { + List values = listOrEmpty(create.getParameterValues()); + List names = values.stream().map(TestCaseParameterValue::getName).toList(); + if (!PARAMETERS.equals(names)) { + throw BadRequestException.of( + "A test case suggestion proposes the parameters %s in that order, not %s" + .formatted(PARAMETERS, names)); + } + if (nullOrEmpty(values.get(0).getValue()) + || !"COUNT".equals(values.get(1).getValue()) + || !"<=".equals(values.get(2).getValue()) + || !"0".equals(values.get(3).getValue())) { + throw BadRequestException.of( + "A test case suggestion counts the records in violation: strategy COUNT, operator <= and" + + " threshold 0, with a statement"); + } + } + + private static void requireGenerated(TestCaseProposal proposal) { + TestCaseGeneratedBy generatedBy = proposal.getGeneratedBy(); + CreateTestCase create = proposal.getTestCase(); + if (nullOrEmpty(proposal.getInspectionQuery())) { + throw BadRequestException.of("A test case suggestion carries the inspection query"); + } + String digest = + digest(create.getTestDefinition(), create.getEntityLink(), create.getParameterValues()); + if (generatedBy == null + || generatedBy.getClass_() == null + || generatedBy.getClass_().getId() == null) { + throw BadRequestException.of("A test case suggestion names the class it was generated for"); + } + if (!digest.equals(generatedBy.getContentDigest())) { + throw BadRequestException.of( + "The content digest of a test case suggestion must be that of its test definition, entity" + + " link and parameter values: %s".formatted(digest)); + } + } + + /** The test case to create: the proposal's values with the approver as its creator. */ + public static TestCase testCaseOf(TestCaseProposal proposal, String approver) { + CreateTestCase create = proposal.getTestCase(); + return new org.openmetadata.service.resources.dqtests.TestCaseMapper() + .createToEntity(create, approver) + .withInspectionQuery(proposal.getInspectionQuery()) + .withGeneratedBy(proposal.getGeneratedBy()); + } +} diff --git a/openmetadata-service/src/main/resources/json/data/policy/OntologyAuthorPolicy.json b/openmetadata-service/src/main/resources/json/data/policy/OntologyAuthorPolicy.json index 6c330fa6f23e..625e3c343c21 100644 --- a/openmetadata-service/src/main/resources/json/data/policy/OntologyAuthorPolicy.json +++ b/openmetadata-service/src/main/resources/json/data/policy/OntologyAuthorPolicy.json @@ -2,7 +2,7 @@ "name": "OntologyAuthorPolicy", "displayName": "Ontology Author Policy", "fullyQualifiedName": "OntologyAuthorPolicy", - "description": "Policy for authoring ontologies: create, edit and delete ontologies, concepts, properties, axioms and change sets, read releases, and request a release review.", + "description": "Policy for authoring ontologies: create, edit and delete ontologies, concepts, properties, axioms, shapes and change sets, read releases, and request a release review.", "enabled": true, "allowDelete": false, "provider": "system", @@ -10,7 +10,7 @@ { "name": "OntologyAuthorPolicy-AuthorRule", "description": "Allow authors to create, edit, delete and view the content of an ontology.", - "resources": ["ontology", "ontologyConcept", "ontologyProperty", "ontologyAxiom", "ontologyChangeSet"], + "resources": ["ontology", "ontologyConcept", "ontologyProperty", "ontologyAxiom", "ontologyShape", "ontologyChangeSet"], "operations": ["Create", "Delete", "ViewAll", "EditAll"], "effect": "allow" }, diff --git a/openmetadata-service/src/main/resources/json/data/policy/OntologyReviewerPolicy.json b/openmetadata-service/src/main/resources/json/data/policy/OntologyReviewerPolicy.json index b60eb535ba86..617ff01df7b4 100644 --- a/openmetadata-service/src/main/resources/json/data/policy/OntologyReviewerPolicy.json +++ b/openmetadata-service/src/main/resources/json/data/policy/OntologyReviewerPolicy.json @@ -10,7 +10,7 @@ { "name": "OntologyReviewerPolicy-ViewRule", "description": "Allow reviewers to view ontologies, their content and their releases.", - "resources": ["ontology", "ontologyConcept", "ontologyProperty", "ontologyAxiom", "ontologyChangeSet", "ontologyRelease"], + "resources": ["ontology", "ontologyConcept", "ontologyProperty", "ontologyAxiom", "ontologyShape", "ontologyChangeSet", "ontologyRelease"], "operations": ["ViewAll"], "effect": "allow" } diff --git a/openmetadata-service/src/main/resources/json/data/role/OntologyAuthor.json b/openmetadata-service/src/main/resources/json/data/role/OntologyAuthor.json index 1262d96b9174..4d2dcdbc72aa 100644 --- a/openmetadata-service/src/main/resources/json/data/role/OntologyAuthor.json +++ b/openmetadata-service/src/main/resources/json/data/role/OntologyAuthor.json @@ -1,7 +1,7 @@ { "name": "OntologyAuthor", "displayName": "Ontology Author", - "description": "Users with the Ontology Author role create and edit ontologies, concepts, properties and axioms, capture releases, and request their review.", + "description": "Users with the Ontology Author role create and edit ontologies, concepts, properties, axioms and shapes, capture releases, and request their review.", "allowDelete": false, "provider": "system", "policies": [ diff --git a/openmetadata-service/src/main/resources/json/data/taskFormSchemas/TableConstraintSuggestion.json b/openmetadata-service/src/main/resources/json/data/taskFormSchemas/TableConstraintSuggestion.json new file mode 100644 index 000000000000..de72b285db4b --- /dev/null +++ b/openmetadata-service/src/main/resources/json/data/taskFormSchemas/TableConstraintSuggestion.json @@ -0,0 +1,31 @@ +{ + "name": "TableConstraintSuggestion", + "displayName": "Table Constraint Suggestion", + "taskType": "Suggestion", + "taskCategory": "MetadataUpdate", + "formSchema": { + "type": "object", + "required": [ + "suggestedValue" + ], + "properties": { + "suggestedValue": { + "type": "string", + "title": "Suggested Table Constraint (JSON)" + }, + "reasoning": { + "type": "string", + "title": "Reason for suggestion" + } + } + }, + "uiSchema": { + "suggestedValue": { + "ui:widget": "textarea" + }, + "reasoning": { + "ui:widget": "textarea" + } + }, + "fullyQualifiedName": "TableConstraintSuggestion" +} diff --git a/openmetadata-service/src/main/resources/json/data/taskFormSchemas/TestCaseSuggestion.json b/openmetadata-service/src/main/resources/json/data/taskFormSchemas/TestCaseSuggestion.json new file mode 100644 index 000000000000..bd86cdd38b57 --- /dev/null +++ b/openmetadata-service/src/main/resources/json/data/taskFormSchemas/TestCaseSuggestion.json @@ -0,0 +1,31 @@ +{ + "name": "TestCaseSuggestion", + "displayName": "Test Case Suggestion", + "taskType": "Suggestion", + "taskCategory": "MetadataUpdate", + "formSchema": { + "type": "object", + "required": [ + "suggestedValue" + ], + "properties": { + "suggestedValue": { + "type": "string", + "title": "Suggested Test Case (JSON)" + }, + "reasoning": { + "type": "string", + "title": "Reason for suggestion" + } + } + }, + "uiSchema": { + "suggestedValue": { + "ui:widget": "textarea" + }, + "reasoning": { + "ui:widget": "textarea" + } + }, + "fullyQualifiedName": "TestCaseSuggestion" +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/alerting/matching/AlertsRuleEvaluatorMaskedFieldChangeTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/alerting/matching/AlertsRuleEvaluatorMaskedFieldChangeTest.java new file mode 100644 index 000000000000..c711ed876c02 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/alerting/matching/AlertsRuleEvaluatorMaskedFieldChangeTest.java @@ -0,0 +1,98 @@ +/* + * 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.alerting.matching; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.auth.JWTAuthMechanism; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.teams.AuthenticationMechanism; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.ChangeDescription; +import org.openmetadata.schema.type.ChangeEvent; +import org.openmetadata.schema.type.EventType; +import org.openmetadata.schema.type.FieldChange; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.events.ChangeEventMasking; + +/** An alert reads the stored event, so a masked field must still match by name once stored. */ +class AlertsRuleEvaluatorMaskedFieldChangeTest { + + @BeforeAll + static void knowTheEntityTypes() { + EntityInterface.ENTITY_TYPE_TO_CLASS_MAP.putIfAbsent(Entity.USER, User.class); + EntityInterface.ENTITY_TYPE_TO_CLASS_MAP.putIfAbsent( + Entity.ONTOLOGY_CHANGE_SET.toLowerCase(Locale.ROOT), OntologyChangeSet.class); + } + + @Test + void aStoredDraftUpdateMatchesAnAlertOnItsOperations() { + final ChangeEvent stored = + stored( + new ChangeEvent() + .withEntityType(Entity.ONTOLOGY_CHANGE_SET) + .withEntity(new OntologyChangeSet().withId(UUID.randomUUID()).withName("draft")), + "operations"); + + assertTrue(new AlertsRuleEvaluator(stored).matchAnyFieldChange(List.of("operations"))); + assertFalse(new AlertsRuleEvaluator(stored).matchAnyFieldChange(List.of("description"))); + } + + @Test + void aStoredUserUpdateMatchesAnAlertOnItsAuthenticationMechanism() { + final User bot = + new User() + .withId(UUID.randomUUID()) + .withName("ingestion-bot") + .withEmail("ingestion-bot@open-metadata.org") + .withAuthenticationMechanism( + new AuthenticationMechanism() + .withAuthType(AuthenticationMechanism.AuthType.JWT) + .withConfig(new JWTAuthMechanism().withJWTToken("eyJ.secret.token"))); + final ChangeEvent stored = + stored( + new ChangeEvent().withEntityType(Entity.USER).withEntity(bot), + "authenticationMechanism"); + + assertTrue( + new AlertsRuleEvaluator(stored).matchAnyFieldChange(List.of("authenticationMechanism"))); + } + + private static ChangeEvent stored(final ChangeEvent event, final String field) { + final ChangeEvent recorded = + event + .withId(UUID.randomUUID()) + .withEventType(EventType.ENTITY_UPDATED) + .withTimestamp(System.currentTimeMillis()) + .withChangeDescription( + new ChangeDescription() + .withFieldsUpdated( + List.of( + new FieldChange() + .withName(field) + .withOldValue("old-secret") + .withNewValue("new-secret")))); + final String json = ChangeEventMasking.masked(JsonUtils.pojoToJson(recorded)); + assertFalse(json.contains("secret")); + return JsonUtils.readValue(json, ChangeEvent.class); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/AppConfigurationCheckTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/AppConfigurationCheckTest.java new file mode 100644 index 000000000000..b4ab557c760a --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/AppConfigurationCheckTest.java @@ -0,0 +1,153 @@ +/* + * 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.apps; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; + +import jakarta.ws.rs.core.Response; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.MockedStatic; +import org.openmetadata.schema.entity.app.App; +import org.openmetadata.service.Entity; +import org.openmetadata.service.apps.bundles.cache.CacheWarmupApp; +import org.openmetadata.service.apps.bundles.insights.DataInsightsReportApp; +import org.openmetadata.service.apps.bundles.rdf.RdfIndexApp; +import org.openmetadata.service.apps.bundles.searchIndex.SearchIndexApp; +import org.openmetadata.service.exception.AppException; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.search.SearchRepository; + +class AppConfigurationCheckTest { + + private static final Map BAD_BATCH_SIZE = Map.of("batchSize", "many"); + + @Test + void defaultCheckAcceptsEveryConfiguration() { + AbstractNativeApplication app = new AbstractNativeApplication(null, null); + + assertDoesNotThrow(() -> app.validateConfigForSave(Map.of("anything", Map.of("at", "all")))); + } + + @Test + void searchIndexAppRefusesAStringBatchSize() { + SearchIndexApp app = new SearchIndexApp(null, null); + + AppException refused = + assertThrows(AppException.class, () -> app.validateConfigForSave(BAD_BATCH_SIZE)); + + assertRefusedWith("Invalid App Configuration: Cannot deserialize value of type", refused); + assertDoesNotThrow(() -> app.validateConfigForSave(Map.of("batchSize", 100))); + } + + @Test + void cacheWarmupAppRefusesAStringBatchSize() { + CacheWarmupApp app = new CacheWarmupApp(null, null); + + AppException refused = + assertThrows(AppException.class, () -> app.validateConfigForSave(BAD_BATCH_SIZE)); + + assertRefusedWith("Invalid App Configuration: Cannot deserialize value of type", refused); + assertDoesNotThrow(() -> app.validateConfigForSave(Map.of("batchSize", 100))); + } + + @Test + void rdfIndexAppRefusesAStringBatchSize() { + RdfIndexApp app = new RdfIndexApp(null, null); + + AppException refused = + assertThrows(AppException.class, () -> app.validateConfigForSave(BAD_BATCH_SIZE)); + + assertEquals("Invalid App Configuration", refused.getMessage()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), refused.getResponse().getStatus()); + assertDoesNotThrow(() -> app.validateConfigForSave(Map.of("batchSize", 100))); + } + + @Test + void dataInsightsReportAppRefusesAStringFlag() { + try (MockedStatic entity = mockStatic(Entity.class)) { + entity + .when(Entity::getCollectionDAO) + .thenReturn(mock(CollectionDAO.class, Answers.RETURNS_DEEP_STUBS)); + DataInsightsReportApp app = new DataInsightsReportApp(null, null); + + AppException refused = + assertThrows( + AppException.class, () -> app.validateConfigForSave(Map.of("sendToAdmins", "maybe"))); + + assertRefusedWith("Invalid DataInsightsReportAppConfig configuration: ", refused); + assertDoesNotThrow(() -> app.validateConfigForSave(Map.of("sendToAdmins", false))); + } + } + + @Test + void anAppThatInheritsTheDefaultCheckIsNotBuilt() { + App app = + new App().withName("inheriting").withClassName(ThrowingConstructorApp.class.getName()); + + assertDoesNotThrow(() -> handler().validateConfigurationForSave(app, null, null)); + } + + @Test + void anAppWithItsOwnCheckIsBuiltAndChecked() { + App app = + new App() + .withName("declaring") + .withClassName(DeclaringApp.class.getName()) + .withAppConfiguration(Map.of("batchSize", "many")); + + AppException refused = + assertThrows( + AppException.class, () -> handler().validateConfigurationForSave(app, null, null)); + + assertRefusedWith("Invalid declared configuration", refused); + app.setAppConfiguration(Map.of("batchSize", 100)); + assertDoesNotThrow(() -> handler().validateConfigurationForSave(app, null, null)); + } + + private static ApplicationHandler handler() { + return mock(ApplicationHandler.class, CALLS_REAL_METHODS); + } + + public static class ThrowingConstructorApp extends AbstractNativeApplication { + public ThrowingConstructorApp(CollectionDAO collectionDAO, SearchRepository searchRepository) { + super(collectionDAO, searchRepository); + throw new IllegalStateException("constructor must not run"); + } + } + + public static class DeclaringApp extends AbstractNativeApplication { + public DeclaringApp(CollectionDAO collectionDAO, SearchRepository searchRepository) { + super(collectionDAO, searchRepository); + } + + @Override + public void validateConfigForSave(Map config) { + if (!(config.get("batchSize") instanceof Number)) { + throw AppException.byMessage(Response.Status.BAD_REQUEST, "Invalid declared configuration"); + } + } + } + + private static void assertRefusedWith(String messagePrefix, AppException refused) { + assertTrue(refused.getMessage().startsWith(messagePrefix), refused.getMessage()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), refused.getResponse().getStatus()); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java index 9f151a274baf..277f744dcb7b 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/events/ChangeEventMaskingTest.java @@ -28,14 +28,20 @@ import org.junit.jupiter.api.Test; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.auth.JWTAuthMechanism; +import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.entity.data.Table; import org.openmetadata.schema.entity.services.ingestionPipelines.IngestionPipeline; import org.openmetadata.schema.entity.teams.AuthenticationMechanism; import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.security.client.OpenMetadataJWTClientConfig; import org.openmetadata.schema.services.connections.metadata.OpenMetadataConnection; +import org.openmetadata.schema.type.ChangeDescription; import org.openmetadata.schema.type.ChangeEvent; import org.openmetadata.schema.type.EventType; +import org.openmetadata.schema.type.FieldChange; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; @@ -131,6 +137,115 @@ void anEventOfATypeWithNoMaskedFieldIsStoredAsItCame() { assertSame(event, ChangeEventMasking.masked(event)); } + @Test + void aChangeOfAMaskedFieldKeepsItsNameAndLosesItsValues() { + final ChangeDescription changes = + new ChangeDescription() + .withFieldsAdded(List.of(change("authenticationMechanism", null, "added-secret"))) + .withFieldsUpdated( + List.of( + change("authenticationMechanism", "old-secret", "new-secret"), + change("authenticationMechanism.config", "old-secret", "new-secret"), + change("displayName", "Old", "New"))) + .withFieldsDeleted(List.of(change("authenticationMechanism", "gone-secret", null))); + + final String stored = + ChangeEventMasking.masked( + JsonUtils.pojoToJson(userEvent(bot()).withChangeDescription(changes))); + + final JsonNode kept = JsonUtils.readTree(stored).path("changeDescription"); + assertEquals( + List.of("authenticationMechanism"), kept.path("fieldsAdded").findValuesAsText("name")); + assertEquals( + List.of("authenticationMechanism"), kept.path("fieldsDeleted").findValuesAsText("name")); + assertEquals( + List.of("authenticationMechanism", "authenticationMechanism.config", "displayName"), + kept.path("fieldsUpdated").findValuesAsText("name")); + for (final String kind : List.of("fieldsAdded", "fieldsUpdated", "fieldsDeleted")) { + for (final JsonNode entry : kept.path(kind)) { + final boolean isMasked = entry.path("name").asText().startsWith("authenticationMechanism"); + assertEquals(!isMasked, entry.has("newValue") || entry.has("oldValue")); + } + } + assertEquals("New", kept.path("fieldsUpdated").get(2).path("newValue").asText()); + assertFalse(stored.contains("secret")); + } + + @Test + void aChangeOfAFieldThatOnlyHoldsASecretInsideItStaysInTheRecordedChanges() { + final ChangeDescription changes = + new ChangeDescription().withFieldsUpdated(List.of(change("description", "Old", "New"))); + + final String event = JsonUtils.pojoToJson(userEvent(bot()).withChangeDescription(changes)); + + assertEquals( + List.of("description"), + JsonUtils.readTree(ChangeEventMasking.masked(event)) + .path("changeDescription") + .path("fieldsUpdated") + .findValuesAsText("name")); + } + + @Test + void aDraftsOperationsLeaveItsEntityAndItsRecordedChanges() { + EntityInterface.ENTITY_TYPE_TO_CLASS_MAP.putIfAbsent( + Entity.ONTOLOGY_CHANGE_SET.toLowerCase(Locale.ROOT), OntologyChangeSet.class); + final UUID tableId = UUID.randomUUID(); + final OntologyChangeOperation operation = + new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBinding(new OntologyBindingChange().withTableId(tableId)); + final ChangeDescription changes = + new ChangeDescription() + .withFieldsUpdated( + List.of( + change("operations", "[]", JsonUtils.pojoToJson(List.of(operation))), + change("undoCursor", "0", "1"))); + final ChangeEvent event = + new ChangeEvent() + .withId(UUID.randomUUID()) + .withEventType(EventType.ENTITY_UPDATED) + .withEntityType(Entity.ONTOLOGY_CHANGE_SET) + .withChangeDescription(changes) + .withEntity( + new OntologyChangeSet() + .withId(UUID.randomUUID()) + .withName("draft") + .withUndoCursor(1) + .withOperations(List.of(operation)) + .withChangeDescription(changes) + .withIncrementalChangeDescription(changes)); + + final String stored = ChangeEventMasking.masked(JsonUtils.pojoToJson(event)); + + assertFalse(stored.contains(tableId.toString())); + final JsonNode entity = storedEntity(stored); + assertFalse(entity.has("operations")); + assertEquals( + List.of("operations", "undoCursor"), + entity.path("changeDescription").path("fieldsUpdated").findValuesAsText("name")); + assertFalse(entity.path("changeDescription").path("fieldsUpdated").get(0).has("newValue")); + assertFalse(entity.path("changeDescription").path("fieldsUpdated").get(0).has("oldValue")); + final JsonNode incremental = entity.path("incrementalChangeDescription").path("fieldsUpdated"); + assertEquals(List.of("operations", "undoCursor"), incremental.findValuesAsText("name")); + assertFalse(incremental.get(0).has("newValue")); + assertFalse(incremental.get(0).has("oldValue")); + assertEquals("draft", entity.path("name").asText()); + assertEquals(1, entity.path("undoCursor").asInt()); + final JsonNode updated = + JsonUtils.readTree(stored).path("changeDescription").path("fieldsUpdated"); + assertEquals(List.of("operations", "undoCursor"), updated.findValuesAsText("name")); + assertFalse(updated.get(0).has("newValue")); + assertFalse(updated.get(0).has("oldValue")); + assertEquals("1", updated.get(1).path("newValue").asText()); + } + + private static FieldChange change( + final String name, final Object oldValue, final Object newValue) { + return new FieldChange().withName(name).withOldValue(oldValue).withNewValue(newValue); + } + private static ChangeEvent userEvent(final Object entity) { return new ChangeEvent() .withId(UUID.randomUUID()) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java new file mode 100644 index 000000000000..ded7192d6096 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/GeneratedTestScopeTest.java @@ -0,0 +1,212 @@ +/* + * 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.jdbi3; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestCaseGeneratedBy; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.service.exception.BadRequestException; + +class GeneratedTestScopeTest { + private static final String SET_BY_SERVER = + "generatedBy is set by the server when a suggestion creates a test from a shape, and cannot be sent or changed"; + + @Test + void aCreateThatSendsGeneratedByIsRefused() { + BadRequestException e = + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireUnsetOnCreate(generated(UUID.randomUUID(), "a = 1"))); + assertEquals(SET_BY_SERVER, e.getMessage()); + } + + @Test + void aCreateInsideTheScopeIsAccepted() { + try (GeneratedTestScope.Handle ignored = GeneratedTestScope.enter()) { + assertTrue(GeneratedTestScope.isActive()); + assertDoesNotThrow( + () -> GeneratedTestScope.requireUnsetOnCreate(generated(UUID.randomUUID(), "a = 1"))); + } + assertFalse(GeneratedTestScope.isActive()); + } + + @Test + void aPersonsTestMayCarryNoGeneratedByAndMayChangeFreely() { + TestCase original = plain(UUID.randomUUID(), "a = 1"); + TestCase updated = plain(original.getTestDefinition().getId(), "a = 2"); + assertDoesNotThrow(() -> GeneratedTestScope.requireUnchanged(original, updated)); + } + + @Test + void aPatchThatAddsOrChangesGeneratedByIsRefused() { + UUID definition = UUID.randomUUID(); + assertEquals( + SET_BY_SERVER, + assertThrows( + BadRequestException.class, + () -> + GeneratedTestScope.requireUnchanged( + plain(definition, "a = 1"), generated(definition, "a = 1"))) + .getMessage()); + TestCase other = generated(definition, "a = 1"); + other.getGeneratedBy().setIdentity("b".repeat(64)); + assertEquals( + SET_BY_SERVER, + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireUnchanged(generated(definition, "a = 1"), other)) + .getMessage()); + } + + @Test + void aChangeToWhatAGeneratedTestFreezesIsRefused() { + UUID definition = UUID.randomUUID(); + TestCase original = generated(definition, "a = 1"); + assertEquals( + GeneratedTestScope.FROM_A_SHAPE, + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireUnchanged(original, generated(definition, "a = 2"))) + .getMessage()); + TestCase otherLink = generated(definition, "a = 1").withEntityLink("<#E::table::x.y.z.t>"); + assertThrows( + BadRequestException.class, () -> GeneratedTestScope.requireUnchanged(original, otherLink)); + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireUnchanged(original, generated(UUID.randomUUID(), "a = 1"))); + } + + @Test + void aChangeToDescriptionOnlyIsAccepted() { + UUID definition = UUID.randomUUID(); + TestCase updated = generated(definition, "a = 1").withDescription("now with words"); + assertDoesNotThrow( + () -> GeneratedTestScope.requireUnchanged(generated(definition, "a = 1"), updated)); + } + + @Test + void theReconcileMayChangeWhatIsFrozenInsideTheScope() { + UUID definition = UUID.randomUUID(); + try (GeneratedTestScope.Handle ignored = GeneratedTestScope.enter()) { + assertDoesNotThrow( + () -> + GeneratedTestScope.requireUnchanged( + generated(definition, "a = 1"), generated(definition, "a = 2"))); + } + } + + @Test + void aChangeToAnyOneOfTheFourFrozenParametersIsRefused() { + UUID definition = UUID.randomUUID(); + for (String name : List.of("sqlExpression", "strategy", "operator", "threshold")) { + TestCase original = counted(definition, "0"); + TestCase updated = counted(definition, "0"); + updated.getParameterValues().stream() + .filter(value -> name.equals(value.getName())) + .forEach(value -> value.setValue("changed")); + BadRequestException e = + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireUnchanged(original, updated), + name); + assertEquals(GeneratedTestScope.FROM_A_SHAPE, e.getMessage(), name); + } + } + + @Test + void theSameFourParametersAreAcceptedUnchanged() { + UUID definition = UUID.randomUUID(); + assertDoesNotThrow( + () -> + GeneratedTestScope.requireUnchanged( + counted(definition, "0"), counted(definition, "0").withDescription("words"))); + } + + private static TestCase counted(final UUID definition, final String threshold) { + return generated(definition, "SELECT 1") + .withParameterValues( + List.of( + new TestCaseParameterValue().withName("sqlExpression").withValue("SELECT 1"), + new TestCaseParameterValue().withName("strategy").withValue("COUNT"), + new TestCaseParameterValue().withName("operator").withValue("<="), + new TestCaseParameterValue().withName("threshold").withValue(threshold))); + } + + private static TestCase plain(final UUID definition, final String statement) { + return new TestCase() + .withEntityLink("<#E::table::svc.db.schema.t>") + .withTestDefinition(new EntityReference().withId(definition).withType("testDefinition")) + .withParameterValues( + List.of(new TestCaseParameterValue().withName("sqlExpression").withValue(statement))); + } + + @Test + void aPutNamesTheDefinitionByNameAndTheStoredTestSaysWhereItComesFrom() { + UUID definition = UUID.randomUUID(); + TestCase stored = generated(definition, "a = 1"); + stored.getTestDefinition().setFullyQualifiedName("tableCustomSQLQuery"); + TestCase sameName = plain(definition, "a = 1"); + sameName.setTestDefinition( + new EntityReference() + .withType("testDefinition") + .withFullyQualifiedName("tableCustomSQLQuery")); + TestCase otherName = plain(definition, "a = 1"); + otherName.setTestDefinition( + new EntityReference() + .withType("testDefinition") + .withFullyQualifiedName("tableRowCountToEqual")); + + assertDoesNotThrow(() -> GeneratedTestScope.requireFrozenFieldsUnchanged(stored, sameName)); + assertEquals( + GeneratedTestScope.FROM_A_SHAPE, + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireFrozenFieldsUnchanged(stored, otherName)) + .getMessage()); + } + + @Test + void aReferenceThatCarriesAnIdIsComparedByIdAndNotByName() { + UUID definition = UUID.randomUUID(); + TestCase stored = generated(definition, "a = 1"); + stored.getTestDefinition().setFullyQualifiedName("tableCustomSQLQuery"); + TestCase sameId = plain(definition, "a = 1"); + sameId.getTestDefinition().setFullyQualifiedName("renamedDefinition"); + TestCase otherId = plain(UUID.randomUUID(), "a = 1"); + otherId.getTestDefinition().setFullyQualifiedName("tableCustomSQLQuery"); + + assertDoesNotThrow(() -> GeneratedTestScope.requireFrozenFieldsUnchanged(stored, sameId)); + assertEquals( + GeneratedTestScope.FROM_A_SHAPE, + assertThrows( + BadRequestException.class, + () -> GeneratedTestScope.requireFrozenFieldsUnchanged(stored, otherId)) + .getMessage()); + } + + private static TestCase generated(final UUID definition, final String statement) { + return plain(definition, statement) + .withGeneratedBy(new TestCaseGeneratedBy().withIdentity("a".repeat(64))); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java new file mode 100644 index 000000000000..943a8be088f8 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/OntologyConceptBindingStoreAncestorsTest.java @@ -0,0 +1,422 @@ +/* + * 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.jdbi3; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyAxiom; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyAxiomType; +import org.openmetadata.schema.type.OntologyExpression; +import org.openmetadata.schema.type.OntologyExpressionKind; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.exception.BadRequestException; + +/** + * The walk up the named subclass steps of a class, with the axioms served by a stubbed DAO that + * answers as the real one does: the subclass axioms of the classes asked for, by axiom name, up to + * the limit. The walk is bound at 10,000, which {@link OntologyConceptBindingStore#ancestors} reads + * as the classes it returns, the start included, and {@link + * OntologyConceptBindingStore#namedParentsAbove} as the classes above the starts and the axioms it + * reads, all starts together. + */ +class OntologyConceptBindingStoreAncestorsTest { + private static final UUID ONTOLOGY = UUID.randomUUID(); + private static final String BASE = "https://example.org/walk/"; + private static final String REFUSED = + "Binding property inheritance exceeds the 10000 axiom limit"; + + /** A stubbed DAO that counts the statements asked of it. */ + private static final class Axioms { + private final List stored = new ArrayList<>(); + private final AtomicInteger statements = new AtomicInteger(); + private final AtomicInteger mostHashes = new AtomicInteger(); + private final AtomicInteger lastHashes = new AtomicInteger(); + private final OntologyConceptBindingStore store; + + private record Stored(String name, String subjectHash, String json) {} + + Axioms() { + final CollectionDAO dao = mock(CollectionDAO.class); + final OntologyReferenceDAO references = mock(OntologyReferenceDAO.class); + when(dao.ontologyReferenceDAO()).thenReturn(references); + when(references.ancestors(any(UUID.class), anyList(), anyInt(), anyString())) + .thenAnswer( + call -> { + statements.incrementAndGet(); + final List asked = call.getArgument(1); + mostHashes.accumulateAndGet(asked.size(), Math::max); + lastHashes.set(asked.size()); + final Set hashes = new HashSet<>(asked); + final int limit = call.getArgument(2); + return stored.stream() + .filter(axiom -> hashes.contains(axiom.subjectHash())) + .sorted(Comparator.comparing(Stored::name)) + .limit(limit) + .map(Stored::json) + .toList(); + }); + store = new OntologyConceptBindingStore(dao, type -> "table"); + } + + /** {@code child} is a subclass of {@code parent}, in an axiom of the given name. */ + Axioms subclass(final String name, final String child, final String parent) { + final OntologyAxiom axiom = + new OntologyAxiom() + .withId(UUID.randomUUID()) + .withName(name) + .withAxiomType(OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(iri(child)) + .withExpressions( + List.of( + new OntologyExpression() + .withKind(OntologyExpressionKind.NAMED_CLASS) + .withClassIri(iri(parent)))); + stored.add( + new Stored( + name, DigestUtils.sha256Hex(iri(child).toString()), JsonUtils.pojoToJson(axiom))); + return this; + } + + /** One axiom that puts {@code child} under every one of {@code parents}. */ + Axioms subclassOfAll(final String name, final String child, final List parents) { + final OntologyAxiom axiom = + new OntologyAxiom() + .withId(UUID.randomUUID()) + .withName(name) + .withAxiomType(OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(iri(child)) + .withExpressions( + parents.stream() + .map( + parent -> + new OntologyExpression() + .withKind(OntologyExpressionKind.NAMED_CLASS) + .withClassIri(iri(parent))) + .toList()); + stored.add( + new Stored( + name, DigestUtils.sha256Hex(iri(child).toString()), JsonUtils.pojoToJson(axiom))); + return this; + } + + /** {@code length} single-parent steps above {@code bottom}, each class named for its step. */ + Axioms chain(final String bottom, final int length) { + String child = bottom; + for (int step = 1; step <= length; step++) { + final String parent = bottom + "Above" + step; + subclass(child + "Is" + parent, child, parent); + child = parent; + } + return this; + } + + Set ancestors(final String start) { + return store.ancestors(concept(start)); + } + + Map> above(final String... starts) { + return store.namedParentsAbove( + ONTOLOGY, java.util.Arrays.stream(starts).map(s -> iri(s).toString()).toList()); + } + + int statements() { + return statements.get(); + } + + int mostHashesInAStatement() { + return mostHashes.get(); + } + + int hashesInTheLastStatement() { + return lastHashes.get(); + } + } + + private static URI iri(final String name) { + return URI.create(BASE + name); + } + + private static OntologyConcept concept(final String name) { + return new OntologyConcept() + .withId(UUID.nameUUIDFromBytes(name.getBytes())) + .withName(name) + .withIri(iri(name)) + .withOntology(new EntityReference().withId(ONTOLOGY).withType("ontology")); + } + + private static Set iris(final String... names) { + return java.util.Arrays.stream(names) + .map(name -> iri(name).toString()) + .collect(java.util.stream.Collectors.toSet()); + } + + /** 5,000 and 4,999 axioms: 9,999 classes above the starts, under the bound of 10,000. */ + @Test + void twoStartsUnderDisjointChainsOf5000And4999AxiomsAreWalkedTogether() { + final Axioms axioms = new Axioms().chain("First", 5_000).chain("Second", 4_999); + + final Map> parents = axioms.above("First", "Second"); + + assertEquals(9_999, parents.size()); + assertEquals(Set.of(iri("FirstAbove1").toString()), parents.get(iri("First").toString())); + assertEquals(Set.of(iri("SecondAbove1").toString()), parents.get(iri("Second").toString())); + assertEquals(5_001, axioms.statements()); + } + + /** 5,000 and 5,000 axioms: exactly 10,000 classes above the starts, which the bound allows. */ + @Test + void twoStartsWhoseChainsHoldExactlyTheBoundAreWalked() { + final Axioms axioms = new Axioms().chain("First", 5_000).chain("Second", 5_000); + + assertEquals(10_000, axioms.above("First", "Second").size()); + } + + /** 5,001 and 5,000 axioms: 10,001 classes above the starts together, over the bound. */ + @Test + void twoStartsWhoseChainsHoldMoreThanTheBoundTogetherAreRefused() { + final Axioms axioms = new Axioms().chain("First", 5_001).chain("Second", 5_000); + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> axioms.above("First", "Second")); + + assertEquals(REFUSED, refused.getMessage()); + } + + /** + * One start under 10,000 axioms: 10,000 classes above it, which {@code namedParentsAbove} allows. + * {@code ancestors} counts the start too, 10,001 classes in all, over the bound as it was. + */ + @Test + void oneStartUnderAChainOf10000AxiomsIsWalkedAboveButRefusedAsAnAncestorSet() { + final Axioms axioms = new Axioms().chain("Start", 10_000); + + assertEquals(10_000, axioms.above("Start").size()); + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> axioms.ancestors("Start")); + + assertEquals(REFUSED, refused.getMessage()); + } + + /** 9,999 axioms: 10,000 classes with the start, which the bound allows. */ + @Test + void oneStartUnderAChainOf9999AxiomsHasAnAncestorSetOfExactlyTheBound() { + final Axioms axioms = new Axioms().chain("Start", 9_999); + + assertEquals(10_000, axioms.ancestors("Start").size()); + } + + private static String step(final int index) { + return index == 0 ? "Start" : "StartAbove" + index; + } + + /** The chain of 5,999 steps over Start, and {@code skips} axioms that put step i under i + 2. */ + private static Axioms chainWithSkips(final int skips) { + final Axioms axioms = new Axioms().chain("Start", 5_999); + for (int i = 0; i < skips; i++) { + axioms.subclass("Skip" + i, step(i), step(i + 2)); + } + return axioms; + } + + /** 5,999 classes above Start, 5,999 + 4,002 = 10,001 axioms: over the bound by the axioms. */ + @Test + void oneStartWithMoreAxiomsThanClassesAboveItIsRefusedByTheAxioms() { + final Axioms axioms = chainWithSkips(4_002); + + final BadRequestException refusedAbove = + assertThrows(BadRequestException.class, () -> axioms.above("Start")); + final BadRequestException refusedAncestors = + assertThrows(BadRequestException.class, () -> axioms.ancestors("Start")); + + assertEquals(REFUSED, refusedAbove.getMessage()); + assertEquals(REFUSED, refusedAncestors.getMessage()); + } + + /** The same 5,999 classes above Start and 10,000 axioms: at the bound, answered. */ + @Test + void oneStartWithExactlyTheBoundInAxiomsAndFewerClassesAboveItIsWalked() { + final Axioms axioms = chainWithSkips(4_001); + + assertEquals(5_999, axioms.above("Start").size()); + assertEquals(6_000, axioms.ancestors("Start").size()); + } + + /** 10,001 starts with one axiom each under one class: 1 class above, 10,001 axioms in one read. */ + @Test + void startsWhoseAxiomsAreMoreThanTheBoundAreRefusedAfterTheFirstStatement() { + final Axioms axioms = new Axioms(); + final List starts = new ArrayList<>(); + for (int i = 0; i < 10_001; i++) { + starts.add("Sharing" + i); + axioms.subclass("Axiom" + i, "Sharing" + i, "Named"); + } + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> axioms.above(starts.toArray(String[]::new))); + + assertEquals(REFUSED, refused.getMessage()); + assertEquals(1, axioms.statements()); + } + + /** Two axioms of 5,001 named parents each: 10,002 classes in the one level, refused at once. */ + @Test + void aLevelOfMoreClassesThanTheBoundIsRefusedBeforeAnotherStatementIsAsked() { + final List first = new ArrayList<>(); + final List second = new ArrayList<>(); + for (int i = 0; i < 5_001; i++) { + first.add("ParentA" + i); + second.add("ParentB" + i); + } + final Axioms axioms = + new Axioms() + .subclassOfAll("AxiomA", "Start", first) + .subclassOfAll("AxiomB", "Start", second); + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> axioms.above("Start")); + + assertEquals(REFUSED, refused.getMessage()); + assertEquals(1, axioms.statements()); + } + + /** 30,001 starts, a chunk of 30,000 and one more. 5,001 of them are under Named: 1 class above. */ + @Test + void startsLongerThanOneChunkAreReadInChunksAndWalkedOnce() { + final Axioms axioms = new Axioms(); + final String[] starts = new String[CHUNK + 1]; + for (int i = 0; i <= CHUNK; i++) { + starts[i] = "Sharing" + i; + } + for (int i = 0; i < 5_000; i++) { + axioms.subclass("Axiom" + i, "Sharing" + i, "Named"); + } + axioms.subclass("AxiomLast", "Sharing" + CHUNK, "Named"); + + final Map> parents = axioms.above(starts); + + assertEquals(5_001, parents.size()); + assertEquals(Set.of(iri("Named").toString()), parents.get(iri("Sharing30000").toString())); + assertEquals(30_000, axioms.mostHashesInAStatement()); + assertEquals(3, axioms.statements()); + } + + /** + * Every parent is a start, so the first level finds no new class and no level follows. The first + * chunk of starts holds 9,999 axioms and the last start, alone in the second chunk, 1 or 2: + * 10,000 axioms in two statements, which the bound allows, or 10,001, which it does not, though + * neither chunk is over the limit of its own statement. + */ + @Test + void theChunksOfTheFirstLevelAreBoundTogether() { + final Axioms refusing = chunkedStarts(2); + final Axioms control = chunkedStarts(1); + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> refusing.above(chunkedStartNames())); + final Map> parents = control.above(chunkedStartNames()); + + assertEquals(REFUSED, refused.getMessage()); + assertEquals(2, refusing.statements()); + assertEquals(1, refusing.hashesInTheLastStatement()); + assertEquals(2, control.statements()); + assertEquals(10_000, parents.size()); + assertEquals(Set.of(iri("X1").toString()), parents.get(iri("X0").toString())); + assertEquals(Set.of(iri("X9999").toString()), parents.get(iri("X9998").toString())); + assertEquals(Set.of(iri("X0").toString()), parents.get(iri("Last").toString())); + } + + private static final int CHUNK = 30_000; + + private static String[] chunkedStartNames() { + final String[] starts = new String[CHUNK + 1]; + for (int i = 0; i < CHUNK; i++) { + starts[i] = "X" + i; + } + starts[CHUNK] = "Last"; + return starts; + } + + /** X(i) is under X(i+1) for the 9,999 axioms of the first chunk, and Last, alone in the second, under {@code last} of them. */ + private static Axioms chunkedStarts(final int last) { + final Axioms axioms = new Axioms(); + for (int i = 0; i < 9_999; i++) { + axioms.subclass("Axiom" + i, "X" + i, "X" + (i + 1)); + } + for (int i = 0; i < last; i++) { + axioms.subclass("Last" + i, "Last", "X" + i); + } + return axioms; + } + + @Test + void twoChainsThatMeetAreWalkedInThreeStatements() { + final Axioms axioms = twoParentsThatMeet(); + + final Set ancestors = axioms.ancestors("Start"); + + assertEquals(iris("Start", "A", "B", "X", "Top"), ancestors); + assertEquals(3, axioms.statements()); + } + + @Test + void aClassUnderTwoClassesHasBothAndEverythingAboveEach() { + final Axioms axioms = twoParentsThatMeet(); + + final Map> parents = axioms.above("Start"); + + assertEquals( + Set.of(iri("A").toString(), iri("B").toString()), parents.get(iri("Start").toString())); + assertEquals(Set.of(iri("Top").toString()), parents.get(iri("A").toString())); + assertEquals(Set.of(iri("X").toString()), parents.get(iri("B").toString())); + assertEquals(Set.of(iri("Top").toString()), parents.get(iri("X").toString())); + } + + @Test + void aClassWithNoParentIsItsOwnAncestorSetInOneStatement() { + final Axioms axioms = new Axioms(); + + assertEquals(iris("Start"), axioms.ancestors("Start")); + assertEquals(1, axioms.statements()); + } + + /** Start is under A and B, A is under Top, and B is under X, which is under Top. */ + private static Axioms twoParentsThatMeet() { + return new Axioms() + .subclass("StartIsA", "Start", "A") + .subclass("StartIsB", "Start", "B") + .subclass("AIsTop", "A", "Top") + .subclass("BIsX", "B", "X") + .subclass("XIsTop", "X", "Top"); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TaskRepositoryConstraintPermissionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TaskRepositoryConstraintPermissionTest.java new file mode 100644 index 000000000000..65499350501a --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TaskRepositoryConstraintPermissionTest.java @@ -0,0 +1,147 @@ +/* + * 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.jdbi3; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import jakarta.ws.rs.core.SecurityContext; +import java.security.Principal; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.openmetadata.schema.entity.feed.TaskFormSchema; +import org.openmetadata.schema.entity.feed.UiSchema; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.service.Entity; +import org.openmetadata.service.security.AuthRequest; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContextInterface; + +/** + * The right to resolve a suggestion task on its table comes from the suggested change. A task form + * bound to the task's category can narrow it for a description suggestion, never for a table + * constraint. + */ +class TaskRepositoryConstraintPermissionTest { + private static final String TABLE_FQN = "svc.db.schema.orders"; + private MockedStatic entity; + private Authorizer authorizer; + private SecurityContext securityContext; + private TaskFormSchemaRepository formRepository; + + @BeforeEach + void setUp() { + formRepository = mock(TaskFormSchemaRepository.class); + when(formRepository.resolve(anyString(), any(), any())) + .thenReturn(Optional.of(formWithPermission("EditDescription"))); + entity = mockStatic(Entity.class); + entity + .when(() -> Entity.getEntityRepository(Entity.TASK_FORM_SCHEMA)) + .thenAnswer(i -> formRepository); + authorizer = mock(Authorizer.class); + Principal principal = mock(Principal.class); + when(principal.getName()).thenReturn("shared_user2"); + securityContext = mock(SecurityContext.class); + when(securityContext.getUserPrincipal()).thenReturn(principal); + } + + @AfterEach + void tearDown() { + entity.close(); + } + + @Test + void aConstraintSuggestion_needsEditAllOnTheTableWhateverPermissionTheFormNames() { + TaskRepository repository = mock(TaskRepository.class, CALLS_REAL_METHODS); + + repository.checkPermissionsForResolveTask( + authorizer, suggestion("TableConstraint"), false, securityContext); + + ArgumentCaptor tableOperation = + ArgumentCaptor.forClass(OperationContext.class); + verify(authorizer, times(2)) + .authorize(any(SecurityContext.class), tableOperation.capture(), any()); + OperationContext table = tableOperation.getAllValues().get(1); + assertEquals(Entity.TABLE, table.getResource()); + assertEquals( + List.of(MetadataOperation.EDIT_ALL), table.getOperations((ResourceContextInterface) null)); + verify(authorizer, never()).authorizeRequests(any(), any(), any()); + } + + @Test + void aDescriptionSuggestion_stillAsksForThePermissionTheFormNames() { + TaskRepository repository = mock(TaskRepository.class, CALLS_REAL_METHODS); + + repository.checkPermissionsForResolveTask( + authorizer, suggestion("Description"), false, securityContext); + + ArgumentCaptor> requests = ArgumentCaptor.forClass(List.class); + verify(authorizer).authorizeRequests(any(), requests.capture(), any()); + assertEquals( + List.of(MetadataOperation.EDIT_DESCRIPTION, MetadataOperation.EDIT_ALL), + requests.getValue().stream() + .map( + request -> + request + .operationContext() + .getOperations((ResourceContextInterface) null) + .get(0)) + .toList()); + } + + private static TaskFormSchema formWithPermission(String permission) { + return new TaskFormSchema() + .withUiSchema( + new UiSchema() + .withAdditionalProperty( + "ui:handler", Map.of("type", "suggestion", "permission", permission))); + } + + private static Task suggestion(String suggestionType) { + return new Task() + .withId(UUID.randomUUID()) + .withType(TaskEntityType.Suggestion) + .withAbout( + new EntityReference() + .withId(UUID.randomUUID()) + .withType(Entity.TABLE) + .withFullyQualifiedName(TABLE_FQN)) + .withPayload( + Map.of( + "suggestionType", + suggestionType, + "fieldPath", + suggestionType.equals("Description") ? "description" : "tableConstraints", + "suggestedValue", + "x")); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v1114/MigrationUtilTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v1114/MigrationUtilTest.java index 6144871a5901..8acc1b66d257 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v1114/MigrationUtilTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v1114/MigrationUtilTest.java @@ -16,14 +16,19 @@ import java.util.Map; import org.jdbi.v3.core.Handle; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.mockito.MockedStatic; import org.openmetadata.schema.api.search.FieldValueBoost; import org.openmetadata.schema.api.search.GlobalSettings; import org.openmetadata.schema.api.search.SearchSettings; +import org.openmetadata.schema.entity.Bot; import org.openmetadata.schema.entity.teams.Role; import org.openmetadata.schema.settings.Settings; import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.BotRepository; import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.ListFilter; import org.openmetadata.service.jdbi3.locator.ConnectionType; import org.openmetadata.service.migration.utils.SearchSettingsMergeUtil; @@ -65,6 +70,46 @@ SELECT COUNT(*) FROM role_entity WHERE json->>'name' = :name """; + private static final String FIND_BOT_USER_POSTGRES = + """ + SELECT id FROM user_entity + WHERE json->>'name' = :name + AND (json->>'isBot')::boolean = true + """; + + private static final String FIND_BOT_USER_MYSQL = + """ + SELECT id FROM user_entity + WHERE JSON_UNQUOTE(JSON_EXTRACT(json, '$.name')) = :name + AND JSON_EXTRACT(json, '$.isBot') = true + """; + + private static final String CHECK_ROLE_EXISTS_MYSQL = + """ + SELECT COUNT(*) FROM role_entity + WHERE JSON_UNQUOTE(JSON_EXTRACT(json, '$.name')) = :name + """; + + private static final String ANY_USER_ROLE_QUERY = + """ + SELECT COUNT(*) as cnt FROM entity_relationship + WHERE fromId = :userId + AND fromEntity = 'user' AND toEntity = 'role' AND relation = :relation + """; + + private static final String INSERT_USER_ROLE_POSTGRES = + """ + INSERT INTO entity_relationship (fromId, toId, fromEntity, toEntity, relation) + VALUES (:userId, :roleId, 'user', 'role', :relation) + ON CONFLICT DO NOTHING + """; + + private static final String INSERT_USER_ROLE_MYSQL = + """ + INSERT IGNORE INTO entity_relationship (fromId, toId, fromEntity, toEntity, relation) + VALUES (:userId, :roleId, 'user', 'role', :relation) + """; + private static final List SYSTEM_POLICIES = List.of( "OrganizationPolicy", @@ -221,6 +266,140 @@ void restoreBotRelationshipsIfMissingInsertsOnlyWhenMatchingBotsExist() { .execute(); } + @Test + void restoreBotUserRolesGivesBuiltInBotWithoutRoleItMappedRole() { + Handle handle = botRoleHandle("ingestion-bot", "user-1", "IngestionBotRole", "role-1", 0); + + runRestoreBotUserRoles(handle, ConnectionType.POSTGRES, "ingestion-bot"); + + verify(insertUserRole(handle, INSERT_USER_ROLE_POSTGRES, "user-1", "role-1")).execute(); + } + + @Test + void restoreBotUserRolesGivesApplicationBotWithoutRoleApplicationBotRole() { + Handle handle = + botRoleHandle("searchindexingapplicationbot", "user-2", "ApplicationBotRole", "role-2", 0); + + runRestoreBotUserRoles(handle, ConnectionType.POSTGRES, "SearchIndexingApplicationBot"); + + verify(insertUserRole(handle, INSERT_USER_ROLE_POSTGRES, "user-2", "role-2")).execute(); + } + + @Test + void restoreBotUserRolesLeavesApplicationBotThatHoldsAnotherRole() { + Handle handle = + botRoleHandle("narrowedapplicationbot", "user-3", "ApplicationBotRole", "role-2", 1); + + runRestoreBotUserRoles(handle, ConnectionType.POSTGRES, "NarrowedApplicationBot"); + + verify(insertUserRole(handle, INSERT_USER_ROLE_POSTGRES, "user-3", "role-2"), never()) + .execute(); + } + + @Test + void restoreBotUserRolesLeavesBotThatAlreadyHoldsItsDefaultRole() { + Handle handle = botRoleHandle("lineage-bot", "user-4", "LineageBotRole", "role-4", 1); + + runRestoreBotUserRoles(handle, ConnectionType.POSTGRES, "lineage-bot"); + + verify(insertUserRole(handle, INSERT_USER_ROLE_POSTGRES, "user-4", "role-4"), never()) + .execute(); + } + + @Test + void restoreBotUserRolesChecksAnyRoleWithHasRelationOnMysql() { + Handle handle = mock(Handle.class, RETURNS_DEEP_STUBS); + when(handle.createQuery(FIND_BOT_USER_MYSQL).bind("name", "profiler-bot").mapToMap().list()) + .thenReturn(List.of(Map.of("id", "user-5"))); + when(handle + .createQuery(CHECK_ROLE_EXISTS_MYSQL.replace("COUNT(*)", "id")) + .bind("name", "ProfilerBotRole") + .mapToMap() + .list()) + .thenReturn(List.of(Map.of("id", "role-5"))); + when(handle + .createQuery(ANY_USER_ROLE_QUERY) + .bind("userId", "user-5") + .bind("relation", 10) + .mapTo(Integer.class) + .one()) + .thenReturn(0); + + runRestoreBotUserRoles(handle, ConnectionType.MYSQL, "profiler-bot"); + + verify(insertUserRole(handle, INSERT_USER_ROLE_MYSQL, "user-5", "role-5")).execute(); + } + + @ParameterizedTest + @EnumSource(ConnectionType.class) + void restoreBotUserRolesLeavesBotWithAnyRoleOnEveryEngine(ConnectionType connectionType) { + Handle handle = mock(Handle.class, RETURNS_DEEP_STUBS); + boolean mysql = connectionType == ConnectionType.MYSQL; + String findUser = mysql ? FIND_BOT_USER_MYSQL : FIND_BOT_USER_POSTGRES; + String findRole = mysql ? CHECK_ROLE_EXISTS_MYSQL : CHECK_ROLE_EXISTS_POSTGRES; + String insert = mysql ? INSERT_USER_ROLE_MYSQL : INSERT_USER_ROLE_POSTGRES; + when(handle.createQuery(findUser).bind("name", "usage-bot").mapToMap().list()) + .thenReturn(List.of(Map.of("id", "user-6"))); + when(handle + .createQuery(findRole.replace("COUNT(*)", "id")) + .bind("name", "UsageBotRole") + .mapToMap() + .list()) + .thenReturn(List.of(Map.of("id", "role-6"))); + when(handle + .createQuery(ANY_USER_ROLE_QUERY) + .bind("userId", "user-6") + .bind("relation", 10) + .mapTo(Integer.class) + .one()) + .thenReturn(1); + + runRestoreBotUserRoles(handle, connectionType, "usage-bot"); + + verify(insertUserRole(handle, insert, "user-6", "role-6"), never()).execute(); + } + + private Handle botRoleHandle( + String userName, String userId, String roleName, String roleId, int roleCount) { + Handle handle = mock(Handle.class, RETURNS_DEEP_STUBS); + when(handle.createQuery(FIND_BOT_USER_POSTGRES).bind("name", userName).mapToMap().list()) + .thenReturn(List.of(Map.of("id", userId))); + when(handle + .createQuery(CHECK_ROLE_EXISTS_POSTGRES.replace("COUNT(*)", "id")) + .bind("name", roleName) + .mapToMap() + .list()) + .thenReturn(List.of(Map.of("id", roleId))); + when(handle + .createQuery(ANY_USER_ROLE_QUERY) + .bind("userId", userId) + .bind("relation", 10) + .mapTo(Integer.class) + .one()) + .thenReturn(roleCount); + return handle; + } + + private org.jdbi.v3.core.statement.Update insertUserRole( + Handle handle, String insert, String userId, String roleId) { + return handle + .createUpdate(insert) + .bind("userId", userId) + .bind("roleId", roleId) + .bind("relation", 10); + } + + private void runRestoreBotUserRoles( + Handle handle, ConnectionType connectionType, String botName) { + BotRepository botRepository = mock(BotRepository.class); + when(botRepository.listAll(any(), any(ListFilter.class))) + .thenReturn(List.of(new Bot().withName(botName))); + try (MockedStatic entity = mockStatic(Entity.class)) { + entity.when(() -> Entity.getEntityRepository(Entity.BOT)).thenReturn(botRepository); + MigrationUtil.restoreBotUserRolesIfMissing(handle, connectionType); + } + } + @Test void checkAndLogDataLossSymptomsHandlesCountsAndQueryFailuresGracefully() { Handle handle = mock(Handle.class, RETURNS_DEEP_STUBS); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyCsvCodecTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyCsvCodecTest.java index e697dcf01fd2..9b14dc81881d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyCsvCodecTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyCsvCodecTest.java @@ -487,7 +487,7 @@ void metadataIsRejectedOnInapplicableRowKinds() { @Test void previewRefusesPropertyMetadataTheKindCannotCarryNamingTheColumn() { final String dataOnly = - "Only data properties can define enum values, units or identifier intent"; + "Only data properties can define enum values, units, identifier intent or display-name intent"; assertEquals( "CSV row 2, column unit: " + dataOnly, previewErrorOf( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPagerRequestTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPagerRequestTest.java index 678bafa4bef4..f110487dd309 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPagerRequestTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/NativeOntologyDataGraphPagerRequestTest.java @@ -12,6 +12,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.macasaet.fernet.Key; @@ -173,6 +174,22 @@ void aClampedClusterPageAdvertisesTheOffsetAfterItsClampedRanks() { assertEquals(53, page.getNextClusterOffset()); } + @Test + void profileFactsAreComputedOnlyForTheClustersNotAlreadyLoaded() { + final var loaded = List.of(prefix(1, null)); + givenVisible(1, 2); + final var ranked = List.of(new ConceptAssetCount(id(1), 1), new ConceptAssetCount(id(2), 1)); + when(store.boundConcepts(ONTOLOGY, 2, 0)).thenReturn(ranked); + when(store.countBoundConcepts(ONTOLOGY)).thenReturn(2); + final var repeated = cluster(concept(1)); + final var fresh = cluster(concept(2)); + when(graph.clusters(any(), eq(ranked), eq(4))).thenReturn(List.of(repeated, fresh)); + final NativeOntologyDataGraphPage page = + pager().page(READER, ONTOLOGY, request(loaded, clusters(0, 2))); + assertEquals(1, page.getClusters().size()); + verify(graph).addProfileFacts(any(), eq(List.of(fresh))); + } + private NativeOntologyDataGraphPager pager() { return pager(CODEC); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyAggregateStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyAggregateStatementTest.java new file mode 100644 index 000000000000..a8aaf2d0379c --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyAggregateStatementTest.java @@ -0,0 +1,346 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.openmetadata.schema.api.data.OntologyStatementDirection.FORWARD; +import static org.openmetadata.schema.api.data.OntologyStatementDirection.INVERSE; +import static org.openmetadata.service.ontology.OntologyMappingShapeModel.plan; +import static org.openmetadata.service.ontology.OntologyMappingShapeModel.read; +import static org.openmetadata.service.ontology.OntologyMappingShapeModel.sql; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.FILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; + +import jakarta.ws.rs.ClientErrorException; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.RecordStatement; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.security.AuthorizationException; + +/** + * The counting statements: the number of records of a class, and the records of a class that + * relate to the most records along one relation. + */ +class OntologyAggregateStatementTest { + private static final String POSTGRES = "Postgres"; + + @Test + void aClassCountCountsTheDistinctKeysThatTheRowFilterKeeps() { + final RecordStatement count = + OntologyConceptSqlGenerator.count(model(FILTERED_IDENTITY, POSTGRES).mapped("Person")); + + assertEquals( + "SELECT COUNT(*) AS records\nFROM (\n SELECT DISTINCT t0.id AS k0\n" + + " FROM shop.parties t0\n WHERE t0.id IS NOT NULL\n AND t0.kind = 'person'\n" + + ") k\nLIMIT 1", + sql(count)); + assertEquals(List.of("0 count Person"), plan(count)); + assertEquals(List.of("parties"), read(count)); + assertEquals(1, count.rowCap()); + assertFalse(count.extraRow()); + } + + @Test + void aClassCountOverATwoColumnKeyCountsEachPairOnce() { + assertEquals( + "SELECT TOP 1 COUNT(*) AS records\nFROM (\n" + + " SELECT DISTINCT t0.[tenant_id] AS k0, t0.[customer_id] AS k1\n" + + " FROM [shop].[crm_customers] t0\n WHERE t0.[tenant_id] IS NOT NULL\n" + + " AND t0.[customer_id] IS NOT NULL\n) k", + sql(OntologyConceptSqlGenerator.count(model(COMPOSITE_KEY, "Mssql").mapped("Account")))); + } + + @Test + void aClassCountNeedsTheIdentityTableOfTheClass() { + final OntologyMappingShapeModel hidden = model(COMPOSITE_KEY, POSTGRES).hide("crm_customers"); + + assertEquals( + "The identity table of class https://example.org/compositeKey#Account is not visible to" + + " you", + assertThrows( + AuthorizationException.class, + () -> OntologyConceptSqlGenerator.count(hidden.mapped("Account"))) + .getMessage()); + } + + @Test + void aRelationCountRanksTheRecordsOfTheClassByTheRecordsTheyRelateTo() { + final RecordStatement top = + OntologyConceptSqlGenerator.top( + model(COLUMN_RELATION, "Mysql").path("Customer", "placedBy", INVERSE)); + + assertEquals( + "SELECT t0.`id`, t0.`name`, COUNT(*) AS records\nFROM `shop`.`customers` t0\n" + + "JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id`\n" + + "WHERE t0.`id` IS NOT NULL\n AND t1.`id` IS NOT NULL\n" + + "GROUP BY t0.`id`, t0.`name`\nORDER BY records DESC, t0.`id`\nLIMIT 8", + sql(top)); + assertEquals( + List.of("0 key Customer part 0", "1 displayName Customer customerName", "2 count Order"), + plan(top)); + assertEquals(List.of("customers", "orders"), read(top)); + assertEquals(8, top.rowCap()); + assertFalse(top.extraRow()); + } + + @Test + void aRelationCountThroughALinkTableKeepsTheRowFilterOfEveryTable() { + final RecordStatement top = + OntologyConceptSqlGenerator.top( + OntologyExpandStatementTest.filteredLinkTable("Mssql") + .path("Order", "contains", FORWARD)); + + assertEquals( + "SELECT TOP 8 t0.[id], COUNT(*) AS records\nFROM [shop].[orders] t0\n" + + "JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id]\n" + + "JOIN [shop].[products] t2 ON t2.[sku] = t1.[product_sku]\n" + + "WHERE t0.[id] IS NOT NULL\n AND t0.[channel] = N'web'\n AND t1.[quantity] > 0\n" + + " AND t2.[sku] IS NOT NULL\n AND t2.[title] <> N'Drill'\n" + + "GROUP BY t0.[id]\nORDER BY records DESC, t0.[id]", + sql(top)); + assertEquals(List.of("0 key Order part 0", "1 count Product"), plan(top)); + } + + @Test + void aRelationCountFollowsOnlyTheJoinThatExpandFollows() { + final OntologyMappingShapeModel model = model(LINK_TABLE, POSTGRES).delete("order_items"); + + final ClientErrorException refused = + assertThrows( + ClientErrorException.class, + () -> OntologyConceptSqlGenerator.top(model.path("Order", "contains", FORWARD))); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "Relation https://example.org/linkTable#contains has no join from class" + + " https://example.org/linkTable#Order to the identity table of class" + + " https://example.org/linkTable#Product", + refused.getMessage()); + } + + @Test + void aLinkCountOverAColumnCountsTheDistinctPairsOfAStartKeyAndTheColumnThatHoldsTheJoin() { + final RecordStatement links = + OntologyConceptSqlGenerator.links( + model(COLUMN_RELATION, "Mysql").path("Order", "placedBy", FORWARD)); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS r0\n" + + " FROM `shop`.`orders` t0\n" + + " WHERE t0.`id` IS NOT NULL\n" + + " AND t0.`customer_id` IS NOT NULL\n) k", + sql(links)); + assertEquals(List.of("0 count Customer"), plan(links)); + assertEquals(List.of("orders"), read(links)); + assertEquals(1, links.rowCap()); + assertFalse(links.extraRow()); + } + + @Test + void aLinkCountGoingBackJoinsTheClassThatHoldsTheColumnAndReadsItsKey() { + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.id AS k0, t1.id AS r0\n" + + " FROM shop.customers t0\n" + + " JOIN shop.orders t1 ON t1.customer_id = t0.id\n" + + " WHERE t0.id IS NOT NULL\n" + + " AND t1.id IS NOT NULL\n) k", + sql( + OntologyConceptSqlGenerator.links( + model(COLUMN_RELATION, POSTGRES).path("Customer", "placedBy", INVERSE)))); + } + + @Test + void aLinkCountGoingBackOverALinkTableJoinsTheIdentityTableOfTheClassThatBindsTheRelation() { + final RecordStatement forward = + OntologyConceptSqlGenerator.links( + model(LINK_TABLE, POSTGRES).path("Order", "contains", FORWARD)); + final RecordStatement inverse = + OntologyConceptSqlGenerator.links( + model(LINK_TABLE, POSTGRES).path("Product", "contains", INVERSE)); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0\n" + + " FROM shop.orders t0\n" + + " JOIN shop.order_items t1 ON t1.order_id = t0.id\n" + + " WHERE t0.id IS NOT NULL\n" + + " AND t1.product_sku IS NOT NULL\n) k", + sql(forward)); + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.sku AS k0, t2.id AS r0\n" + + " FROM shop.products t0\n" + + " JOIN shop.order_items t1 ON t1.product_sku = t0.sku\n" + + " JOIN shop.orders t2 ON t2.id = t1.order_id\n" + + " WHERE t0.sku IS NOT NULL\n" + + " AND t2.id IS NOT NULL\n) k", + sql(inverse)); + assertEquals(List.of("orders", "order_items"), read(forward)); + assertEquals(List.of("products", "order_items", "orders"), read(inverse)); + assertEquals(List.of("0 count Product"), plan(forward)); + assertEquals(List.of("0 count Order"), plan(inverse)); + } + + @Test + void + aLinkCountKeepsTheRowFilterOfTheClassThatBindsTheRelationAndOfALinkTableAndNeverOfTheObjectClass() { + final OntologyMappingShapeModel filtered = + OntologyExpandStatementTest.filteredLinkTable("Mssql"); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.[id] AS k0, t1.[product_sku] AS r0\n" + + " FROM [shop].[orders] t0\n" + + " JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id]\n" + + " WHERE t0.[id] IS NOT NULL\n" + + " AND t0.[channel] = N'web'\n" + + " AND t1.[product_sku] IS NOT NULL\n" + + " AND t1.[quantity] > 0\n) k", + sql(OntologyConceptSqlGenerator.links(filtered.path("Order", "contains", FORWARD)))); + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.[sku] AS k0, t2.[id] AS r0\n" + + " FROM [shop].[products] t0\n" + + " JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku]\n" + + " JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id]\n" + + " WHERE t0.[sku] IS NOT NULL\n" + + " AND t0.[title] <> N'Drill'\n" + + " AND t2.[id] IS NOT NULL\n" + + " AND t1.[quantity] > 0\n" + + " AND t2.[channel] = N'web'\n) k", + sql(OntologyConceptSqlGenerator.links(filtered.path("Product", "contains", INVERSE)))); + } + + @Test + void aLinkCountGoingBackOverAFilteredColumnKeepsTheRowFilterOfBothClasses() { + final OntologyMappingShapeModel parties = + new OntologyMappingShapeModel(OntologyLinkShapes.FILTERED_START, POSTGRES); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.id AS k0, t1.id AS r0\n" + + " FROM shop.parties t0\n" + + " JOIN shop.parties t1 ON t1.employer_id = t0.id\n" + + " WHERE t0.id IS NOT NULL\n" + + " AND t0.kind = 'organization'\n" + + " AND t1.id IS NOT NULL\n" + + " AND t1.kind = 'person'\n) k", + sql(OntologyConceptSqlGenerator.links(parties.path("Organization", "worksFor", INVERSE)))); + } + + @Test + void aLinkCountOverATableThatIsNoLinkTableKeepsItsRowFilterInBothDirections() { + final OntologyMappingShapeModel details = + new OntologyMappingShapeModel(OntologyLinkShapes.FILTERED_CONTRIBUTING, POSTGRES); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.id AS k0, t1.customer_id AS r0\n" + + " FROM shop.orders t0\n" + + " JOIN shop.order_details t1 ON t1.order_id = t0.id\n" + + " WHERE t0.id IS NOT NULL\n" + + " AND t0.channel = 'web'\n" + + " AND t1.customer_id IS NOT NULL\n" + + " AND t1.region = 'eu'\n) k", + sql(OntologyConceptSqlGenerator.links(details.path("Order", "placedBy", FORWARD)))); + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.id AS k0, t2.id AS r0\n" + + " FROM shop.customers t0\n" + + " JOIN shop.order_details t1 ON t1.customer_id = t0.id\n" + + " JOIN shop.orders t2 ON t2.id = t1.order_id\n" + + " WHERE t0.id IS NOT NULL\n" + + " AND t2.id IS NOT NULL\n" + + " AND t1.region = 'eu'\n" + + " AND t2.channel = 'web'\n) k", + sql(OntologyConceptSqlGenerator.links(details.path("Customer", "placedBy", INVERSE)))); + } + + @Test + void aLinkCountOverATwoColumnJoinNeedsEachColumnToBeSet() { + final OntologyMappingShapeModel branches = + new OntologyMappingShapeModel(OntologyLinkShapes.COMPOSITE_KEY, POSTGRES); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.id AS k0, t0.tenant AS r0, t0.branch AS r1\n" + + " FROM shop.employees t0\n" + + " WHERE t0.id IS NOT NULL\n" + + " AND t0.tenant IS NOT NULL\n" + + " AND t0.branch IS NOT NULL\n) k", + sql(OntologyConceptSqlGenerator.links(branches.path("Employee", "worksAt", FORWARD)))); + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.tenant_id AS k0, t0.branch_id AS k1, t1.id AS r0\n" + + " FROM shop.branches t0\n" + + " JOIN shop.employees t1 ON t1.tenant = t0.tenant_id AND t1.branch = t0.branch_id\n" + + " WHERE t0.tenant_id IS NOT NULL\n" + + " AND t0.branch_id IS NOT NULL\n" + + " AND t1.id IS NOT NULL\n) k", + sql(OntologyConceptSqlGenerator.links(branches.path("Branch", "worksAt", INVERSE)))); + } + + @Test + void aLinkCountOverALinkTableOfATwoColumnKeyJoinsTheOrderOnBothPairedColumns() { + final OntologyMappingShapeModel lines = + new OntologyMappingShapeModel(OntologyLinkShapes.COMPOSITE_LINK_TABLE, POSTGRES); + + assertEquals( + "SELECT COUNT(*) AS links\nFROM (\n" + + " SELECT DISTINCT t0.sku AS k0, t2.tenant AS r0, t2.order_no AS r1\n" + + " FROM shop.products t0\n" + + " JOIN shop.order_lines t1 ON t1.sku = t0.sku\n" + + " JOIN shop.orders t2 ON t2.tenant = t1.tenant AND t2.order_no = t1.order_no\n" + + " WHERE t0.sku IS NOT NULL\n" + + " AND t2.tenant IS NOT NULL\n" + + " AND t2.order_no IS NOT NULL\n) k", + sql(OntologyConceptSqlGenerator.links(lines.path("Product", "contains", INVERSE)))); + } + + @Test + void aLinkCountIsRefusedLikeTheRecordsThatRelateToTheMost() { + final OntologyMappingShapeModel missing = model(LINK_TABLE, POSTGRES).delete("order_items"); + final OntologyMappingShapeModel hidden = model(COLUMN_RELATION, POSTGRES).hide("customers"); + + final ClientErrorException noJoin = + assertThrows( + ClientErrorException.class, + () -> OntologyConceptSqlGenerator.links(missing.path("Order", "contains", FORWARD))); + + assertEquals(409, noJoin.getResponse().getStatus()); + assertEquals( + "Relation https://example.org/linkTable#contains has no join from class" + + " https://example.org/linkTable#Order to the identity table of class" + + " https://example.org/linkTable#Product", + noJoin.getMessage()); + assertEquals( + "The identity table of class https://example.org/columnRelation#Customer is not visible" + + " to you", + assertThrows( + AuthorizationException.class, + () -> OntologyConceptSqlGenerator.links(hidden.path("Order", "placedBy", FORWARD))) + .getMessage()); + } + + private static OntologyMappingShapeModel model(final Shape shape, final String serviceType) { + return new OntologyMappingShapeModel(shape, serviceType); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAccessLogTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAccessLogTest.java new file mode 100644 index 000000000000..e2fda52e59f6 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAccessLogTest.java @@ -0,0 +1,109 @@ +/* + * 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.ontology; + +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 static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.Database; +import org.openmetadata.schema.type.Include; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.util.EntityUtil.Fields; +import org.slf4j.LoggerFactory; + +class OntologyBindingAccessLogTest { + private final Authorizer authorizer = mock(Authorizer.class); + private final EntityRepository repository = mock(EntityRepository.class); + private final Access access = new Access(null, null); + private Logger logger; + private Level level; + private ListAppender appender; + + @BeforeEach + void setUp() { + logger = (Logger) LoggerFactory.getLogger(OntologyBindingAccess.class); + level = logger.getLevel(); + logger.setLevel(Level.DEBUG); + appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + when(repository.getEntityType()).thenReturn(Entity.DATABASE); + when(repository.getEntityClass()).thenReturn(Database.class); + when(repository.getFields(any(String.class))).thenReturn(new Fields(Set.of())); + } + + @AfterEach + void tearDown() { + logger.detachAppender(appender); + logger.setLevel(level); + } + + @Test + void aTargetHiddenFromTheReaderIsLoggedByCountAndNeverById() { + final Database first = new Database().withId(UUID.randomUUID()); + final Database second = new Database().withId(UUID.randomUUID()); + when(repository.get(any(), any(List.class), any(), any(Include.class))) + .thenReturn(List.of(first, second)); + doThrow(new AuthorizationException("denied")).when(authorizer).authorize(any(), any(), any()); + + final var viewable = + new OntologyBindingAccess(authorizer, type -> repository) + .viewable(access, Entity.DATABASE, List.of(first.getId(), second.getId())); + + assertTrue(viewable.isEmpty()); + assertEquals( + List.of("Binding target of type database: 2 of 2 are hidden from the reader"), messages()); + assertFalse(messages().toString().contains(first.getId().toString())); + } + + @Test + void aSingleTargetTheReaderCannotReadIsLoggedWithoutItsId() { + final UUID id = UUID.randomUUID(); + when(repository.get(any(), any(UUID.class), any(), any(Include.class), any(Boolean.class))) + .thenReturn(new Database().withId(id)); + doThrow(new AuthorizationException("denied")).when(authorizer).authorize(any(), any(), any()); + + final var readable = + new OntologyBindingAccess(authorizer, type -> repository) + .readable(access, Entity.DATABASE, id); + + assertTrue(readable.isEmpty()); + assertEquals( + List.of("A binding target of type database is unavailable to the current reader"), + messages()); + } + + private List messages() { + return appender.list.stream().map(ILoggingEvent::getFormattedMessage).toList(); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAndShapeOperationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAndShapeOperationTest.java new file mode 100644 index 000000000000..d1700570d034 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingAndShapeOperationTest.java @@ -0,0 +1,378 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.function.Consumer; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyChangeEvidence; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationState; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyColumnBindingChange; +import org.openmetadata.schema.type.OntologyJoinChange; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeBasis; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.utils.JsonUtils; + +/** The rules a change set applies to binding and shape operations whenever it is saved. */ +class OntologyBindingAndShapeOperationTest { + private static final UUID ONTOLOGY_ID = UUID.fromString("2ecf752a-956d-4a44-95ec-cce029f5c1d7"); + private static final UUID OPERATION_ID = UUID.fromString("7a1c0f5e-3f0b-4f43-9a5c-6a0d6de0b001"); + private static final UUID TABLE_ID = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0002"); + private static final UUID ORDERS_TABLE_ID = + UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0003"); + private static final URI CUSTOMER = URI.create("https://example.org/sales/Customer"); + private static final URI EMAIL = URI.create("https://example.org/sales/email"); + private static final URI PLACED = URI.create("https://example.org/sales/placed"); + private static final String REFUSED = "Ontology operation '" + OPERATION_ID + "' is invalid: "; + + @Test + void aDraftCarriesAClassAPropertyABindingAndAShape() { + final OntologyChangeSet draft = + draft( + classOperation(), + propertyOperation(), + binding(change -> {}), + shape(shape -> {}).withId(UUID.randomUUID())); + + OntologyChangeSetValidator.normalizeAndValidate(draft); + + assertEquals( + List.of( + OntologyChangeOperationState.ACTIVE, + OntologyChangeOperationState.ACTIVE, + OntologyChangeOperationState.ACTIVE, + OntologyChangeOperationState.ACTIVE), + draft.getOperations().stream().map(OntologyChangeOperation::getState).toList()); + } + + @Test + void aBindingOperationRequiresItsBindingAndNoOtherPayload() { + final OntologyChangeOperation missing = binding(change -> {}).withBinding(null); + final OntologyChangeOperation two = + binding(change -> {}).withConcept(classOperation().getConcept()); + + assertRefused(REFUSED + "operation UPSERT_BINDING requires exactly one binding", missing); + assertRefused(REFUSED + "operation UPSERT_BINDING requires exactly one binding", two); + } + + @Test + void aBindingOperationNamesItsTableInItsPayload() { + assertRefused( + REFUSED + "a binding operation names its table in its payload, not in targetId", + binding(change -> {}).withTargetId(TABLE_ID)); + assertRefused( + REFUSED + "a binding requires a tableId", binding(change -> change.setTableId(null))); + } + + @Test + void aBindingNamesItsClassAndPropertiesByAbsoluteIri() { + assertRefused( + REFUSED + "Ontology classIri must be an absolute IRI", + binding(change -> change.setClassIri(URI.create("Customer")))); + assertRefused( + REFUSED + "Ontology classIri must be an absolute IRI", + binding(change -> change.setClassIri(null))); + assertRefused( + REFUSED + "Ontology propertyIri must be an absolute IRI", + binding(change -> change.getColumns().getFirst().setPropertyIri(URI.create("email")))); + } + + @Test + void aBindingRevisionIsAWholeNumber() { + assertRefused( + REFUSED + "baseVersion is the whole binding revision the operation was built against", + binding(change -> {}).withBaseVersion(1.5)); + assertRefused( + REFUSED + "baseVersion is the whole binding revision the operation was built against", + binding(change -> {}).withBaseVersion(-1.0)); + + final OntologyChangeSet draft = draft(binding(change -> {}).withBaseVersion(3.0)); + OntologyChangeSetValidator.normalizeAndValidate(draft); + assertEquals(3L, OntologyBindingChanges.builtAgainst(draft.getOperations().getFirst())); + } + + @Test + void aBindingPassesTheRulesOfTheBindingsApiOnItsFields() { + assertRefused( + REFUSED + + "A role and a subject key are set together. A binding with a role names its key columns, and a binding without a role names none", + binding(change -> change.setSubjectKey(null))); + assertRefused( + REFUSED + "Duplicate property and column bindings are not allowed", + binding( + change -> + change.setColumns( + List.of(column(EMAIL, "email", null), column(EMAIL, "email", null))))); + assertRefused( + REFUSED + "A join requires a target table, a status and 1 to 16 distinct column pairs", + binding( + change -> + change.setColumns( + List.of( + column( + PLACED, + "customer_id", + new OntologyJoinChange() + .withTargetAssetId(ORDERS_TABLE_ID) + .withOn(List.of())))))); + assertRefused( + REFUSED + + "A row filter compares with a string of at most 1024 characters, a number or a boolean. `in` takes a list of 1 to 100 of them, and `isNull` and `isNotNull` take no value", + binding( + change -> + change.setRowFilter( + new OntologyRowFilter() + .withColumn(List.of("status")) + .withOperator(OntologyRowFilterOperator.IS_NULL) + .withValue("active")))); + assertRefused( + REFUSED + "Column paths require 1 to 32 nonblank name segments of at most 256 characters", + binding(change -> change.setSubjectKey(List.of(List.of(" "))))); + } + + @Test + void aDraftWritesEachBindingOnce() { + final OntologyChangeOperation second = binding(change -> {}).withId(UUID.randomUUID()); + final OntologyChangeOperation otherTable = + binding(change -> change.setTableId(ORDERS_TABLE_ID)).withId(UUID.randomUUID()); + + assertRefused("A native draft may write each binding only once", binding(change -> {}), second); + OntologyChangeSetValidator.normalizeAndValidate(draft(binding(change -> {}), otherTable)); + } + + @Test + void aShapeNamesItsTargetClassByAbsoluteIriAndPassesTheShapeRules() { + assertRefused( + REFUSED + "Ontology targetConcept must be an absolute IRI", + shape(shape -> shape.setTargetConcept(URI.create("Customer")))); + assertRefused( + REFUSED + + "/constraints/0: A constraint states at least one of minCount, maxCount, classIri, datatypeIri, minInclusive, maxInclusive, in or pattern", + shape( + shape -> + shape.setConstraints( + List.of(new OntologyShapeConstraint().withId("email").withPath(EMAIL))))); + } + + @Test + void onlyAShapeOperationCarriesABasis() { + assertRefused( + REFUSED + "only a shape operation carries a basis", + binding(change -> {}).withBasis(OntologyShapeBasis.OBSERVED)); + + final OntologyChangeSet draft = + draft(shape(shape -> {}).withBasis(OntologyShapeBasis.DECLARED)); + OntologyChangeSetValidator.normalizeAndValidate(draft); + assertEquals(OntologyShapeBasis.DECLARED, draft.getOperations().getFirst().getBasis()); + } + + @Test + void anEvidenceEntryNamesATableAndAKind() { + assertRefused( + REFUSED + "every evidence entry names a table and a kind", + binding(change -> {}) + .withEvidence( + List.of(new OntologyChangeEvidence().withKind(OntologyChangeEvidenceKind.NAME)))); + assertRefused( + REFUSED + "every evidence entry names a table and a kind", + binding(change -> {}) + .withEvidence(List.of(new OntologyChangeEvidence().withTableId(TABLE_ID)))); + } + + @Test + void anOperationCarriesEvidenceOfEveryKindInTheClosedList() { + final List kinds = + List.of( + "declaredKey", + "storedJoinCount", + "testCase", + "lineage", + "profile", + "name", + "sampleData", + "measured"); + assertEquals( + kinds, + Arrays.stream(OntologyChangeEvidenceKind.values()) + .map(OntologyChangeEvidenceKind::value) + .toList()); + final OntologyChangeSet draft = + draft( + binding(change -> {}) + .withEvidence( + kinds.stream() + .map( + kind -> + new OntologyChangeEvidence() + .withTableId(TABLE_ID) + .withColumns(List.of(List.of("customer_id"))) + .withKind(OntologyChangeEvidenceKind.fromValue(kind))) + .toList())); + + OntologyChangeSetValidator.normalizeAndValidate(draft); + + assertEquals( + kinds, + JsonUtils.readTree(JsonUtils.pojoToJson(draft.getOperations().getFirst())) + .path("evidence") + .findValuesAsText("kind")); + } + + @Test + void aSaveNeverStoresACountOfWithheldEvidence() { + final OntologyChangeSet draft = draft(binding(change -> {}).withWithheldEvidenceCount(4)); + + OntologyChangeSetValidator.normalizeAndValidate(draft); + + assertNull(draft.getOperations().getFirst().getWithheldEvidenceCount()); + } + + @Test + void anEmptyEvidenceListIsStoredAsNoEvidence() { + final OntologyChangeSet draft = draft(binding(change -> {}).withEvidence(List.of())); + + OntologyChangeSetValidator.normalizeAndValidate(draft); + + assertNull(draft.getOperations().getFirst().getEvidence()); + } + + @Test + void aGlossaryChangeSetTakesNoBindingOrShape() { + final OntologyChangeSet glossaryDraft = + new OntologyChangeSet() + .withGlossaries( + List.of(new EntityReference().withId(UUID.randomUUID()).withType("glossary"))) + .withOperations(List.of(binding(change -> {}))) + .withUndoCursor(1); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> OntologyChangeSetValidator.normalizeAndValidate(glossaryDraft)); + + assertEquals( + "Bindings and shapes must be authored in an ontology, not a glossary change set", + refusal.getMessage()); + } + + private static void assertRefused( + final String expected, final OntologyChangeOperation... operations) { + final OntologyChangeSet draft = draft(operations); + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> OntologyChangeSetValidator.normalizeAndValidate(draft)); + assertEquals(expected, refusal.getMessage()); + } + + private static OntologyChangeSet draft(final OntologyChangeOperation... operations) { + return new OntologyChangeSet() + .withOntology(ontology()) + .withBaseWorkingRevision(0L) + .withOperations(List.of(operations)) + .withUndoCursor(operations.length); + } + + private static EntityReference ontology() { + return new EntityReference().withId(ONTOLOGY_ID).withType("ontology"); + } + + private static OntologyChangeOperation classOperation() { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_CONCEPT) + .withConcept( + new OntologyConcept() + .withId(UUID.randomUUID()) + .withName("Customer") + .withIri(CUSTOMER) + .withOntology(ontology())); + } + + private static OntologyChangeOperation propertyOperation() { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_PROPERTY) + .withProperty( + new OntologyProperty() + .withId(UUID.randomUUID()) + .withName("email") + .withIri(EMAIL) + .withKind(OntologyPropertyKind.DATA) + .withOntology(ontology())); + } + + /** An identity binding of the customer table, changed by {@code edit} before it is sent. */ + private static OntologyChangeOperation binding(final Consumer edit) { + final OntologyBindingChange change = + new OntologyBindingChange() + .withClassIri(CUSTOMER) + .withTableId(TABLE_ID) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of("customer_id"))) + .withColumns(List.of(column(EMAIL, "email", null))); + edit.accept(change); + return new OntologyChangeOperation() + .withId(OPERATION_ID) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBinding(change); + } + + private static OntologyColumnBindingChange column( + final URI propertyIri, final String column, final OntologyJoinChange join) { + return new OntologyColumnBindingChange() + .withPropertyIri(propertyIri) + .withColumnPath(List.of(column)) + .withJoin(join); + } + + /** A shape on the customer class, changed by {@code edit} before it is sent. */ + private static OntologyChangeOperation shape(final Consumer edit) { + final OntologyShape shape = + new OntologyShape() + .withId(UUID.randomUUID()) + .withName("CustomerShape") + .withOntology(ontology()) + .withTargetConcept(CUSTOMER) + .withConstraints( + List.of( + new OntologyShapeConstraint().withId("email").withPath(EMAIL).withMinCount(1))); + edit.accept(shape); + return new OntologyChangeOperation() + .withId(OPERATION_ID) + .withOperationType(OntologyChangeOperationType.UPSERT_SHAPE) + .withShape(shape); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutorTest.java new file mode 100644 index 000000000000..4ea26d44b8ac --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingChangeExecutorTest.java @@ -0,0 +1,112 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.net.URI; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.service.exception.PreconditionFailedException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; + +/** Which binding revision a binding operation must have been built against to be written. */ +class OntologyBindingChangeExecutorTest { + private static final UUID OPERATION_ID = UUID.fromString("7a1c0f5e-3f0b-4f43-9a5c-6a0d6de0b001"); + private static final UUID TABLE_ID = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0002"); + private static final UUID CLASS_ID = UUID.fromString("5b0e7a52-9d1c-4f0e-b7a1-2c3d4e5f0003"); + private static final BindingRow BOUND = + new BindingRow( + UUID.randomUUID(), TABLE_ID, OntologyBindingAssetType.TABLE, "hash", List.of()); + private static final String STALE = + "The binding of class https://example.org/sales/Customer to table " + + TABLE_ID + + " changed since operation '" + + OPERATION_ID + + "' was built: the operation carries "; + + @Test + void anOperationBuiltAgainstTheCurrentRevisionCommitsTheNextOne() { + assertEquals(4L, guard(3.0).next(3L, BOUND)); + assertEquals(1L, guard(0.0).next(0L, null)); + } + + @Test + void anOperationThatBindsANewTableCarriesNoRevision() { + assertEquals(8L, guard(null).next(7L, null)); + } + + @Test + void aSetThatWritesTwoBindingsOfOneClassIsJudgedAgainstTheRevisionBeforeItsFirstWrite() { + final Map revisionsBefore = new HashMap<>(); + + assertEquals(4L, guard(3.0, revisionsBefore).next(3L, BOUND)); + assertEquals(5L, guard(3.0, revisionsBefore).next(4L, BOUND)); + assertEquals(6L, guard(null, revisionsBefore).next(5L, null)); + final PreconditionFailedException refusal = + assertThrows( + PreconditionFailedException.class, () -> guard(2.0, revisionsBefore).next(6L, BOUND)); + + assertEquals( + STALE + "binding revision 2 and the class is at binding revision 3", refusal.getMessage()); + } + + @Test + void anOperationBuiltAgainstAnEarlierRevisionIsRefusedWithItsBindingNamed() { + final PreconditionFailedException refusal = + assertThrows(PreconditionFailedException.class, () -> guard(3.0).next(4L, BOUND)); + + assertEquals( + STALE + "binding revision 3 and the class is at binding revision 4", refusal.getMessage()); + assertEquals(412, refusal.getResponse().getStatus()); + } + + @Test + void anOperationBuiltBeforeItsTableWasBoundIsRefusedOnceTheTableIsBound() { + final PreconditionFailedException refusal = + assertThrows(PreconditionFailedException.class, () -> guard(null).next(2L, BOUND)); + + assertEquals( + STALE + "no binding revision and the class is at binding revision 2", refusal.getMessage()); + assertEquals(412, refusal.getResponse().getStatus()); + } + + /** The guard of an operation that is the first of its set to write to the class. */ + private static OntologyConceptBindingService.RevisionGuard guard(final Double builtAgainst) { + return guard(builtAgainst, new HashMap<>()); + } + + private static OntologyConceptBindingService.RevisionGuard guard( + final Double builtAgainst, final Map revisionsBefore) { + return OntologyBindingChangeExecutor.revisionGuard( + new OntologyChangeOperation() + .withId(OPERATION_ID) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBaseVersion(builtAgainst) + .withBinding( + new OntologyBindingChange() + .withClassIri(URI.create("https://example.org/sales/Customer")) + .withTableId(TABLE_ID)), + CLASS_ID, + revisionsBefore); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingRulesTest.java index 9082e82e5c75..b23266dcf57d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingRulesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyBindingRulesTest.java @@ -10,7 +10,9 @@ import jakarta.ws.rs.ClientErrorException; import java.net.URI; +import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.IntStream; @@ -23,12 +25,34 @@ import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyAssetBinding; import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; class OntologyBindingRulesTest { private static final long MAX_REVISION = 9_007_199_254_740_991L; + private static final String ROLE_AND_KEY = + "A role and a subject key are set together. A binding with a role names its key columns, and a binding without a role names none"; + private static final String KEY_SIZE = "A subject key takes 1 to 16 distinct columns"; + private static final String COLUMN_PATH = + "Column paths require 1 to 32 nonblank name segments of at most 256 characters"; + private static final String TABLES_ONLY = + "Only table bindings take a role, a subject key or a row filter"; + private static final String FILTER_VALUE = + "A row filter compares with a string of at most 1024 characters, a number or a boolean. `in` takes a list of 1 to 100 of them, and `isNull` and `isNotNull` take no value"; + private static final String FILTER_SHAPE = + "A row filter requires a column and a supported operator"; + private static final String JOIN_SHAPE = + "A join requires a target table, a status and 1 to 16 distinct column pairs"; + private static final String DUPLICATE_COLUMNS = + "Duplicate property and column bindings are not allowed"; @Test void staleChangedWritesConflictAndTheRevisionAdvancesByOne() { @@ -149,6 +173,214 @@ void rejectsMalformedAndOversizedAssociations() { } } + @Test + void aRoleAndASubjectKeyAreSetTogether() { + assertDoesNotThrow(() -> OntologyBindingRules.validate(identity(key("tenant"), key("id")))); + assertDoesNotThrow( + () -> + OntologyBindingRules.validate( + asset().withRole(OntologyBindingRole.CONTRIBUTING).withSubjectKey(keys(16)))); + assertRejected(ROLE_AND_KEY, asset().withRole(OntologyBindingRole.IDENTITY)); + assertRejected( + ROLE_AND_KEY, asset().withRole(OntologyBindingRole.IDENTITY).withSubjectKey(List.of())); + assertRejected(ROLE_AND_KEY, asset().withSubjectKey(List.of(key("id")))); + assertRejected(KEY_SIZE, identity(key("id"), key("id"))); + assertRejected( + KEY_SIZE, asset().withRole(OntologyBindingRole.IDENTITY).withSubjectKey(keys(17))); + assertRejected(COLUMN_PATH, identity(key(" "))); + assertRejected(COLUMN_PATH, identity(List.of())); + } + + @Test + void onlyATableBindingTakesARoleAKeyOrAFilter() { + final var dashboard = asset().withAssetType(OntologyBindingAssetType.DASHBOARD); + assertDoesNotThrow(() -> OntologyBindingRules.validate(dashboard)); + assertRejected( + TABLES_ONLY, identity(key("id")).withAssetType(OntologyBindingAssetType.DASHBOARD)); + assertRejected( + TABLES_ONLY, + asset() + .withAssetType(OntologyBindingAssetType.TOPIC) + .withRowFilter(filter(OntologyRowFilterOperator.IS_NULL, null))); + } + + @Test + void aRowFilterTakesTheValueItsOperatorNeeds() { + for (final Object value : List.of("DELETED", "", 7, 2.5, true, "x".repeat(1024))) { + assertDoesNotThrow( + () -> OntologyBindingRules.validate(filtered(OntologyRowFilterOperator.EQUALS, value))); + } + for (final Object value : List.of("x".repeat(1025), "a\u0000b", List.of("a"), Map.of("a", 1))) { + assertRejected(FILTER_VALUE, filtered(OntologyRowFilterOperator.NOT_EQUALS, value)); + } + for (final var comparison : + List.of( + OntologyRowFilterOperator.EQUALS, + OntologyRowFilterOperator.NOT_EQUALS, + OntologyRowFilterOperator.LESS_THAN, + OntologyRowFilterOperator.LESS_THAN_OR_EQUALS, + OntologyRowFilterOperator.GREATER_THAN, + OntologyRowFilterOperator.GREATER_THAN_OR_EQUALS)) { + assertDoesNotThrow(() -> OntologyBindingRules.validate(filtered(comparison, 10))); + assertRejected(FILTER_VALUE, filtered(comparison, null)); + } + } + + @Test + void aListFilterTakesOneToAHundredValuesAndANullCheckTakesNone() { + assertDoesNotThrow( + () -> + OntologyBindingRules.validate( + filtered(OntologyRowFilterOperator.IN, List.of("EU", 44, false)))); + assertDoesNotThrow( + () -> + OntologyBindingRules.validate( + filtered(OntologyRowFilterOperator.IN, Collections.nCopies(100, "EU")))); + for (final Object value : + List.of( + "EU", + List.of(), + Collections.nCopies(101, "EU"), + List.of(List.of("EU")), + List.of("a\u0000b"))) { + assertRejected(FILTER_VALUE, filtered(OntologyRowFilterOperator.IN, value)); + } + assertRejected(FILTER_VALUE, filtered(OntologyRowFilterOperator.IN, null)); + for (final var check : + List.of(OntologyRowFilterOperator.IS_NULL, OntologyRowFilterOperator.IS_NOT_NULL)) { + assertDoesNotThrow(() -> OntologyBindingRules.validate(filtered(check, null))); + assertRejected(FILTER_VALUE, filtered(check, "x")); + } + } + + @Test + void aRowFilterNamesOneColumnAndOneOperator() { + assertRejected(FILTER_SHAPE, filtered(null, "x")); + assertRejected( + COLUMN_PATH, + asset() + .withRowFilter( + new OntologyRowFilter() + .withOperator(OntologyRowFilterOperator.IS_NULL) + .withColumn(List.of()))); + assertRejected( + COLUMN_PATH, + asset() + .withRowFilter( + new OntologyRowFilter() + .withOperator(OntologyRowFilterOperator.EQUALS) + .withColumn(List.of("status", " ")) + .withValue("x"))); + } + + @Test + void aJoinNamesItsTargetItsStatusAndItsColumnPairs() { + assertDoesNotThrow( + () -> OntologyBindingRules.validate(joined(join(pair("customer_id", "id"))))); + assertDoesNotThrow(() -> OntologyBindingRules.validate(joined(join(pairs(16))))); + assertRejected(JOIN_SHAPE, joined(join(pair("customer_id", "id")).withTargetAssetId(null))); + assertRejected(JOIN_SHAPE, joined(join(pair("customer_id", "id")).withStatus(null))); + assertRejected(JOIN_SHAPE, joined(join())); + assertRejected(JOIN_SHAPE, joined(join(pairs(17)))); + assertRejected(JOIN_SHAPE, joined(join(pair("customer_id", "id"), pair("customer_id", "id")))); + assertRejected(COLUMN_PATH, joined(join(pair("customer_id", " ")))); + assertRejected(COLUMN_PATH, joined(join(pair("", "id")))); + } + + @Test + void aRelationColumnNeedsAJoinAndADataColumnTakesNone() { + final var relation = new OntologyProperty().withKind(OntologyPropertyKind.OBJECT); + final var attribute = new OntologyProperty().withKind(OntologyPropertyKind.DATA); + final var withJoin = column().withJoin(join(pair("customer_id", "id"))); + assertDoesNotThrow(() -> OntologyBindingRules.requireJoinFor(relation, withJoin)); + assertDoesNotThrow(() -> OntologyBindingRules.requireJoinFor(attribute, column())); + assertEquals( + "A column bound to an OBJECT property requires a join to the table that holds the related records", + assertThrows( + BadRequestException.class, + () -> OntologyBindingRules.requireJoinFor(relation, column())) + .getMessage()); + assertEquals( + "Only a column bound to an OBJECT property takes a join", + assertThrows( + BadRequestException.class, + () -> OntologyBindingRules.requireJoinFor(attribute, withJoin)) + .getMessage()); + } + + @Test + void onePropertyBoundTwiceToOneColumnIsADuplicateWhateverItsJoin() { + final var plain = column(); + final var joined = + new OntologyColumnBinding() + .withPropertyId(plain.getPropertyId()) + .withColumnPath(plain.getColumnPath()) + .withJoin(join(pair("value", "id"))); + assertRejected(DUPLICATE_COLUMNS, asset().withColumns(List.of(plain, joined))); + } + + @Test + void aWriteThatRepeatsTheStoredBindingIsTheSameBinding() { + final var relation = column().withJoin(join(pair("customer_id", "id"))); + final var requested = + identity(key("tenant"), key("id")) + .withRowFilter(filter(OntologyRowFilterOperator.NOT_EQUALS, "DELETED")) + .withColumns(List.of(relation)); + final var stored = + new BindingRow( + UUID.randomUUID(), + requested.getAssetId(), + OntologyBindingAssetType.TABLE, + "hash", + List.of(relation), + OntologyBindingRole.IDENTITY, + List.of(key("tenant"), key("id")), + filter(OntologyRowFilterOperator.NOT_EQUALS, "DELETED")); + assertTrue(OntologyBindingRules.sameBinding(stored, requested)); + assertFalse( + OntologyBindingRules.sameBinding( + stored, copy(requested).withRole(OntologyBindingRole.CONTRIBUTING))); + assertFalse( + OntologyBindingRules.sameBinding( + stored, copy(requested).withSubjectKey(List.of(key("id"), key("tenant"))))); + assertFalse( + OntologyBindingRules.sameBinding( + stored, + copy(requested) + .withRowFilter(filter(OntologyRowFilterOperator.NOT_EQUALS, "ARCHIVED")))); + assertFalse(OntologyBindingRules.sameBinding(stored, copy(requested).withRowFilter(null))); + final var confirmed = + new OntologyColumnBinding() + .withPropertyId(relation.getPropertyId()) + .withColumnPath(relation.getColumnPath()) + .withJoin( + join(pair("customer_id", "id")) + .withTargetAssetId(relation.getJoin().getTargetAssetId()) + .withStatus(OntologyJoinStatus.CONFIRMED)); + assertFalse( + OntologyBindingRules.sameBinding(stored, copy(requested).withColumns(List.of(confirmed)))); + } + + @Test + void aRowWrittenBeforeRolesExistedEqualsARequestThatAssignsNothing() { + final var requested = asset(); + final var stored = + new BindingRow( + UUID.randomUUID(), + requested.getAssetId(), + OntologyBindingAssetType.TABLE, + "hash", + List.of()); + assertTrue(OntologyBindingRules.sameBinding(stored, requested)); + assertTrue(OntologyBindingRules.sameBinding(stored, copy(requested).withSubjectKey(null))); + assertFalse( + OntologyBindingRules.sameBinding( + stored, + copy(requested) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(key("id"))))); + } + @Test void revisionMustBePresentAndExactlyRepresentable() { for (final Long invalid : new Long[] {null, -1L, MAX_REVISION + 1}) { @@ -173,4 +405,68 @@ private static OntologyColumnBinding column() { private static List columns(int count) { return IntStream.range(0, count).mapToObj(index -> column()).toList(); } + + private static void assertRejected(final String message, final OntologyAssetBinding asset) { + assertEquals( + message, + assertThrows(BadRequestException.class, () -> OntologyBindingRules.validate(asset)) + .getMessage()); + } + + @SafeVarargs + private static OntologyAssetBinding identity(final List... key) { + return asset().withRole(OntologyBindingRole.IDENTITY).withSubjectKey(List.of(key)); + } + + private static List key(final String column) { + return List.of(column); + } + + private static List> keys(final int count) { + return IntStream.range(0, count).mapToObj(index -> key("k" + index)).toList(); + } + + private static OntologyRowFilter filter( + final OntologyRowFilterOperator operator, final Object value) { + return new OntologyRowFilter() + .withColumn(List.of("status")) + .withOperator(operator) + .withValue(value); + } + + private static OntologyAssetBinding filtered( + final OntologyRowFilterOperator operator, final Object value) { + return asset().withRowFilter(filter(operator, value)); + } + + private static OntologyAssetBinding joined(final OntologyColumnJoin join) { + return asset().withColumns(List.of(column().withJoin(join))); + } + + private static OntologyColumnJoin join(final OntologyJoinColumnPair... pairs) { + return new OntologyColumnJoin() + .withTargetAssetId(UUID.randomUUID()) + .withStatus(OntologyJoinStatus.INFERRED) + .withOn(List.of(pairs)); + } + + private static OntologyJoinColumnPair pair(final String child, final String parent) { + return new OntologyJoinColumnPair().withChild(List.of(child)).withParent(List.of(parent)); + } + + private static OntologyJoinColumnPair[] pairs(final int count) { + return IntStream.range(0, count) + .mapToObj(index -> pair("c" + index, "p" + index)) + .toArray(OntologyJoinColumnPair[]::new); + } + + private static OntologyAssetBinding copy(final OntologyAssetBinding asset) { + return new OntologyAssetBinding() + .withAssetId(asset.getAssetId()) + .withAssetType(asset.getAssetType()) + .withColumns(asset.getColumns()) + .withRole(asset.getRole()) + .withSubjectKey(asset.getSubjectKey()) + .withRowFilter(asset.getRowFilter()); + } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeApplicationServiceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeApplicationServiceTest.java index abac8f716d9e..dd2979cf8189 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeApplicationServiceTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeApplicationServiceTest.java @@ -30,12 +30,17 @@ import jakarta.ws.rs.BadRequestException; import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.SecurityContext; import jakarta.ws.rs.core.UriInfo; +import java.net.URI; +import java.security.Principal; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.List; import java.util.UUID; +import java.util.function.Function; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -45,17 +50,21 @@ import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.EventType; import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.OntologyBindingChange; import org.openmetadata.schema.type.OntologyChangeApplicationResult; import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeOperationResult; import org.openmetadata.schema.type.OntologyChangeOperationResultStatus; import org.openmetadata.schema.type.OntologyChangeOperationType; import org.openmetadata.schema.type.OntologyChangeSetState; +import org.openmetadata.service.exception.PreconditionFailedException; import org.openmetadata.service.jdbi3.OntologyChangeSetRepository; +import org.openmetadata.service.ontology.OntologyChangeApplicationService.BindingWriter; import org.openmetadata.service.ontology.OntologyChangeApplicationService.ChangeTransaction; import org.openmetadata.service.ontology.OntologyChangeApplicationService.Dependencies; import org.openmetadata.service.ontology.OntologyChangeApplicationService.EntityCacheInvalidator; import org.openmetadata.service.ontology.OntologyChangeOperationExecutor.OperationOutcome; +import org.openmetadata.service.ontology.OntologyConceptBindingService.Access; import org.openmetadata.service.util.RestUtil.PutResponse; class OntologyChangeApplicationServiceTest { @@ -73,6 +82,9 @@ class OntologyChangeApplicationServiceTest { private final EntityCacheInvalidator cacheInvalidator = mock(EntityCacheInvalidator.class); private final Clock clock = Clock.fixed(Instant.ofEpochMilli(NOW), ZoneOffset.UTC); private final OntologyChangeOperation operation = operation(); + private final List bindingWrites = new ArrayList<>(); + private BindingWriter bindingWriter = this::recordingAttempt; + private int bindingAttempts; private OntologyChangeSet changeSet; private OntologyChangeApplicationService service; @@ -107,7 +119,8 @@ void setUp() { OntologyPackCatalog.bundled(), null, (install, user) -> {}, - (jobId, ontologyId) -> null); + (jobId, ontologyId) -> null, + (caller, applied) -> bindingWriter.attempt(caller, applied)); service = new OntologyChangeApplicationService(repository, dependencies, clock); } @@ -204,6 +217,122 @@ void retriesEveryOperationAfterAnAtomicFailure() { verify(executor).execute(uriInfo, USER, operation); } + @Test + void writesABindingAsTheCallerWhoAppliesInsideTheTransaction() { + final OntologyChangeOperation binding = bindingOperation(); + final UUID ontologyId = nativeDraftOf(binding); + final Access caller = caller(); + + final OntologyChangeSet applied = service.apply(caller, changeSetId).getEntity(); + + assertEquals(OntologyChangeSetState.APPLIED, applied.getState()); + assertEquals(List.of(new BindingWrite(caller, ontologyId, binding, true)), bindingWrites); + assertEquals( + List.of(OntologyChangeOperationResultStatus.APPLIED), + applied.getApplicationResult().getResults().stream() + .map(OntologyChangeOperationResult::getStatus) + .toList()); + assertEquals(USER, applied.getApplicationResult().getAppliedBy()); + verify(executor, never()).execute(any(), any(), any()); + } + + @Test + void aRefusedBindingAnswersTheApplyAndRecordsNoFailedApplication() { + nativeDraftOf(bindingOperation()); + bindingWriter = + (caller, applied) -> + written -> { + throw new PreconditionFailedException("the binding changed"); + }; + + final PreconditionFailedException refused = + assertThrows(PreconditionFailedException.class, () -> service.apply(caller(), changeSetId)); + + assertEquals("the binding changed", refused.getMessage()); + assertEquals(OntologyChangeSetState.DRAFT, changeSet.getState()); + assertFalse(transaction.isActive()); + verify(repository, never()).transition(any(), any(), any(), any(), any()); + verify(eventPublisher, never()).publish(any(), any(), any()); + } + + @Test + void eachRunOfTheTransactionStartsItsOwnBindingWrites() { + final OntologyChangeOperation binding = bindingOperation(); + final UUID ontologyId = nativeDraftOf(binding); + final Access caller = caller(); + transaction.runTwiceAsAfterADeadlock(); + + final OntologyChangeSet applied = service.apply(caller, changeSetId).getEntity(); + + assertEquals(2, bindingAttempts); + assertEquals( + List.of( + new BindingWrite(caller, ontologyId, binding, true), + new BindingWrite(caller, ontologyId, binding, true)), + bindingWrites); + assertEquals(1, applied.getApplicationResult().getResults().size()); + } + + @Test + void anApplyWithNoCallerWritesNoBinding() { + final OntologyChangeOperation binding = bindingOperation(); + nativeDraftOf(binding); + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> service.apply(uriInfo, changeSetId, USER)); + + assertEquals( + "Ontology operation '" + + binding.getId() + + "' writes a binding, which only a caller of the change set API can apply", + refused.getMessage()); + assertEquals(List.of(), bindingWrites); + verify(repository, never()).transition(any(), any(), any(), any(), any()); + } + + /** Turns the draft into one of an ontology that holds this one operation, and returns its id. */ + private UUID nativeDraftOf(final OntologyChangeOperation only) { + final UUID ontologyId = UUID.randomUUID(); + changeSet.setGlossaries(List.of()); + changeSet.setOntology(new EntityReference().withId(ontologyId).withType("ontology")); + changeSet.setBaseWorkingRevision(0L); + changeSet.setOperations(List.of(only)); + when(executor.inScope(eq(changeSet), any())) + .thenAnswer(invocation -> invocation.>getArgument(1).get()); + return ontologyId; + } + + private Access caller() { + final SecurityContext securityContext = mock(SecurityContext.class); + final Principal principal = mock(Principal.class); + when(principal.getName()).thenReturn(USER); + when(securityContext.getUserPrincipal()).thenReturn(principal); + return new Access(uriInfo, securityContext); + } + + private Function recordingAttempt( + final Access caller, final OntologyChangeSet applied) { + bindingAttempts++; + return written -> { + bindingWrites.add( + new BindingWrite(caller, applied.getOntology().getId(), written, transaction.isActive())); + return new OperationOutcome(new EntityReference().withId(UUID.randomUUID()), null); + }; + } + + private record BindingWrite( + Access caller, UUID ontologyId, OntologyChangeOperation operation, boolean inTransaction) {} + + private static OntologyChangeOperation bindingOperation() { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBinding( + new OntologyBindingChange() + .withClassIri(URI.create("https://example.org/sales/Customer")) + .withTableId(UUID.randomUUID())); + } + private OntologyChangeSet changeSet(final OntologyChangeApplicationResult result) { return new OntologyChangeSet() .withId(changeSetId) @@ -233,21 +362,29 @@ private static PutResponse response(final OntologyChangeSet c private static final class RecordingTransaction implements ChangeTransaction { private boolean active; private int executionCount; + private int runs = 1; @Override public PutResponse execute( final Supplier> work) { - PutResponse result; + PutResponse result = null; active = true; executionCount++; try { - result = work.get(); + for (int run = 0; run < runs; run++) { + result = work.get(); + } } finally { active = false; } return result; } + /** A transaction that loses a deadlock rolls back and runs its work again. */ + private void runTwiceAsAfterADeadlock() { + runs = 2; + } + private boolean isActive() { return active; } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEventPublisherTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEventPublisherTest.java index 8342983ed552..db1f07bccab0 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEventPublisherTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEventPublisherTest.java @@ -14,6 +14,7 @@ package org.openmetadata.service.ontology; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.time.Clock; import java.time.Instant; @@ -23,8 +24,11 @@ import java.util.UUID; import org.junit.jupiter.api.Test; import org.openmetadata.schema.entity.data.Glossary; +import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.type.ChangeEvent; import org.openmetadata.schema.type.EventType; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.utils.JsonUtils; class OntologyChangeEventPublisherTest { @@ -50,4 +54,31 @@ void publishesTypedOntologyEventsWithEntityContext() { assertEquals("steward", event.getUserName()); assertEquals(1234, event.getTimestamp()); } + + @Test + void anAppliedChangeSetEventHoldsNoOperations() { + final List storedEvents = new ArrayList<>(); + final UUID tableId = UUID.randomUUID(); + final OntologyChangeSet changeSet = + new OntologyChangeSet() + .withId(UUID.randomUUID()) + .withName("draft") + .withFullyQualifiedName("draft") + .withVersion(0.2) + .withOperations( + List.of( + new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withBinding(new OntologyBindingChange().withTableId(tableId)))); + + new OntologyChangeEventPublisher(storedEvents::add, Clock.systemUTC()) + .publish(EventType.ONTOLOGY_CHANGE_SET_APPLIED, changeSet, "steward"); + + final ChangeEvent event = JsonUtils.readValue(storedEvents.getFirst(), ChangeEvent.class); + assertEquals(EventType.ONTOLOGY_CHANGE_SET_APPLIED, event.getEventType()); + assertEquals("ontologyChangeSet", event.getEntityType()); + assertFalse(storedEvents.getFirst().contains(tableId.toString())); + assertFalse(storedEvents.getFirst().contains("operations")); + assertEquals("draft", JsonUtils.readTree(storedEvents.getFirst()).at("/entity/name").asText()); + } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java new file mode 100644 index 000000000000..d88eb8c6358e --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeEvidenceViewTest.java @@ -0,0 +1,306 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import jakarta.ws.rs.BadRequestException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.type.OntologyChangeEvidence; +import org.openmetadata.schema.type.OntologyChangeEvidenceKind; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.exception.PreconditionFailedException; +import org.openmetadata.service.secrets.masker.MaskedFields; + +/** Evidence as a reader sees it, what a save by that reader stores, and what no reader is sent. */ +class OntologyChangeEvidenceViewTest { + private static final UUID OPERATION_ID = UUID.fromString("7a1c0f5e-3f0b-4f43-9a5c-6a0d6de0b001"); + private static final UUID SHOWN = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0002"); + private static final UUID HIDDEN = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0003"); + + private final List> lookups = new ArrayList<>(); + private final OntologyChangeEvidenceView view = + new OntologyChangeEvidenceView( + tableIds -> { + lookups.add(tableIds); + final Set viewable = new HashSet<>(tableIds); + viewable.retainAll(Set.of(SHOWN)); + return viewable; + }); + + @Test + void aReaderSeesOnlyTheEvidenceOfTablesTheReaderMayView() { + final OntologyChangeSet changeSet = + changeSet( + operation(OPERATION_ID, name(SHOWN), profile(HIDDEN), lineage(SHOWN)), + operation(UUID.randomUUID())); + + view.apply(changeSet); + + final OntologyChangeOperation supported = changeSet.getOperations().getFirst(); + final OntologyChangeOperation unsupported = changeSet.getOperations().getLast(); + assertEquals(List.of(name(SHOWN), lineage(SHOWN)), supported.getEvidence()); + assertEquals(1, supported.getWithheldEvidenceCount()); + assertNull(unsupported.getEvidence()); + assertNull(unsupported.getWithheldEvidenceCount()); + } + + @Test + void aReaderWhoMayViewEveryTableSeesEveryEntryAndACountOfZero() { + final OntologyChangeSet changeSet = + changeSet(operation(OPERATION_ID, name(SHOWN), lineage(SHOWN))); + + view.apply(changeSet); + + final OntologyChangeOperation operation = changeSet.getOperations().getFirst(); + assertEquals(List.of(name(SHOWN), lineage(SHOWN)), operation.getEvidence()); + assertEquals(0, operation.getWithheldEvidenceCount()); + } + + @ParameterizedTest + @EnumSource(OntologyChangeEvidenceKind.class) + void evidenceOfEachKindIsWithheldWhenItsTableIsHidden(final OntologyChangeEvidenceKind kind) { + final OntologyChangeSet changeSet = + changeSet(operation(OPERATION_ID, entry(HIDDEN, kind), entry(SHOWN, kind))); + + view.apply(changeSet); + + final OntologyChangeOperation operation = changeSet.getOperations().getFirst(); + assertEquals(List.of(entry(SHOWN, kind)), operation.getEvidence()); + assertEquals(1, operation.getWithheldEvidenceCount()); + } + + @Test + void aRecordedChangeHoldsTheOperationsWithNoEvidence() { + final OntologyChangeOperation supported = operation(OPERATION_ID, name(SHOWN), profile(HIDDEN)); + final OntologyChangeOperation unsupported = operation(UUID.randomUUID()); + + final List recorded = + OntologyChangeEvidenceView.withoutEvidence(List.of(supported, unsupported)); + + assertEquals(List.of(operation(OPERATION_ID), unsupported), recorded); + assertEquals(List.of(name(SHOWN), profile(HIDDEN)), supported.getEvidence()); + } + + @Test + void aMaskedCopyOfADraftLeavesOutEveryOperationAndSoItsEvidence() { + final OntologyChangeSet changeSet = + changeSet( + operation(OPERATION_ID, name(SHOWN), profile(HIDDEN)).withWithheldEvidenceCount(1)) + .withName("draft"); + + final JsonNode stored = JsonUtils.readTree(JsonUtils.pojoToMaskedJson(changeSet)); + + assertTrue(MaskedFields.anyIn(OntologyChangeSet.class)); + assertEquals(List.of("operations"), MaskedFields.wholeFieldsOf(OntologyChangeSet.class)); + assertTrue(stored.path("operations").isMissingNode()); + assertEquals("draft", stored.path("name").asText()); + } + + @Test + void onePageOfChangeSetsDecidesEachTableOnce() { + final OntologyChangeSet first = changeSet(operation(OPERATION_ID, name(SHOWN), name(HIDDEN))); + final OntologyChangeSet second = + changeSet(operation(UUID.randomUUID(), profile(HIDDEN), profile(SHOWN))); + + view.applyAll(List.of(first, second)); + view.apply(changeSet(operation(UUID.randomUUID(), lineage(HIDDEN)))); + + assertEquals(List.of(List.of(SHOWN, HIDDEN)), lookups); + assertEquals(List.of(profile(SHOWN)), second.getOperations().getFirst().getEvidence()); + } + + @Test + void aSaveKeepsTheEvidenceItsWriterWasNotShown() { + final List stored = + List.of(operation(OPERATION_ID, name(SHOWN), profile(HIDDEN), lineage(SHOWN))); + + assertEquals( + List.of(name(SHOWN), profile(HIDDEN), lineage(SHOWN)), + saved(stored, operation(OPERATION_ID, name(SHOWN), lineage(SHOWN)))); + assertEquals( + List.of(lineage(SHOWN), profile(HIDDEN)), + saved(stored, operation(OPERATION_ID, lineage(SHOWN)))); + assertEquals( + List.of(name(SHOWN), profile(HIDDEN), lineage(SHOWN), testCase(SHOWN)), + saved(stored, operation(OPERATION_ID, name(SHOWN), lineage(SHOWN), testCase(SHOWN)))); + assertEquals(List.of(profile(HIDDEN)), saved(stored, operation(OPERATION_ID))); + } + + @Test + void anEntrySentAboutAHiddenTableIsNotStoredWhetherOrNotItRepeatsAWithheldOne() { + final List stored = + List.of(operation(OPERATION_ID, name(SHOWN), profile(HIDDEN))); + + assertEquals( + List.of(name(SHOWN), profile(HIDDEN)), + saved(stored, operation(OPERATION_ID, name(SHOWN), profile(HIDDEN)))); + assertEquals( + List.of(name(SHOWN), profile(HIDDEN)), + saved(stored, operation(OPERATION_ID, name(SHOWN), lineage(HIDDEN)))); + } + + @Test + void anOperationTheDraftDoesNotStoreKeepsTheEntriesItsWriterMayView() { + final List stored = + List.of(operation(OPERATION_ID, name(SHOWN), profile(HIDDEN))); + + assertEquals( + List.of(name(SHOWN)), + saved(stored, operation(UUID.randomUUID(), lineage(HIDDEN), name(SHOWN)))); + assertEquals( + List.of(testCase(SHOWN)), + saved(List.of(), operation(OPERATION_ID, profile(HIDDEN), testCase(SHOWN)))); + assertEquals(List.of(), saved(List.of(), operation(OPERATION_ID, lineage(HIDDEN)))); + assertNull(saved(stored, operation(UUID.randomUUID()))); + } + + @Test + void aSaveRefusesMoreEvidenceThanAnOperationHolds() { + final List stored = + List.of(operation(OPERATION_ID, profile(HIDDEN), lineage(HIDDEN))); + final OntologyChangeEvidence[] sent = + IntStream.range(0, 19) + .mapToObj(index -> name(SHOWN).withColumns(List.of(List.of("column_" + index)))) + .toArray(OntologyChangeEvidence[]::new); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> view.savedByReader(stored, List.of(operation(OPERATION_ID, sent)))); + + assertEquals( + "Ontology operation '" + + OPERATION_ID + + "' is invalid: evidence holds at most 20 entries, counting the 2 that a read withheld", + refusal.getMessage()); + } + + @Test + void aSaveThatSendsBackTheCountItsReadWithheldIsAccepted() { + final List stored = + List.of(operation(OPERATION_ID, name(SHOWN), profile(HIDDEN))); + + assertEquals( + List.of(name(SHOWN), profile(HIDDEN)), + view.savedByReader( + stored, + List.of(operation(OPERATION_ID, name(SHOWN))), + java.util.Map.of(OPERATION_ID, 1)) + .getFirst() + .getEvidence()); + } + + @Test + void + aSaveIsRefusedWhenTheCountItsReadWithheldIsLargerOrSmallerThanTheStoredOperationWithholdsNow() { + final List stored = + List.of(operation(OPERATION_ID, name(SHOWN), profile(HIDDEN))); + + for (final int read : new int[] {0, 2}) { + final PreconditionFailedException refusal = + assertThrows( + PreconditionFailedException.class, + () -> + view.savedByReader( + stored, + List.of(operation(OPERATION_ID, name(SHOWN))), + java.util.Map.of(OPERATION_ID, read))); + assertEquals( + "The evidence of operation '" + + OPERATION_ID + + "' changed for you since you read this change set. Read the change set again," + + " then save.", + refusal.getMessage()); + } + } + + @Test + void aCountSentWhenNothingIsWithheldIsRefusedOnlyWhenItIsNotZero() { + final List stored = List.of(operation(OPERATION_ID, name(SHOWN))); + final List sent = List.of(operation(OPERATION_ID, name(SHOWN))); + + assertEquals( + List.of(name(SHOWN)), + view.savedByReader(stored, sent, java.util.Map.of(OPERATION_ID, 0)) + .getFirst() + .getEvidence()); + assertThrows( + PreconditionFailedException.class, + () -> view.savedByReader(stored, sent, java.util.Map.of(OPERATION_ID, 3))); + } + + @Test + void aCountForAnOperationTheDraftDoesNotStoreIsNotChecked() { + final UUID added = UUID.randomUUID(); + + assertNull( + view.savedByReader(List.of(), List.of(operation(added)), java.util.Map.of(added, 4)) + .getFirst() + .getEvidence()); + } + + private List saved( + final List stored, final OntologyChangeOperation sent) { + return view.savedByReader(stored, List.of(sent)).getFirst().getEvidence(); + } + + private static OntologyChangeSet changeSet(final OntologyChangeOperation... operations) { + return new OntologyChangeSet().withOperations(List.of(operations)); + } + + private static OntologyChangeOperation operation( + final UUID id, final OntologyChangeEvidence... evidence) { + return new OntologyChangeOperation() + .withId(id) + .withOperationType(OntologyChangeOperationType.UPSERT_CONCEPT) + .withEvidence(evidence.length == 0 ? null : List.of(evidence)); + } + + private static OntologyChangeEvidence name(final UUID tableId) { + return entry(tableId, OntologyChangeEvidenceKind.NAME); + } + + private static OntologyChangeEvidence profile(final UUID tableId) { + return entry(tableId, OntologyChangeEvidenceKind.PROFILE); + } + + private static OntologyChangeEvidence lineage(final UUID tableId) { + return entry(tableId, OntologyChangeEvidenceKind.LINEAGE); + } + + private static OntologyChangeEvidence testCase(final UUID tableId) { + return entry(tableId, OntologyChangeEvidenceKind.TEST_CASE); + } + + private static OntologyChangeEvidence entry( + final UUID tableId, final OntologyChangeEvidenceKind kind) { + return new OntologyChangeEvidence().withTableId(tableId).withKind(kind); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangePreflightTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangePreflightTest.java index d3e09a0f5ea3..907c84b3a739 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangePreflightTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangePreflightTest.java @@ -32,8 +32,10 @@ import org.openmetadata.schema.entity.data.OntologyChangeSet; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyAxiomType; +import org.openmetadata.schema.type.OntologyBindingChange; import org.openmetadata.schema.type.OntologyChangeOperation; import org.openmetadata.schema.type.OntologyChangeOperationType; import org.openmetadata.schema.type.OntologyExpression; @@ -165,6 +167,67 @@ void acceptsAPropertyRangedOverAnXsdDatatypeAndDomainedOnACreatedConcept() { () -> preflightWithoutConcepts().validate(nativeChangeSet(), List.of(concept, property))); } + @Test + void refusesABindingWhoseClassIsNeitherDeclaredNorCreatedByTheSet() { + final URI account = URI.create("https://example.org/Account"); + + assertNeedsConcept(bindingOf(account), account.toString()); + } + + @Test + void refusesAShapeWhoseTargetClassIsNeitherDeclaredNorCreatedByTheSet() { + final URI account = URI.create("https://example.org/Account"); + + assertNeedsConcept(shapeOn(account), account.toString()); + } + + @Test + void acceptsABindingAndAShapeOnAClassTheSetCreates() { + final URI account = URI.create("https://example.org/Account"); + + assertDoesNotThrow( + () -> + preflightWithoutConcepts() + .validate( + nativeChangeSet(), + List.of(upsertConcept(account), bindingOf(account), shapeOn(account)))); + } + + @Test + void refusesABindingInAGlossaryChangeSet() { + final OntologyChangeSet glossaryChangeSet = + new OntologyChangeSet() + .withGlossaries(List.of(new EntityReference().withId(UUID.randomUUID()))); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> + preflightWithoutConcepts() + .validate( + glossaryChangeSet, + List.of(bindingOf(URI.create("https://example.org/Account"))))); + + assertEquals( + "Bindings and shapes must be authored in an ontology, not a glossary change set", + refusal.getMessage()); + } + + private static OntologyChangeOperation bindingOf(final URI classIri) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBinding( + new OntologyBindingChange().withClassIri(classIri).withTableId(UUID.randomUUID())); + } + + private static OntologyChangeOperation shapeOn(final URI classIri) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_SHAPE) + .withShape(new OntologyShape().withId(UUID.randomUUID()).withTargetConcept(classIri)); + } + private static OntologyChangePreflight preflightWithoutConcepts() { return new OntologyChangePreflight( (entityType, id) -> { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccessTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccessTest.java new file mode 100644 index 000000000000..b2822e7215be --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyChangeSetReadAccessTest.java @@ -0,0 +1,169 @@ +/* + * 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.ontology; + +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 jakarta.ws.rs.core.SecurityContext; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.mockito.MockedConstruction; +import org.mockito.Mockito; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; +import org.openmetadata.service.security.policyevaluator.ResourceContextInterface; + +class OntologyChangeSetReadAccessTest { + private static final SecurityContext CALLER = Mockito.mock(SecurityContext.class); + + @Test + void aCallerWhoMayEditTheOntologyMayReadItsDraft() { + try (MockedConstruction ignored = + Mockito.mockConstruction(ResourceContext.class)) { + assertTrue( + OntologyChangeSetReadAccess.mayRead( + grantingOnly(Entity.ONTOLOGY), CALLER, OntologyChangeSetReadAccessTest::draft)); + } + } + + @Test + void aCallerRefusedTheOntologyMayNotReadItsDraft() { + try (MockedConstruction ignored = + Mockito.mockConstruction(ResourceContext.class)) { + assertFalse( + OntologyChangeSetReadAccess.mayRead( + grantingOnly(Entity.GLOSSARY), CALLER, OntologyChangeSetReadAccessTest::draft)); + } + } + + @Test + void aDraftThatCannotBeLoadedIsNotShown() { + assertFalse( + OntologyChangeSetReadAccess.mayRead( + grantingOnly(Entity.ONTOLOGY), + CALLER, + () -> { + throw new EntityNotFoundException("gone"); + })); + } + + @Test + void aScopeThatNoLongerExistsIsNotShown() { + final Authorizer missingScope = Mockito.mock(Authorizer.class); + Mockito.doThrow(new EntityNotFoundException("ontology gone")) + .when(missingScope) + .authorize( + Mockito.any(SecurityContext.class), + Mockito.any(OperationContext.class), + Mockito.any(ResourceContextInterface.class)); + + try (MockedConstruction ignored = + Mockito.mockConstruction(ResourceContext.class)) { + assertFalse( + OntologyChangeSetReadAccess.mayRead( + missingScope, CALLER, OntologyChangeSetReadAccessTest::draft)); + } + } + + @Test + void aHistoryKeepsTheSnapshotsOfReadableDraftsAndDecidesEachDraftOnce() { + final OntologyChangeSet readable = draft(); + final OntologyChangeSet unreadable = draft(); + final OntologyChangeSet gone = draft(); + final List snapshots = + List.of(readable, unreadable, readable, gone, unreadable, readable, gone); + final Map loads = new HashMap<>(); + final Map scopeOf = new IdentityHashMap<>(); + final Authorizer authorizer = refusing(scopeOf, unreadable.getOntology().getId()); + + try (MockedConstruction ignored = + Mockito.mockConstruction( + ResourceContext.class, + (context, creation) -> scopeOf.put(context, creation.arguments().get(1)))) { + final List kept = + OntologyChangeSetReadAccess.readable( + authorizer, + CALLER, + snapshots, + id -> { + loads.merge(id, 1, Integer::sum); + if (id.equals(gone.getId())) { + throw new EntityNotFoundException("gone"); + } + return snapshots.stream().filter(s -> s.getId().equals(id)).findFirst().get(); + }); + + assertEquals(List.of(readable, readable, readable), kept); + } + assertEquals(Map.of(readable.getId(), 1, unreadable.getId(), 1, gone.getId(), 1), loads); + } + + private static Authorizer refusing(final Map scopeOf, final UUID ontologyId) { + final Authorizer authorizer = Mockito.mock(Authorizer.class); + Mockito.doAnswer( + call -> { + if (ontologyId.equals(scopeOf.get(call.getArgument(2)))) { + throw new AuthorizationException("denied"); + } + return null; + }) + .when(authorizer) + .authorize( + Mockito.any(SecurityContext.class), + Mockito.any(OperationContext.class), + Mockito.any(ResourceContextInterface.class)); + return authorizer; + } + + private static OntologyChangeSet draft() { + return new OntologyChangeSet() + .withId(UUID.randomUUID()) + .withOntology(new EntityReference().withId(UUID.randomUUID()).withType(Entity.ONTOLOGY)) + .withOperations(List.of()); + } + + private static Authorizer grantingOnly(final String resource) { + final Authorizer authorizer = Mockito.mock(Authorizer.class); + Mockito.doAnswer( + call -> { + final OperationContext operation = call.getArgument(1); + final boolean granted = + resource.equals(operation.getResource()) + && operation.getOperations(null).equals(List.of(MetadataOperation.EDIT_ALL)); + if (!granted) { + throw new AuthorizationException("denied"); + } + return null; + }) + .when(authorizer) + .authorize( + Mockito.any(SecurityContext.class), + Mockito.any(OperationContext.class), + Mockito.any(ResourceContextInterface.class)); + return authorizer; + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcilerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcilerTest.java new file mode 100644 index 000000000000..d2535bd71362 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconcilerTest.java @@ -0,0 +1,94 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +import jakarta.ws.rs.BadRequestException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.service.ontology.OntologyCheckReconciler.Found; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Checks; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Compiled; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.DeleteTest; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Held; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Proposed; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Refused; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.TaskState; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.TestState; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Write; + +class OntologyCheckReconcilerTest { + private static final UUID CLASS = UUID.fromString("00000000-0000-0000-0000-0000000000c1"); + private static final UUID TEST = UUID.fromString("00000000-0000-0000-0000-000000000001"); + private static final UUID TASK = UUID.fromString("00000000-0000-0000-0000-000000000002"); + + @Test + void aCompileThatTheServerRefusesIsReadAsRefusedAndNotAsNoChecks() { + final Found found = + OntologyCheckReconciler.attempt( + CLASS, + () -> { + throw new BadRequestException("Binding property inheritance exceeds the limit"); + }); + + final Refused refused = assertInstanceOf(Refused.class, found.decision()); + assertEquals("Binding property inheritance exceeds the limit", refused.reason()); + assertEquals(Map.of(), found.byIdentity()); + } + + @Test + void aCompileThatFailsIsReadAsRefusedWithItsMessage() { + final Found found = + OntologyCheckReconciler.attempt( + CLASS, + () -> { + throw new IllegalStateException("the binding rows changed"); + }); + + assertEquals( + new Refused("the binding rows changed"), assertInstanceOf(Refused.class, found.decision())); + } + + @Test + void aCompileThatAnswersIsPassedOn() { + final Found answered = new Found(new Checks(List.of()), Map.of()); + assertEquals(answered, OntologyCheckReconciler.attempt(CLASS, () -> answered)); + } + + @Test + void aRefusedCompileLeavesTheTestAndTheOpenTaskOfItsClassAlone() { + final Found found = + OntologyCheckReconciler.attempt( + CLASS, + () -> { + throw new BadRequestException("refused"); + }); + final Map decisions = Map.of(CLASS, found.decision()); + final Held test = new Held(TEST, CLASS, "test", "a", "d1", List.of(), TestState.LIVE); + final Proposed task = new Proposed(TASK, CLASS, "b", "d1", List.of(), TaskState.OPEN, "other"); + + final List writes = + OntologyCheckReconciliation.decide(decisions, List.of(test), List.of(task)); + + assertEquals(List.of(), writes); + assertEquals( + List.of(new DeleteTest(TEST)), + OntologyCheckReconciliation.decide( + Map.of(CLASS, new Checks(List.of())), List.of(test), List.of())); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java new file mode 100644 index 000000000000..3c1ebf64c0ff --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCheckReconciliationTest.java @@ -0,0 +1,441 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.service.ontology.OntologyCheckReconciler.Outcome; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Binding; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.CancelTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Checks; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Compiled; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.CreateTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.DeleteTest; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Held; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Proposed; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Refused; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.ReplaceTask; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.RestoreTest; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.TaskState; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.TestState; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.UpdateTest; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Wanted; +import org.openmetadata.service.ontology.OntologyCheckReconciliation.Write; + +class OntologyCheckReconciliationTest { + private static final UUID CLASS = UUID.fromString("00000000-0000-0000-0000-0000000000c1"); + private static final UUID OTHER_CLASS = UUID.fromString("00000000-0000-0000-0000-0000000000c2"); + private static final UUID ASSET = UUID.fromString("00000000-0000-0000-0000-0000000000a1"); + private static final UUID ID_1 = UUID.fromString("00000000-0000-0000-0000-000000000001"); + private static final UUID ID_2 = UUID.fromString("00000000-0000-0000-0000-000000000002"); + private static final UUID ID_3 = UUID.fromString("00000000-0000-0000-0000-000000000003"); + private static final UUID ID_4 = UUID.fromString("00000000-0000-0000-0000-000000000004"); + private static final List REV_3 = List.of(new Binding(CLASS, ASSET, 3)); + private static final List REV_4 = List.of(new Binding(CLASS, ASSET, 4)); + + private static Wanted check(final String identity, final String digest, final List b) { + return new Wanted(identity, digest, b); + } + + private static Held test( + final UUID id, final String identity, final String digest, final TestState state) { + return new Held(id, CLASS, "test-" + id, identity, digest, REV_3, state); + } + + private static Proposed task( + final UUID id, final String identity, final String digest, final TaskState state) { + return new Proposed(id, CLASS, identity, digest, REV_3, state, "made-by-" + id); + } + + /** The task that was approved and created the test with this id, as {@code test} names it. */ + private static Proposed approvedTestOf(final UUID testId) { + return new Proposed(ID_2, CLASS, "a", "d1", REV_3, TaskState.APPROVED, "test-" + testId); + } + + private static List decide( + final Compiled compiled, final List tests, final List tasks) { + final Map classes = new LinkedHashMap<>(); + classes.put(CLASS, compiled); + return OntologyCheckReconciliation.decide(classes, tests, tasks); + } + + @Test + void aCheckWithNoTestAndNoTaskGetsANewTask() { + final List writes = + decide(new Checks(List.of(check("a", "d1", REV_3))), List.of(), List.of()); + assertEquals(List.of(new CreateTask(CLASS, "a")), writes); + } + + @Test + void aTestWhoseDigestChangedIsUpdatedInPlace() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(test(ID_1, "a", "d1", TestState.LIVE)), + List.of()); + assertEquals(List.of(new UpdateTest(ID_1, CLASS, "a")), writes); + } + + @Test + void aTestWhoseReadBindingsChangedIsUpdatedInPlace() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_4))), + List.of(test(ID_1, "a", "d1", TestState.LIVE)), + List.of()); + assertEquals(List.of(new UpdateTest(ID_1, CLASS, "a")), writes); + } + + @Test + void aTestWithTheSameDigestAndBindingsIsLeftAlone() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(test(ID_1, "a", "d1", TestState.LIVE)), + List.of()); + assertEquals(List.of(), writes); + } + + @Test + void aTestMakesTheOpenTaskOfTheSameCheckWait() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(test(ID_1, "a", "d1", TestState.LIVE)), + List.of(task(ID_2, "a", "d1", TaskState.OPEN))); + assertEquals( + List.of( + new UpdateTest(ID_1, CLASS, "a"), new CancelTask(ID_2, "A test of this check exists")), + writes); + } + + @Test + void anOpenTaskWhoseContentChangedGetsItsValueReplaced() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(), + List.of(task(ID_2, "a", "d1", TaskState.OPEN))); + assertEquals(List.of(new ReplaceTask(ID_2, CLASS, "a")), writes); + } + + @Test + void anOpenTaskWithTheSameContentIsLeftAlone() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(), + List.of(task(ID_2, "a", "d1", TaskState.OPEN))); + assertEquals(List.of(), writes); + } + + @Test + void aRejectedTaskOfTheSameContentProposesNothing() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(), + List.of(task(ID_2, "a", "d1", TaskState.REJECTED))); + assertEquals(List.of(), writes); + } + + @Test + void aRejectedTaskOfOtherContentIsProposedAgain() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(), + List.of(task(ID_2, "a", "d1", TaskState.REJECTED))); + assertEquals(List.of(new CreateTask(CLASS, "a")), writes); + } + + @Test + void aTestAPersonDeletedWithTheSameDigestProposesNothing() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_PERSON)), + List.of()); + assertEquals(List.of(), writes); + } + + @Test + void aTestAPersonDeletedWithOtherContentIsProposedAgain() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_PERSON)), + List.of()); + assertEquals(List.of(new CreateTask(CLASS, "a")), writes); + } + + @Test + void aTestWhoseCheckNoLongerAppearsIsDeletedAndItsOpenTaskCancelled() { + final List writes = + decide( + new Checks(List.of()), + List.of(test(ID_1, "a", "d1", TestState.LIVE)), + List.of(task(ID_2, "b", "d1", TaskState.OPEN))); + assertEquals( + List.of( + new DeleteTest(ID_1), + new CancelTask(ID_2, OntologyCheckReconciliation.NO_LONGER_CHECKED)), + writes); + } + + @Test + void aTestAlreadyDeletedOrATaskAlreadyClosedWhoseCheckVanishedIsNotTouched() { + final List writes = + decide( + new Checks(List.of()), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_PERSON)), + List.of( + task(ID_2, "b", "d1", TaskState.REJECTED), + task(UUID.randomUUID(), "c", "d1", TaskState.OTHER))); + assertEquals(List.of(), writes); + } + + @Test + void aRefusedCompileChangesNothingForItsClassAndStillReconcilesAnother() { + final Map classes = new LinkedHashMap<>(); + classes.put(CLASS, new Refused("Binding property inheritance exceeds the 10000 axiom limit")); + classes.put(OTHER_CLASS, new Checks(List.of())); + final Held kept = test(ID_1, "a", "d1", TestState.LIVE); + final Held goes = new Held(ID_2, OTHER_CLASS, "t-z", "z", "d1", REV_3, TestState.LIVE); + final Proposed openTask = task(UUID.randomUUID(), "b", "d1", TaskState.OPEN); + final List writes = + OntologyCheckReconciliation.decide(classes, List.of(kept, goes), List.of(openTask)); + assertEquals(List.of(new DeleteTest(ID_2)), writes); + } + + @Test + void anEmptyRunWritesNothing() { + assertEquals(List.of(), OntologyCheckReconciliation.decide(Map.of(), List.of(), List.of())); + assertEquals(List.of(), decide(new Checks(List.of()), List.of(), List.of())); + } + + @Test + void aSecondRunOverTheStateTheFirstRunWroteWritesNothing() { + final Wanted created = check("a", "d2", REV_4); + final Wanted replaced = check("b", "d2", REV_4); + final Wanted fresh = check("c", "d1", REV_3); + final List tests = List.of(test(ID_1, "a", "d1", TestState.LIVE)); + final List tasks = List.of(task(ID_2, "b", "d1", TaskState.OPEN)); + final List first = decide(new Checks(List.of(created, replaced, fresh)), tests, tasks); + assertEquals( + List.of( + new UpdateTest(ID_1, CLASS, "a"), + new ReplaceTask(ID_2, CLASS, "b"), + new CreateTask(CLASS, "c")), + first); + final List testsAfter = + List.of(new Held(ID_1, CLASS, "test-" + ID_1, "a", "d2", REV_4, TestState.LIVE)); + final List tasksAfter = + List.of( + new Proposed(ID_2, CLASS, "b", "d2", REV_4, TaskState.OPEN, "made-by-" + ID_2), + new Proposed(UUID.randomUUID(), CLASS, "c", "d1", REV_3, TaskState.OPEN, "made-by-c")); + assertEquals( + List.of(), decide(new Checks(List.of(created, replaced, fresh)), testsAfter, tasksAfter)); + } + + @Test + void twoOpenTasksOfOneCheckKeepOneAndCancelTheOther() { + final UUID duplicate = UUID.fromString("00000000-0000-0000-0000-000000000003"); + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(), + List.of( + task(ID_2, "a", "d1", TaskState.OPEN), task(duplicate, "a", "d1", TaskState.OPEN))); + assertEquals( + List.of(new CancelTask(duplicate, "Another open suggestion proposes this check")), writes); + } + + @Test + void theTestsOfAClassThatIsNotNamedAreNotTouched() { + final Held elsewhere = new Held(ID_1, OTHER_CLASS, "t-z", "z", "d1", REV_3, TestState.LIVE); + assertEquals( + List.of(), + OntologyCheckReconciliation.decide( + Map.of(CLASS, new Checks(List.of())), List.of(elsewhere), List.of())); + } + + @Test + void aTestTheReconcileDeletedComesBackWhenItsCheckIsWantedAgain() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of(approvedTestOf(ID_1))); + assertEquals(List.of(new RestoreTest(ID_1)), writes); + } + + @Test + void aRestoreIsReportedAsARestoreAndNotAsAnUpdate() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of(approvedTestOf(ID_1))); + + assertEquals(new Outcome(0, 0, 0, 0, 1, 0, 0), Outcome.tally(writes, 0)); + } + + @Test + void aRestoreThatAlsoChangedTheContentIsReportedAsARestoreAndAnUpdate() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_4))), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of(approvedTestOf(ID_1))); + + assertEquals(new Outcome(0, 0, 0, 1, 1, 0, 0), Outcome.tally(writes, 0)); + } + + @Test + void everyKindOfWriteIsCountedOnceAndTheRefusedCountIsKept() { + final List writes = + List.of( + new CreateTask(CLASS, "a"), + new ReplaceTask(ID_2, CLASS, "b"), + new CancelTask(ID_3, "gone"), + new UpdateTest(ID_1, CLASS, "c"), + new RestoreTest(ID_4), + new DeleteTest(ID_1)); + + final Outcome outcome = Outcome.tally(writes, 2); + + assertEquals(new Outcome(1, 1, 1, 1, 1, 1, 2), outcome); + assertEquals(6, outcome.writes()); + } + + @Test + void aTestTheReconcileDeletedComesBackUpdatedWhenItsContentChanged() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_4))), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of(approvedTestOf(ID_1))); + assertEquals(List.of(new RestoreTest(ID_1), new UpdateTest(ID_1, CLASS, "a")), writes); + } + + @Test + void aTestTheReconcileDeletedStaysDeletedWhenAPersonDeletedAnotherOfTheSameContent() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of( + test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE), + test(ID_2, "a", "d1", TestState.DELETED_BY_PERSON)), + List.of()); + assertEquals(List.of(), writes); + } + + @Test + void aTestTheReconcileDeletedGivesWayToANewTaskWhenAPersonDeletedAnotherOfOtherContent() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of( + test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE), + test(ID_2, "a", "d1", TestState.DELETED_BY_PERSON)), + List.of()); + assertEquals(List.of(new CreateTask(CLASS, "a")), writes); + } + + @Test + void ofSeveralTestsTheReconcileDeletedTheOneWithTheLowestIdComesBack() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of( + test(ID_3, "a", "d1", TestState.DELETED_BY_RECONCILE), + test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE), + test(ID_2, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of()); + assertEquals(List.of(new RestoreTest(ID_1)), writes); + } + + @Test + void anApprovedTaskWhoseTestWasHardDeletedProposesNothingForTheSameDigest() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(), + List.of(task(ID_2, "a", "d1", TaskState.APPROVED))); + assertEquals(List.of(), writes); + } + + @Test + void anApprovedTaskWhoseTestWasHardDeletedIsProposedAgainForOtherContent() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(), + List.of(task(ID_2, "a", "d1", TaskState.APPROVED))); + assertEquals(List.of(new CreateTask(CLASS, "a")), writes); + } + + @Test + void anApprovedTaskWhoseTestStillHasARowIsNotAHardDelete() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of(test(ID_1, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of(approvedTestOf(ID_1))); + assertEquals(List.of(new RestoreTest(ID_1), new UpdateTest(ID_1, CLASS, "a")), writes); + } + + @Test + void threeLiveTestsOfOneCheckKeepTheLowestIdAndDeleteTheOthersInIdOrder() { + final List writes = + decide( + new Checks(List.of(check("a", "d2", REV_3))), + List.of( + test(ID_3, "a", "d1", TestState.LIVE), + test(ID_1, "a", "d1", TestState.LIVE), + test(ID_2, "a", "d1", TestState.LIVE)), + List.of()); + assertEquals( + List.of(new UpdateTest(ID_1, CLASS, "a"), new DeleteTest(ID_2), new DeleteTest(ID_3)), + writes); + } + + @Test + void twoLiveTestsOfOneCheckThatAreCurrentLoseOnlyTheHigherId() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of(test(ID_4, "a", "d1", TestState.LIVE), test(ID_2, "a", "d1", TestState.LIVE)), + List.of()); + assertEquals(List.of(new DeleteTest(ID_4)), writes); + } + + @Test + void aSecondRunAfterTheDuplicatesWereDeletedWritesNothing() { + final List writes = + decide( + new Checks(List.of(check("a", "d1", REV_3))), + List.of( + test(ID_1, "a", "d1", TestState.LIVE), + test(ID_2, "a", "d1", TestState.DELETED_BY_RECONCILE)), + List.of()); + assertEquals(List.of(), writes); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyConceptQueryServiceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyConceptQueryServiceTest.java index 37affe56e274..847dff026dfa 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyConceptQueryServiceTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyConceptQueryServiceTest.java @@ -15,9 +15,16 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; +import org.openmetadata.schema.api.services.CreateDatabaseService.DatabaseServiceType; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyColumnBinding; import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.service.exception.BadRequestException; import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; @@ -32,6 +39,11 @@ class OntologyConceptQueryServiceTest { private static final URI MANAGER_IRI = URI.create("urn:hr:Manager"); private static final URI MANAGES_IRI = URI.create("urn:hr:manages"); private static final URI MANAGED_BY_IRI = URI.create("urn:hr:managedBy"); + private static final OntologyProperty TRANSFER_ID = + new OntologyProperty() + .withId(UUID.randomUUID()) + .withName("transferId") + .withKind(OntologyPropertyKind.DATA); @Test void aReaderWhoMayViewOnlyTheTwelfthBoundTableGetsSqlOverIt() { @@ -118,7 +130,7 @@ void aHopFollowedBackAgainstItsRelationReadsAsTheDeclaredInverse() { assertEquals("part of", OntologyConceptQueryService.hopLabel(INCOMING, partOf, null)); assertEquals( "SELECT t1.transfer_id\nFROM payments.customers t0\n" - + "JOIN payments.transfers t1 ON t0.customer_id = t1.customer_id -- has part\nLIMIT 50", + + "JOIN payments.transfers t1 ON t0.customer_id = t1.customer_id\nLIMIT 50", OntologyConceptSqlGenerator.generate( new BoundConcept("Customer", List.of(customers)), List.of( @@ -180,7 +192,7 @@ void anInverseTheReaderMayNotViewStillOrientsASelfRelationAndNamesNothing() { assertEquals("manages", hop.label()); assertEquals( "SELECT t1.employee_id, t1.manager_id\nFROM payments.employees t0\n" - + "JOIN payments.employees t1 ON t0.employee_id = t1.manager_id -- manages\n" + + "JOIN payments.employees t1 ON t0.employee_id = t1.manager_id\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate(employees, List.of(hop)).sql()); } @@ -197,29 +209,29 @@ void anIncomingHopJoinsTheWayItsLabelReads() { assertAll( () -> assertEquals( - employeesJoinedOn("t0.manager_id = t1.employee_id -- managed by"), - sql( + List.of("managed by", employeesJoinedOn("t0.manager_id = t1.employee_id")), + labelAndSql( employees, OntologyConceptQueryService.hop(managedBy, OUTGOING, inverses, managers)), "Employee to Manager over managed by"), () -> assertEquals( - employeesJoinedOn("t0.manager_id = t1.employee_id -- managed by"), - sql( + List.of("managed by", employeesJoinedOn("t0.manager_id = t1.employee_id")), + labelAndSql( employees, OntologyConceptQueryService.hop(manages, INCOMING, inverses, managers)), "Employee to Manager over manages, incoming"), () -> assertEquals( - employeesJoinedOn("t0.employee_id = t1.manager_id -- manages"), - sql( + List.of("manages", employeesJoinedOn("t0.employee_id = t1.manager_id")), + labelAndSql( managers, OntologyConceptQueryService.hop(manages, OUTGOING, inverses, employees)), "Manager to Employee over manages"), () -> assertEquals( - employeesJoinedOn("t0.employee_id = t1.manager_id -- manages"), - sql( + List.of("manages", employeesJoinedOn("t0.employee_id = t1.manager_id")), + labelAndSql( managers, OntologyConceptQueryService.hop(managedBy, INCOMING, inverses, employees)), "Manager to Employee over managed by, incoming")); @@ -240,8 +252,7 @@ void anIncomingHopOverAHiddenInverseJoinsTheSameWayAndNamesOnlyItsOwnProperty() managerBoundEmployees("Manager", managedBy)); assertEquals("manages", hop.label()); - assertEquals( - employeesJoinedOn("t0.manager_id = t1.employee_id -- manages"), sql(employees, hop)); + assertEquals(employeesJoinedOn("t0.manager_id = t1.employee_id"), sql(employees, hop)); } @Test @@ -258,8 +269,7 @@ void anOutgoingChipFromAConceptOnlyInTheRangeFollowsItsOwnProperty() { managers); assertEquals("managed by", hop.label()); - assertEquals( - employeesJoinedOn("t0.manager_id = t1.employee_id -- managed by"), sql(managers, hop)); + assertEquals(employeesJoinedOn("t0.manager_id = t1.employee_id"), sql(managers, hop)); } @Test @@ -276,7 +286,7 @@ void anIncomingChipToAConceptOutsideTheDomainRunsOverTheInverse() { assertEquals("manages", hop.label()); assertEquals( - employeesJoinedOn("t0.employee_id = t1.manager_id -- manages"), + employeesJoinedOn("t0.employee_id = t1.manager_id"), sql(managerBoundEmployees("Manager", managedBy), hop)); } @@ -328,6 +338,119 @@ void aHopWhosePropertyDeclaresNoInverseKeepsItsPropertyAndLabel() { assertEquals("reports to", hop.label()); } + @Test + void aStoredRowFilterIsParsedAsTheColumnsTypeAndAppliedByTheStatement() { + final BindingRow stored = filteredTransfers("void' OR '1'='1"); + + final BoundTable bound = + OntologyBoundTables.of( + transfers(ColumnDataType.VARCHAR), stored, Map.of(TRANSFER_ID.getId(), TRANSFER_ID)); + + assertEquals( + "SELECT `transfer_id`\nFROM `payments`.`transfers`\n" + + "WHERE `status` <> 'void'' OR ''1''=''1'\nLIMIT 50", + OntologyConceptSqlGenerator.generate( + new BoundConcept("Funds Transfer", List.of(bound)), List.of()) + .sql()); + } + + @Test + void aStoredRowFilterThatNoLongerParsesIsABadRequestThatNamesTheTable() { + final BindingRow stored = filteredTransfers("void"); + final Table retyped = transfers(ColumnDataType.INT); + final Table withoutTheColumn = + transfers(ColumnDataType.VARCHAR).withColumns(List.of(column("transfer_id"))); + + assertEquals( + "The row filter of finance.warehouse.payments.transfers no longer applies. The value for" + + " column status does not parse as INT: a whole number is written in ASCII digits," + + " with a leading minus sign when negative and no leading zeros", + assertThrows(BadRequestException.class, () -> statementOver(retyped, stored)).getMessage()); + assertEquals( + "The row filter of finance.warehouse.payments.transfers no longer applies. A row filter" + + " column must exist in the bound table", + assertThrows(BadRequestException.class, () -> statementOver(withoutTheColumn, stored)) + .getMessage()); + } + + @Test + void theRowFilterOfATableTheStatementDoesNotReadIsNeverParsed() { + final BoundTable stale = + OntologyBoundTables.of(transfers(ColumnDataType.INT), filteredTransfers("void"), Map.of()); + final BoundTable customers = + new BoundTable( + "finance.warehouse.payments.customers", + "Mysql", + List.of(List.of("customer_id")), + Map.of(), + List.of(), + List.of()); + final BoundTable settled = + new BoundTable( + "finance.warehouse.payments.settled_transfers", + "Mysql", + List.of(List.of("transfer_id")), + Map.of(), + List.of(), + List.of( + new TableConstraint() + .withConstraintType(TableConstraint.ConstraintType.FOREIGN_KEY) + .withColumns(List.of("customer_id")) + .withReferredColumns( + List.of("finance.warehouse.payments.customers.customer_id")))); + + assertEquals( + "SELECT t1.`transfer_id`\nFROM `payments`.`customers` t0\n" + + "JOIN `payments`.`settled_transfers` t1 ON t0.`customer_id` = t1.`customer_id`\n" + + "LIMIT 50", + OntologyConceptSqlGenerator.generate( + new BoundConcept("Customer", List.of(customers)), + List.of( + new Hop( + UUID.randomUUID(), + null, + "sent", + new BoundConcept("Funds Transfer", List.of(stale, settled))))) + .sql()); + } + + private static String statementOver(final Table table, final BindingRow stored) { + return OntologyConceptSqlGenerator.generate( + new BoundConcept( + "Funds Transfer", List.of(OntologyBoundTables.of(table, stored, Map.of()))), + List.of()) + .sql(); + } + + private static BindingRow filteredTransfers(final String value) { + return new BindingRow( + TRANSFER, + asset(TRANSFER, 1), + OntologyBindingAssetType.TABLE, + "hash1", + List.of( + new OntologyColumnBinding() + .withPropertyId(TRANSFER_ID.getId()) + .withColumnPath(List.of("transfer_id"))), + null, + null, + new OntologyRowFilter() + .withColumn(List.of("status")) + .withOperator(OntologyRowFilterOperator.NOT_EQUALS) + .withValue(value)); + } + + private static Table transfers(final ColumnDataType statusType) { + return new Table() + .withFullyQualifiedName("finance.warehouse.payments.transfers") + .withServiceType(DatabaseServiceType.Mysql) + .withColumns(List.of(column("transfer_id"), column("status").withDataType(statusType))); + } + + private static Column column(final String name) { + return new Column().withName(name).withDataType(ColumnDataType.INT); + } + private static OntologyProperty manages() { return new OntologyProperty() .withId(UUID.randomUUID()) @@ -398,6 +521,11 @@ private static String sql(final BoundConcept from, final Hop hop) { return OntologyConceptSqlGenerator.generate(from, List.of(hop)).sql(); } + /** The label a hop is returned with and the statement over it. The label is no part of the SQL. */ + private static List labelAndSql(final BoundConcept from, final Hop hop) { + return List.of(hop.label(), sql(from, hop)); + } + private static List rows(final UUID concept, final int count) { return IntStream.rangeClosed(1, count) .mapToObj( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyConceptSqlGeneratorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyConceptSqlGeneratorTest.java index bfc4a5a890a3..47a69476fefe 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyConceptSqlGeneratorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyConceptSqlGeneratorTest.java @@ -1,19 +1,29 @@ package org.openmetadata.service.ontology; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.openmetadata.schema.api.data.OntologyConceptQueryDialect; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; import org.openmetadata.schema.type.TableConstraint; import org.openmetadata.service.exception.BadRequestException; import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.BoundConcept; import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.BoundTable; import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.Generated; import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.Hop; +import org.openmetadata.service.ontology.sql.TypedValues; class OntologyConceptSqlGeneratorTest { private static final String TRANSFERS = "finance.warehouse.payments.transfers"; @@ -84,8 +94,8 @@ void twoHopsJoinThroughForeignKeysInEitherDirection() { "\n", "SELECT t2.account_id, t2.iban", "FROM payments.transfers t0", - "JOIN payments.customers t1 ON t0.customer_id = t1.customer_id -- part of", - "JOIN payments.accounts t2 ON t1.customer_id = t2.owner_id AND t1.region = t2.owner_region -- holds", + "JOIN payments.customers t1 ON t0.customer_id = t1.customer_id", + "JOIN payments.accounts t2 ON t1.customer_id = t2.owner_id AND t1.region = t2.owner_region", "LIMIT 50"), generated.sql()); assertEquals(List.of(TRANSFERS, CUSTOMERS, ACCOUNTS), generated.tables()); @@ -121,11 +131,11 @@ void aHopWithoutAConstraintJoinsTheObjectPropertyColumnToTheTargetIdentifier() { assertEquals( "SELECT t1.customer_id, t1.name\nFROM payments.transfers t0\n" - + "JOIN payments.customers t1 ON t0.payer_id = t1.customer_id -- paid by\nLIMIT 50", + + "JOIN payments.customers t1 ON t0.payer_id = t1.customer_id\nLIMIT 50", forward.sql()); assertEquals( "SELECT t1.transfer_id, t1.payer_id\nFROM payments.customers t0\n" - + "JOIN payments.transfers t1 ON t0.customer_id = t1.payer_id -- pays\nLIMIT 50", + + "JOIN payments.transfers t1 ON t0.customer_id = t1.payer_id\nLIMIT 50", inverse.sql()); } @@ -158,7 +168,7 @@ void aBindingWinsOverAForeignKeyOnAnotherColumnAndOtherServicesAreNeverJoined() assertEquals( "SELECT t1.*\nFROM payments.transfers t0\n" - + "JOIN payments.customers t1 ON t0.payer_id = t1.customer_id -- paid by\nLIMIT 50", + + "JOIN payments.customers t1 ON t0.payer_id = t1.customer_id\nLIMIT 50", generated.sql()); } @@ -166,7 +176,7 @@ void aBindingWinsOverAForeignKeyOnAnotherColumnAndOtherServicesAreNeverJoined() void aBoundHopIgnoresTheOnlyForeignKeyWhenItIsOnAnotherColumn() { assertEquals( "SELECT t1.customer_id\nFROM payments.transfers t0\n" - + "JOIN payments.customers t1 ON t0.payee_id = t1.customer_id -- received by\nLIMIT 50", + + "JOIN payments.customers t1 ON t0.payee_id = t1.customer_id\nLIMIT 50", OntologyConceptSqlGenerator.generate( concept("Funds Transfer", payeeBoundTransfers()), List.of( @@ -182,7 +192,7 @@ void aBoundHopIgnoresTheOnlyForeignKeyWhenItIsOnAnotherColumn() { void aBoundHopFromTheReferredTableIgnoresTheOnlyForeignKeyWhenItIsOnAnotherColumn() { assertEquals( "SELECT t1.transfer_id\nFROM payments.customers t0\n" - + "JOIN payments.transfers t1 ON t0.customer_id = t1.payee_id -- received\nLIMIT 50", + + "JOIN payments.transfers t1 ON t0.customer_id = t1.payee_id\nLIMIT 50", OntologyConceptSqlGenerator.generate( concept("Customer", identifiedCustomers()), List.of( @@ -207,7 +217,7 @@ void aForeignKeyThatAgreesWithTheBindingJoinsWithoutAnIdentifier() { assertEquals( "SELECT t1.name\nFROM payments.transfers t0\n" - + "JOIN payments.customers t1 ON t0.payee_id = t1.customer_id -- received by\nLIMIT 50", + + "JOIN payments.customers t1 ON t0.payee_id = t1.customer_id\nLIMIT 50", OntologyConceptSqlGenerator.generate( concept("Funds Transfer", transfers), List.of( @@ -262,7 +272,7 @@ void aBindingPicksBetweenForeignKeysInEachDirection() { assertEquals( "SELECT t1.account_id\nFROM payments.customers t0\n" - + "JOIN payments.accounts t1 ON t0.customer_id = t1.customer_id -- holds\nLIMIT 50", + + "JOIN payments.accounts t1 ON t0.customer_id = t1.customer_id\nLIMIT 50", OntologyConceptSqlGenerator.generate( concept("Customer", customers), List.of(new Hop(HOLDS, null, "holds", concept("Account", accounts)))) @@ -294,7 +304,7 @@ void aBoundHopSkipsAnEarlierCandidateWhoseForeignKeyIgnoresTheBinding() { assertEquals( "SELECT t1.transfer_id\nFROM payments.customers t0\n" - + "JOIN payments.transfers t1 ON t0.customer_id = t1.payee_id -- received\nLIMIT 50", + + "JOIN payments.transfers t1 ON t0.customer_id = t1.payee_id\nLIMIT 50", OntologyConceptSqlGenerator.generate( concept("Customer", customers), List.of( @@ -319,7 +329,7 @@ void aHopBoundOnBothTablesFollowsThePreviousTablesBinding() { assertEquals( "SELECT t1.customer_id\nFROM payments.transfers t0\n" - + "JOIN payments.customers t1 ON t0.payee_id = t1.customer_id -- received by\nLIMIT 50", + + "JOIN payments.customers t1 ON t0.payee_id = t1.customer_id\nLIMIT 50", OntologyConceptSqlGenerator.generate( concept("Funds Transfer", payeeBoundTransfers()), List.of(new Hop(RECEIVED_BY, null, "received by", concept("Customer", customers)))) @@ -416,11 +426,11 @@ void severalForeignKeysToOneTableUseTheOneTheHopPropertyIsBoundTo() { assertEquals( "SELECT t1.customer_id, t1.name\nFROM payments.transfers t0\n" - + "JOIN payments.customers t1 ON t0.payee_id = t1.customer_id -- received by\nLIMIT 50", + + "JOIN payments.customers t1 ON t0.payee_id = t1.customer_id\nLIMIT 50", forward.sql()); assertEquals( "SELECT t1.transfer_id\nFROM payments.customers t0\n" - + "JOIN payments.transfers t1 ON t0.customer_id = t1.payee_id -- received\nLIMIT 50", + + "JOIN payments.transfers t1 ON t0.customer_id = t1.payee_id\nLIMIT 50", inverse.sql()); } @@ -464,7 +474,7 @@ void anUnboundSelfRelationJoinsTheTablesOneForeignKeyToItself() { assertEquals( "SELECT t1.employee_id\nFROM payments.employees t0\n" - + "JOIN payments.employees t1 ON t0.manager_id = t1.employee_id -- managed by\n" + + "JOIN payments.employees t1 ON t0.manager_id = t1.employee_id\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate( employee, List.of(new Hop(MANAGED_BY, null, "managed by", employee))) @@ -484,7 +494,7 @@ void anUnboundHopBetweenTwoConceptsBoundToOneTableJoinsItsOneForeignKey() { assertEquals( "SELECT t1.name\nFROM payments.employees t0\n" - + "JOIN payments.employees t1 ON t0.manager_id = t1.employee_id -- managed by\n" + + "JOIN payments.employees t1 ON t0.manager_id = t1.employee_id\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate( concept("Employee", employees), @@ -521,7 +531,7 @@ void anUnboundSelfRelationWhoseInverseIsBoundJoinsAgainstTheKey() { assertEquals( "SELECT t1.employee_id, t1.manager_id\nFROM payments.employees t0\n" - + "JOIN payments.employees t1 ON t0.employee_id = t1.manager_id -- manages\n" + + "JOIN payments.employees t1 ON t0.employee_id = t1.manager_id\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate( employee, List.of(new Hop(MANAGES, MANAGED_BY, "manages", employee))) @@ -534,7 +544,7 @@ void aBoundSelfRelationWithADeclaredInverseJoinsAlongTheKey() { assertEquals( "SELECT t1.employee_id, t1.manager_id\nFROM payments.employees t0\n" - + "JOIN payments.employees t1 ON t0.manager_id = t1.employee_id -- managed by\n" + + "JOIN payments.employees t1 ON t0.manager_id = t1.employee_id\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate( employee, List.of(new Hop(MANAGED_BY, MANAGES, "managed by", employee))) @@ -550,7 +560,7 @@ void anUnboundHopBetweenTwoConceptsOfOneTableFollowsTheTargetsBindingOfTheInvers assertEquals( "SELECT t1.employee_id, t1.manager_id\nFROM payments.employees t0\n" - + "JOIN payments.employees t1 ON t0.employee_id = t1.manager_id -- manages\n" + + "JOIN payments.employees t1 ON t0.employee_id = t1.manager_id\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate( concept("Manager", managers), @@ -607,7 +617,7 @@ void anUnboundSelfRelationThatIsItsOwnInverseJoinsAlongTheKey() { assertEquals( "SELECT t1.employee_id\nFROM payments.employees t0\n" - + "JOIN payments.employees t1 ON t0.manager_id = t1.employee_id -- managed by\n" + + "JOIN payments.employees t1 ON t0.manager_id = t1.employee_id\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate( employee, List.of(new Hop(MANAGED_BY, MANAGED_BY, "managed by", employee))) @@ -632,7 +642,7 @@ void anUnboundHopWhoseInverseIsBoundPicksBetweenForeignKeysInEachDirection() { assertEquals( "SELECT t1.customer_id\nFROM payments.accounts t0\n" + "JOIN payments.customers t1 ON t0.account_id = t1.primary_account_id" - + " -- primary account of\nLIMIT 50", + + "\nLIMIT 50", OntologyConceptSqlGenerator.generate( concept("Account", accounts), List.of( @@ -659,7 +669,7 @@ void anUnboundSelfRelationWhoseInverseIsBoundToAColumnWithoutAKeyJoinsAgainstThe assertEquals( "SELECT t1.employee_id, t1.boss_id\nFROM payments.employees t0\n" - + "JOIN payments.employees t1 ON t0.employee_id = t1.boss_id -- manages\n" + + "JOIN payments.employees t1 ON t0.employee_id = t1.boss_id\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate( employee, List.of(new Hop(MANAGES, MANAGED_BY, "manages", employee))) @@ -673,7 +683,7 @@ void anUnboundSelfRelationWhoseInverseIsBoundToOneColumnOfACompositeKeyJoinsTheW assertEquals( "SELECT t1.category_id, t1.parent_id\nFROM payments.categories t0\n" + "JOIN payments.categories t1" - + " ON t0.category_id = t1.parent_id AND t0.region = t1.parent_region -- has part\n" + + " ON t0.category_id = t1.parent_id AND t0.region = t1.parent_region\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate( category, List.of(new Hop(HAS_PART, PART_OF, "has part", category))) @@ -687,7 +697,7 @@ void aSelfRelationBoundToOneColumnOfACompositeKeyJoinsTheWholeKey() { assertEquals( "SELECT t1.category_id, t1.parent_id\nFROM payments.categories t0\n" + "JOIN payments.categories t1" - + " ON t0.parent_id = t1.category_id AND t0.parent_region = t1.region -- part of\n" + + " ON t0.parent_id = t1.category_id AND t0.parent_region = t1.region\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate( category, List.of(new Hop(PART_OF, HAS_PART, "part of", category))) @@ -734,7 +744,7 @@ void aHopBoundToOneColumnOfACompositeKeyToAnotherTableJoinsTheWholeKey() { assertEquals( "SELECT t1.customer_id\nFROM payments.transfers t0\n" + "JOIN payments.customers t1" - + " ON t0.payer_id = t1.customer_id AND t0.payer_region = t1.region -- paid by\n" + + " ON t0.payer_id = t1.customer_id AND t0.payer_region = t1.region\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate( concept("Funds Transfer", transfers), @@ -796,7 +806,7 @@ void aKeyEqualToTheBoundColumnWinsOverKeysThatContainIt() { assertEquals( "SELECT t1.employee_id\nFROM payments.employees t0\n" - + "JOIN payments.employees t1 ON t0.manager_id = t1.employee_id -- managed by\n" + + "JOIN payments.employees t1 ON t0.manager_id = t1.employee_id\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate( employee, List.of(new Hop(MANAGED_BY, MANAGES, "managed by", employee))) @@ -827,7 +837,7 @@ void aLaterCandidatesEqualKeyWinsOverAnEarlierCandidatesContainingKeys() { assertEquals( "SELECT t1.customer_id\nFROM payments.transfers t0\n" - + "JOIN payments.vip_customers t1 ON t0.payer_id = t1.customer_id -- paid by\n" + + "JOIN payments.vip_customers t1 ON t0.payer_id = t1.customer_id\n" + "LIMIT 50", OntologyConceptSqlGenerator.generate( concept("Funds Transfer", transfers), @@ -909,7 +919,7 @@ void aReferredColumnWithADotIsUnquotedBeforeDialectQuoting() { assertEquals( "SELECT t1.name\nFROM payments.transfers t0\n" - + "JOIN payments.customers t1 ON t0.customer_id = t1.\"cust.id\" -- part of\nLIMIT 50", + + "JOIN payments.customers t1 ON t0.customer_id = t1.\"cust.id\"\nLIMIT 50", OntologyConceptSqlGenerator.generate( concept("Funds Transfer", payments), List.of(new Hop(PART_OF, null, "part of", concept("Customer", customers)))) @@ -938,6 +948,192 @@ void embeddedQuoteCharactersAreEscaped() { OntologyConceptSqlGenerator.generate(concept("X", ansi), List.of()).sql()); } + static Stream filteredStatements() { + return Stream.of( + Arguments.of( + "Postgres", + "SELECT transfer_id\nFROM payments.transfers\nWHERE status = E'a''b\\\\c:d'\nLIMIT 50", + "SELECT transfer_id\nFROM payments.transfers\nWHERE status = E'a''b\\\\c\\:d'\nLIMIT 50"), + Arguments.of( + "Redshift", + "SELECT transfer_id\nFROM payments.transfers\nWHERE status = 'a''b\\\\c:d'\nLIMIT 50", + "SELECT transfer_id\nFROM payments.transfers\nWHERE status = 'a''b\\\\c\\:d'\nLIMIT 50"), + Arguments.of( + "Trino", + "SELECT transfer_id\nFROM payments.transfers\nWHERE status = 'a''b\\c:d'\nLIMIT 50", + "SELECT transfer_id\nFROM payments.transfers\nWHERE status = 'a''b\\c\\:d'\nLIMIT 50"), + Arguments.of( + "Mysql", + "SELECT `transfer_id`\nFROM `payments`.`transfers`\nWHERE `status` = 'a''b\\\\c:d'\nLIMIT 50", + "SELECT `transfer_id`\nFROM `payments`.`transfers`\nWHERE `status` = 'a''b\\\\c\\:d'\nLIMIT 50"), + Arguments.of( + "Clickhouse", + "SELECT `transfer_id`\nFROM `payments`.`transfers`\nWHERE `status` = 'a''b\\\\c:d'\nLIMIT 50", + "SELECT `transfer_id`\nFROM `payments`.`transfers`\nWHERE `status` = 'a''b\\\\c\\:d'\nLIMIT 50"), + Arguments.of( + "BigQuery", + "SELECT `transfer_id`\nFROM `payments`.`transfers`\nWHERE `status` = 'a\\'b\\\\c:d'\nLIMIT 50", + "SELECT `transfer_id`\nFROM `payments`.`transfers`\nWHERE `status` = 'a\\'b\\\\c\\:d'\nLIMIT 50"), + Arguments.of( + "Snowflake", + "SELECT \"transfer_id\"\nFROM \"payments\".\"transfers\"\nWHERE \"status\" = 'a''b\\\\c:d'\nLIMIT 50", + "SELECT \"transfer_id\"\nFROM \"payments\".\"transfers\"\nWHERE \"status\" = 'a''b\\\\c\\:d'\nLIMIT 50"), + Arguments.of( + "Databricks", + "SELECT `transfer_id`\nFROM `payments`.`transfers`\nWHERE `status` = 'a\\'b\\\\c:d'\nLIMIT 50", + "SELECT `transfer_id`\nFROM `payments`.`transfers`\nWHERE `status` = 'a\\'b\\\\c\\:d'\nLIMIT 50"), + Arguments.of( + "Mssql", + "SELECT TOP 50 [transfer_id]\nFROM [payments].[transfers]\nWHERE [status] = N'a''b\\c:d'", + "SELECT TOP 50 [transfer_id]\nFROM [payments].[transfers]\nWHERE [status] = N'a''b\\c\\:d'")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("filteredStatements") + void aRowFilterValueIsWrittenAsTheEngineOfTheServiceReadsItAndNeverAsItArrived( + final String serviceType, final String sql, final String escapedSql) { + final String arrived = "a'b\\c:d"; + final BoundTable transfers = + filtered( + table(TRANSFERS, serviceType, "transfer_id"), + ColumnDataType.VARCHAR, + filter("status", OntologyRowFilterOperator.EQUALS, arrived)); + + final Generated generated = + OntologyConceptSqlGenerator.generate(concept("Funds Transfer", transfers), List.of()); + + assertEquals(sql, generated.sql()); + assertEquals(escapedSql, generated.escapedSql()); + assertFalse(generated.sql().contains(arrived), generated::sql); + } + + @Test + void theRowFilterOfEachTableReadIsAppliedUnderTheAliasOfThatTable() { + final BoundTable transfers = + filtered( + withConstraints( + table(TRANSFERS, "Postgres", "transfer_id"), + foreignKey(List.of("customer_id"), CUSTOMERS, "customer_id")), + ColumnDataType.VARCHAR, + filter("status", OntologyRowFilterOperator.IN, List.of("open", "held"))); + final BoundTable accounts = + filtered( + withConstraints( + table(ACCOUNTS, "Postgres", "account_id"), + foreignKey(List.of("owner_id"), CUSTOMERS, "customer_id")), + ColumnDataType.DATE, + filter("closed_on", OntologyRowFilterOperator.IS_NULL, null)); + + final Generated generated = + OntologyConceptSqlGenerator.generate( + concept("Funds Transfer", transfers), + List.of( + new Hop( + PART_OF, + null, + "part of", + concept("Customer", table(CUSTOMERS, "Postgres", "name"))), + new Hop(HOLDS, null, "holds", concept("Account", accounts)))); + + assertEquals( + String.join( + "\n", + "SELECT t2.account_id", + "FROM payments.transfers t0", + "JOIN payments.customers t1 ON t0.customer_id = t1.customer_id", + "JOIN payments.accounts t2 ON t1.customer_id = t2.owner_id", + "WHERE t0.status IN ('open', 'held')", + " AND t2.closed_on IS NULL", + "LIMIT 50"), + generated.sql()); + } + + @Test + void aTableJoinedToItselfAppliesItsRowFilterToEachAlias() { + final BoundTable employees = + filtered( + managerBoundEmployees(), + ColumnDataType.BOOLEAN, + filter("active", OntologyRowFilterOperator.EQUALS, true)); + + final Generated generated = + OntologyConceptSqlGenerator.generate( + concept("Employee", employees), + List.of(new Hop(MANAGED_BY, null, "managed by", concept("Employee", employees)))); + + assertEquals( + "SELECT t1.employee_id, t1.manager_id\nFROM payments.employees t0\n" + + "JOIN payments.employees t1 ON t0.manager_id = t1.employee_id\n" + + "WHERE t0.active = TRUE\n AND t1.active = TRUE\nLIMIT 50", + generated.sql()); + } + + @Test + void aRowFilterOnANestedColumnNamesEachSegmentOfItsPath() { + final OntologyRowFilter onCity = + new OntologyRowFilter() + .withColumn(List.of("Address", "city")) + .withOperator(OntologyRowFilterOperator.NOT_EQUALS) + .withValue("Paris"); + final BoundTable customers = + filtered(table(CUSTOMERS, "BigQuery", "name"), ColumnDataType.STRING, onCity); + + assertEquals( + "SELECT `name`\nFROM `payments`.`customers`\nWHERE `Address`.`city` <> 'Paris'\nLIMIT 50", + OntologyConceptSqlGenerator.generate(concept("Customer", customers), List.of()).sql()); + } + + @Test + void aColonInANameIsBareForAPersonAndEscapedForAReaderOfParameters() { + final Generated generated = + OntologyConceptSqlGenerator.generate( + concept( + "Funds Transfer", table("finance.warehouse.payments.t:1", "Postgres", "a:b", ":c")), + List.of()); + + assertEquals("SELECT \"a:b\", \":c\"\nFROM payments.\"t:1\"\nLIMIT 50", generated.sql()); + assertEquals( + "SELECT \"a\\:b\", \"\\:c\"\nFROM payments.\"t\\:1\"\nLIMIT 50", generated.escapedSql()); + } + + @Test + void aNameThatHoldsAControlCharacterIsANamedBadRequest() { + assertEquals( + "SQL generation does not support a name that holds a control character", + assertThrows(BadRequestException.class, () -> sqlFor(TRANSFERS, "Postgres", "transfer\nid")) + .getMessage()); + assertEquals( + "SQL generation does not support a name that holds a control character", + assertThrows( + BadRequestException.class, + () -> sqlFor("finance.warehouse.payments.\"trans\tfers\"", "Mysql", "transfer_id")) + .getMessage()); + } + + @Test + void aRelationLabelIsNoPartOfTheStatement() { + final BoundTable transfers = + withConstraints( + table(TRANSFERS, "Postgres", "transfer_id"), + foreignKey(List.of("customer_id"), CUSTOMERS, "customer_id")); + final String label = "part of\n; DROP TABLE customers; -- */"; + + final Generated generated = + OntologyConceptSqlGenerator.generate( + concept("Funds Transfer", transfers), + List.of( + new Hop( + PART_OF, + null, + label, + concept("Customer", table(CUSTOMERS, "Postgres", "name"))))); + + assertEquals( + "SELECT t1.name\nFROM payments.transfers t0\n" + + "JOIN payments.customers t1 ON t0.customer_id = t1.customer_id\nLIMIT 50", + generated.sql()); + } + @Test void aMissingBindingIsANamedBadRequest() { final BoundConcept unbound = new BoundConcept("Funds Transfer", List.of()); @@ -1040,6 +1236,28 @@ private static BoundConcept concept(final String label, final BoundTable table) return new BoundConcept(label, List.of(table)); } + private static OntologyRowFilter filter( + final String column, final OntologyRowFilterOperator operator, final Object value) { + return new OntologyRowFilter() + .withColumn(List.of(column)) + .withOperator(operator) + .withValue(value); + } + + /** The table with a row filter on a column of the given data type, parsed as a write parses it. */ + private static BoundTable filtered( + final BoundTable table, final ColumnDataType type, final OntologyRowFilter filter) { + final Column column = new Column().withName(filter.getColumn().getLast()).withDataType(type); + return new BoundTable( + table.fullyQualifiedName(), + table.serviceType(), + table.columns(), + table.objectColumns(), + table.identifier(), + table.constraints(), + () -> TypedValues.rowFilter(column, filter)); + } + private static BoundTable table( final String fqn, final String serviceType, final String... columns) { return new BoundTable( diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java new file mode 100644 index 000000000000..1298f5f8cbc0 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyCountRulesTest.java @@ -0,0 +1,919 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.openmetadata.schema.api.data.NativeOntologyCount; +import org.openmetadata.schema.api.data.NativeOntologyCount.State; +import org.openmetadata.schema.api.services.CreateDatabaseService.DatabaseServiceType; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.ColumnProfile; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.PartitionColumnDetails; +import org.openmetadata.schema.type.PartitionProfilerConfig; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TablePartition; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.schema.type.TableProfilerConfig; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyCountRules.ClassRows; +import org.openmetadata.service.ontology.OntologyCountRules.Facts; +import org.openmetadata.service.ontology.OntologyCountRules.Relation; + +/** + * Each case builds a class of orders whose identity table joins to a class of customers, hands the + * rules the catalog and the stored profiles, and reads the state and the number back. + */ +class OntologyCountRulesTest { + private static final long PROFILED_AT = 1_700_000_000_000L; + private static final UUID ORDER = new UUID(0, 1); + private static final UUID CUSTOMER = new UUID(0, 2); + private static final UUID PLACED_BY = new UUID(0, 3); + private static final UUID ORDERS_TABLE = new UUID(1, 1); + private static final UUID CUSTOMERS_TABLE = new UUID(1, 2); + private static final UUID LINKS_TABLE = new UUID(1, 3); + private static final String ORDERS_FQN = "shop.db.public.orders"; + private static final String CUSTOMERS_FQN = "shop.db.public.customers"; + + @Test + void aOneColumnKeyThatCoveredTheWholeTableCountsItsDistinctValues() { + final var world = new World(); + assertExact(100, world.records(ORDER)); + assertEquals(PROFILED_AT, world.records(ORDER).getProfiledAt()); + } + + @Test + void theTableRowCountIsNeverReadWhetherItIsAboveOrBelowTheDistinctValues() { + for (final double rowCount : new double[] {103, 97}) { + final var world = new World(); + world.tableProfile.withRowCount(rowCount); + assertExact(100, world.records(ORDER)); + } + } + + @Test + void aKeyWithDuplicatesStillCountsItsDistinctValuesButGivesNoLinks() { + final var world = new World(); + world.metrics("id", 100, 0, 90); + assertExact(90, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aSingleKeyColumnWithNullsCountsItsDistinctValuesButGivesNoLinks() { + final var world = new World(); + world.metrics("id", 95, 5, 95); + assertExact(95, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aTwoColumnDeclaredPrimaryKeyWithNoNullsCountsOnAnEnforcingEngine() { + final var world = World.twoColumnKey("Postgres"); + assertExact(100, world.records(ORDER)); + assertExact(100, world.links()); + } + + @Test + void aTwoColumnKeyWithNullsInOneColumnCountsTheValuesOfThatColumn() { + final var world = World.twoColumnKey("Postgres"); + world.metrics("tenant", 90, 10, 3); + assertExact(90, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aTwoColumnKeyWithNullsInTwoColumnsCountsNothing() { + final var world = World.twoColumnKey("Postgres"); + world.metrics("id", 90, 10, 90); + world.metrics("tenant", 90, 10, 3); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @ParameterizedTest + @ValueSource(strings = {"Snowflake", "BigQuery", "Redshift", "Databricks"}) + void aDeclaredKeyOnAnEngineThatDoesNotCheckItCountsNothing(final String engine) { + final var world = World.twoColumnKey(engine); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aDeclaredPrimaryKeyWithADuplicateInTheMetricsCountsDistinctValuesAndGivesNoLinks() { + final var world = new World(); + world.columnConstraint("id", ColumnConstraint.PRIMARY_KEY); + world.metrics("id", 100, 0, 90); + assertExact(90, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aDeclaredKeyWithNoMetricsGivesLinksOnAnEnforcingEngineAndNoRecords() { + final var world = new World(); + world.columnConstraint("id", ColumnConstraint.PRIMARY_KEY); + world.noMetrics("id"); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + assertExact(100, world.links()); + } + + @Test + void aDeclaredKeyWithNoMetricsGivesNoLinksOnAnEngineThatDoesNotCheckIt() { + final var world = new World().engine("Snowflake"); + world.columnConstraint("id", ColumnConstraint.PRIMARY_KEY); + world.noMetrics("id"); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aTwoColumnKeyWithNoDeclaredConstraintCountsNothing() { + final var world = World.twoColumnKey("Postgres"); + world.tableConstraints.clear(); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aUniqueConstraintOnOneOfTheTwoKeyColumnsMakesTheKeyUnique() { + final var world = World.twoColumnKey("Postgres"); + world.tableConstraints.clear(); + world.tableConstraint(TableConstraint.ConstraintType.UNIQUE, "id"); + assertExact(100, world.records(ORDER)); + assertExact(100, world.links()); + } + + @Test + void aSampledProfileByPercentageCountsNothing() { + final var world = new World(); + world + .tableProfile + .withProfileSample(50d) + .withProfileSampleType(TableProfile.ProfileSampleType.PERCENTAGE); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aProfileSampledAtOneHundredPercentCountsTheWholeTable() { + final var world = new World(); + world + .tableProfile + .withProfileSample(100d) + .withProfileSampleType(TableProfile.ProfileSampleType.PERCENTAGE); + assertExact(100, world.records(ORDER)); + assertExact(100, world.links()); + } + + @Test + void aFilledRowCapCountsNothing() { + final var world = new World(); + world + .tableProfile + .withProfileSample(100d) + .withProfileSampleType(TableProfile.ProfileSampleType.ROWS); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aRowCapThatTheColumnRowsStayBelowCountsTheWholeTable() { + final var world = new World(); + world + .tableProfile + .withProfileSample(1000d) + .withProfileSampleType(TableProfile.ProfileSampleType.ROWS); + assertExact(100, world.records(ORDER)); + assertExact(100, world.links()); + } + + @Test + void aTableWithAPartitionCountsNothing() { + final var world = new World(); + world.table.withTablePartition( + new TablePartition() + .withColumns(List.of(new PartitionColumnDetails().withColumnName("day")))); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aProfilerConfigWithPartitioningOnCountsNothing() { + final var world = new World(); + world.table.withTableProfilerConfig( + new TableProfilerConfig() + .withPartitioning(new PartitionProfilerConfig().withEnablePartitioning(true))); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aProfilerConfigWithPartitioningOffCountsTheWholeTable() { + final var world = new World(); + world.table.withTableProfilerConfig( + new TableProfilerConfig() + .withPartitioning(new PartitionProfilerConfig().withEnablePartitioning(false))); + assertExact(100, world.records(ORDER)); + assertExact(100, world.links()); + } + + @Test + void aProfilerConfigWithAProfileQueryCountsNothing() { + final var world = new World(); + world.table.withTableProfilerConfig( + new TableProfilerConfig().withProfileQuery("SELECT * FROM orders WHERE open")); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aColumnProfileOlderThanTheTableProfileCountsNothing() { + final var world = new World(); + world.columnProfiles.get(ORDERS_FQN + ".id").withTimestamp(PROFILED_AT - 1); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aRowFilterOnTheClassCountsNothing() { + final var world = new World(); + world.subjectFilter = filter(); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aRowFilterOnTheTargetOnlyKeepsTheRecordsOfTheSubjectAndDropsTheLinks() { + final var world = new World(); + world.objectFilter = filter(); + assertExact(100, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.records(CUSTOMER)); + assertState(State.NOT_DERIVABLE, world.links()); + final var unfiltered = new World(); + assertExact(50, unfiltered.records(CUSTOMER)); + } + + @Test + void aClassWithOnlyAContributingTableHasNoIdentityTable() { + final var world = new World(); + world.subjectRole = OntologyBindingRole.CONTRIBUTING; + assertState(State.NO_IDENTITY_TABLE, world.records(ORDER)); + assertState(State.NO_IDENTITY_TABLE, world.links()); + } + + @Test + void aClassThatBindsNoTableHasNoRecordsAndNoLinks() { + final var world = new World(); + world.subjectRows = List.of(); + assertNull(world.records(ORDER)); + assertNull(world.links()); + } + + @Test + void anIdentityTableTheCallerMayNotViewIsHidden() { + final var world = new World(); + world.tables.remove(ORDERS_TABLE); + assertState(State.IDENTITY_TABLE_HIDDEN, world.records(ORDER)); + assertState(State.IDENTITY_TABLE_HIDDEN, world.links()); + } + + @Test + void anIdentityTableThatWasDeletedIsHiddenInTheSameWay() { + final var world = new World(); + world.tables.remove(ORDERS_TABLE); + world.profileViewable.remove(ORDERS_TABLE); + world.tableProfiles.remove(ORDERS_TABLE); + assertState(State.IDENTITY_TABLE_HIDDEN, world.records(ORDER)); + } + + @Test + void aTargetIdentityTableTheCallerMayNotViewHidesTheLinks() { + final var world = new World(); + world.tables.remove(CUSTOMERS_TABLE); + assertExact(100, world.records(ORDER)); + assertState(State.IDENTITY_TABLE_HIDDEN, world.links()); + } + + @Test + void aTableWhoseDataProfileTheCallerMayNotViewHasNoProfile() { + final var world = new World(); + world.profileViewable.remove(ORDERS_TABLE); + assertState(State.NO_PROFILE, world.records(ORDER)); + assertState(State.NO_PROFILE, world.links()); + } + + @Test + void aTableWithNoStoredProfileHasNoProfile() { + final var world = new World(); + world.tableProfiles.remove(ORDERS_TABLE); + assertState(State.NO_PROFILE, world.records(ORDER)); + assertState(State.NO_PROFILE, world.links()); + } + + @Test + void aJoinThatIsOnlyInferredIsNotConfirmed() { + final var world = new World(); + world.joinStatus = OntologyJoinStatus.INFERRED; + assertExact(100, world.records(ORDER)); + assertState(State.JOIN_NOT_CONFIRMED, world.links()); + } + + @Test + void aRelationWithNoJoinOntoTheTargetHasNoJoin() { + final var world = new World(); + world.joinChildren = List.of(); + assertState(State.NO_JOIN, world.links()); + } + + @Test + void aTargetWithNoIdentityTableHasNoJoinOntoIt() { + final var world = new World(); + world.objectRole = OntologyBindingRole.CONTRIBUTING; + assertState(State.NO_JOIN, world.links()); + } + + @Test + void aJoinHeldByAContributingTableGivesNoLinks() { + final var world = new World(); + world.joinOnContributingTable = true; + assertExact(100, world.records(ORDER)); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aJoinWhoseParentColumnsAreInAnotherOrderThanTheTargetKeyGivesNoLinks() { + final var world = new World(); + world.objectKey = List.of(List.of("id"), List.of("tenant")); + world.joinChildren = List.of("customer_id", "region"); + world.joinParents = List.of("tenant", "id"); + world.metrics("region", 100, 0, 5); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aJoinOnTwoColumnsInTheOrderOfTheTargetKeyCounts() { + final var world = new World(); + world.objectKey = List.of(List.of("id"), List.of("tenant")); + world.joinChildren = List.of("customer_id", "region"); + world.joinParents = List.of("id", "tenant"); + world.metrics("region", 100, 0, 5); + assertExact(100, world.links()); + } + + @Test + void aJoinWithOneNullableChildColumnCountsTheValuesOfThatColumn() { + final var world = new World(); + world.objectKey = List.of(List.of("id"), List.of("tenant")); + world.joinChildren = List.of("customer_id", "region"); + world.joinParents = List.of("id", "tenant"); + world.metrics("region", 90, 10, 5); + assertExact(90, world.links()); + } + + @Test + void aJoinWithTwoNullableChildColumnsGivesNoLinks() { + final var world = new World(); + world.objectKey = List.of(List.of("id"), List.of("tenant")); + world.joinChildren = List.of("customer_id", "region"); + world.joinParents = List.of("id", "tenant"); + world.metrics("customer_id", 95, 5, 40); + world.metrics("region", 90, 10, 5); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aJoinColumnWithoutMetricsGivesNoLinks() { + final var world = new World(); + world.noMetrics("customer_id"); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void anEdgeWhoseTargetIsNotInThePageGivesNoLinks() { + final var world = new World(); + assertState(State.NOT_DERIVABLE, world.linksAmong(Map.of(ORDER, world.classes().get(ORDER)))); + } + + @Test + void anEdgeWhoseSubjectIsNotInThePageHasNoLinks() { + final var world = new World(); + assertNull(world.linksAmong(Map.of(CUSTOMER, world.classes().get(CUSTOMER)))); + } + + @Test + void aRelationThatNoViewablePropertyNamesGivesNoLinks() { + final var world = new World(); + assertState( + State.NOT_DERIVABLE, + OntologyCountRules.links( + new Relation(ORDER, CUSTOMER, null), world.classes(), world.facts())); + } + + @Test + void aClassThatBindsMoreContributingTablesThanAStatementAcceptsGivesNoJoinState() { + final var world = new World(); + world.joinChildren = List.of(); + world.truncated = true; + assertState(State.NOT_DERIVABLE, world.links()); + } + + @ParameterizedTest + @ValueSource(ints = {0, 4, 10, 16, 31}) + void aClassWithOtherTablesAndAnInferredJoinOnItsIdentityTableIsNotConfirmed(final int others) { + final var world = new World(); + world.joinStatus = OntologyJoinStatus.INFERRED; + world.otherTables = others; + assertState(State.JOIN_NOT_CONFIRMED, world.links()); + assertExact(100, world.records(ORDER)); + } + + @ParameterizedTest + @ValueSource(ints = {0, 4, 10, 16, 31}) + void aClassWithOtherTablesAndNoJoinHasNoJoin(final int others) { + final var world = new World(); + world.joinChildren = List.of(); + world.otherTables = others; + assertState(State.NO_JOIN, world.links()); + } + + @ParameterizedTest + @ValueSource(ints = {4, 10, 16, 31}) + void aClassWithOtherTablesAndAConfirmedJoinOnAContributingTableGivesNoLinks(final int others) { + final var world = new World(); + world.joinOnContributingTable = true; + world.otherTables = others; + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aJoinOnADeletedContributingTableHoldsNoJoin() { + final var world = new World(); + world.joinOnContributingTable = true; + world.deleted.add(LINKS_TABLE); + assertState(State.NO_JOIN, world.links()); + } + + @Test + void aConfirmedJoinOnADeletedContributingTableLeavesTheInferredJoinOfTheIdentityTable() { + final var world = new World(); + world.joinOnContributingTable = true; + world.identityJoinStatus = OntologyJoinStatus.INFERRED; + assertState(State.NOT_DERIVABLE, world.links()); + world.deleted.add(LINKS_TABLE); + assertState(State.JOIN_NOT_CONFIRMED, world.links()); + } + + @Test + void aCutClassWithNoConfirmedJoinNeedsAFullRead() { + final var world = new World(); + world.joinChildren = List.of(); + world.truncated = true; + assertEquals( + true, OntologyCountRules.needsAFullRead(world.relation(), world.classes(), world.facts())); + } + + @Test + void aCutClassWhoseRowsHoldAConfirmedJoinNeedsNoFullRead() { + final var world = new World(); + world.truncated = true; + assertEquals( + false, OntologyCountRules.needsAFullRead(world.relation(), world.classes(), world.facts())); + } + + @Test + void aClassThatWasNotCutNeedsNoFullRead() { + final var world = new World(); + world.joinChildren = List.of(); + assertEquals( + false, OntologyCountRules.needsAFullRead(world.relation(), world.classes(), world.facts())); + } + + @Test + void aCutClassWhoseIdentityTableGivesNoCountNeedsNoFullRead() { + final var world = new World(); + world.joinChildren = List.of(); + world.truncated = true; + world.tableProfiles.remove(ORDERS_TABLE); + assertEquals( + false, OntologyCountRules.needsAFullRead(world.relation(), world.classes(), world.facts())); + } + + static Stream transformedPairs() { + final var sqlServer = + List.of( + ColumnDataType.TEXT, + ColumnDataType.MEDIUMTEXT, + ColumnDataType.NTEXT, + ColumnDataType.IMAGE); + final var oracle = + List.of( + ColumnDataType.BYTES, + ColumnDataType.BYTEA, + ColumnDataType.BINARY, + ColumnDataType.VARBINARY, + ColumnDataType.BLOB); + return Stream.concat( + Stream.of("Mssql", "AzureSQL", "Synapse", "MicrosoftFabric") + .flatMap(engine -> sqlServer.stream().map(type -> Arguments.of(engine, type))), + oracle.stream().map(type -> Arguments.of("Oracle", type))); + } + + @ParameterizedTest + @MethodSource("transformedPairs") + void aOneColumnKeyOfATypeTheProfilerTransformsBeforeCountingGivesNoRecords( + final String engine, final ColumnDataType type) { + final var world = new World().engine(engine); + world.columnType("id", type); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + } + + @ParameterizedTest + @ValueSource(strings = {"Mssql", "AzureSQL", "Synapse", "MicrosoftFabric", "Oracle"}) + void theSameKeyAsAVarcharOnTheSameEngineCountsItsDistinctValues(final String engine) { + final var world = new World().engine(engine); + world.columnType("id", ColumnDataType.VARCHAR); + assertExact(100, world.records(ORDER)); + } + + @ParameterizedTest + @CsvSource({ + "Postgres,TEXT", + "Mysql,TEXT", + "Mssql,BYTES", + "Mssql,VARBINARY", + "Mssql,BLOB", + "Oracle,TEXT", + "Oracle,IMAGE", + "Oracle,LONGBLOB", + "Snowflake,BYTES" + }) + void aTypeTheProfilerDoesNotTransformOnThatEngineStillCountsItsDistinctValues( + final String engine, final ColumnDataType type) { + final var world = new World().engine(engine); + world.columnType("id", type); + assertExact(100, world.records(ORDER)); + } + + @Test + void aTransformedKeyStillGivesLinksBecauseTheyReadOnlyValuesAndNulls() { + final var world = new World().engine("Mssql"); + world.columnType("id", ColumnDataType.TEXT); + assertExact(100, world.links()); + world.metrics("id", 100, 0, 99); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void aTransformedColumnOfAKeyOfSeveralColumnsStillCountsItsValues() { + final var world = World.twoColumnKey("Oracle"); + world.columnType("tenant", ColumnDataType.BLOB); + assertExact(100, world.records(ORDER)); + } + + // Dataframe profilers (Datalake, BurstIQ) cast every chunk before counting, statistics + // profilers (Trino, StarRocks) can estimate, and the SAS connector writes the catalog's + // statistics as the profile, so a table of these service types gives no exact count. + + @ParameterizedTest + @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks", "SAS"}) + void aOneColumnKeyOnAServiceTypeThatGivesNoExactCountHasNoRecords(final String engine) { + final var world = new World().engine(engine); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + } + + @ParameterizedTest + @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks", "SAS"}) + void aRelationWhoseChildColumnIsOnAServiceTypeThatGivesNoExactCountHasNoLinks( + final String engine) { + final var world = new World().engine(engine); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @ParameterizedTest + @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks", "SAS"}) + void aDeclaredKeyOfSeveralNotNullColumnsOnAServiceTypeThatGivesNoExactCountHasNoRecords( + final String engine) { + final var world = World.twoColumnKey(engine); + world.columnConstraint("id", ColumnConstraint.NOT_NULL); + world.columnConstraint("tenant", ColumnConstraint.NOT_NULL); + assertState(State.NOT_DERIVABLE, world.records(ORDER)); + } + + @ParameterizedTest + @ValueSource(strings = {"Datalake", "BurstIQ", "Trino", "StarRocks", "SAS"}) + void aDeclaredPrimaryKeyOnAServiceTypeThatGivesNoExactCountHasNoLinks(final String engine) { + final var world = new World().engine(engine); + world.tableConstraint(TableConstraint.ConstraintType.PRIMARY_KEY, "id"); + world.columnConstraint("id", ColumnConstraint.NOT_NULL); + assertState(State.NOT_DERIVABLE, world.links()); + } + + // The SAS connector stores the table's row count as valuesCount, so a column of 9 rows with 2 + // missing has valuesCount 9, nullCount 2 and distinctCount 4, and the nulls are counted. + + @Test + void aSasProfileThatCountsTheNullRowsGivesNoLinks() { + final var world = new World().engine("SAS"); + world.metrics("customer_id", 9, 2, 4); + assertState(State.NOT_DERIVABLE, world.links()); + } + + @Test + void theSameProfileOnPostgresGivesTheValuesCountAsLinks() { + final var world = new World().engine("Postgres"); + world.metrics("customer_id", 9, 2, 4); + assertExact(9, world.links()); + } + + @ParameterizedTest + @ValueSource( + strings = {"Postgres", "Mysql", "Snowflake", "BigQuery", "Redshift", "Databricks", "Hive"}) + void aServiceTypeThatCountsOverTheRowsGivesRecordsAndLinks(final String engine) { + final var world = new World().engine(engine).targetEngine(engine); + assertExact(100, world.records(ORDER)); + assertExact(100, world.links()); + } + + private static OntologyRowFilter filter() { + return new OntologyRowFilter() + .withColumn(List.of("status")) + .withOperator(OntologyRowFilterOperator.EQUALS) + .withValue("open"); + } + + private static void assertExact(final long value, final NativeOntologyCount count) { + assertEquals(State.EXACT, count.getState()); + assertEquals(value, count.getValue()); + } + + private static void assertState(final State state, final NativeOntologyCount count) { + assertEquals(state, count.getState()); + assertNull(count.getValue()); + assertNull(count.getProfiledAt()); + } + + /** + * An orders table with the key {@code id} and a join from {@code customer_id} onto a customers + * table, on Postgres, whose profile covered the whole table: every column holds 100 values, none + * is null, and {@code id} is distinct. + */ + private static final class World { + final Table table; + final Table customers; + final TableProfile tableProfile; + final Map tables = new HashMap<>(); + final Set profileViewable = new HashSet<>(Set.of(ORDERS_TABLE, CUSTOMERS_TABLE)); + final Map tableProfiles = new HashMap<>(); + final Map columnProfiles = new HashMap<>(); + final List tableConstraints = new ArrayList<>(); + List> subjectKey = List.of(List.of("id")); + List> objectKey = List.of(List.of("id")); + List joinChildren = List.of("customer_id"); + List joinParents = List.of("id"); + OntologyJoinStatus joinStatus = OntologyJoinStatus.CONFIRMED; + OntologyBindingRole subjectRole = OntologyBindingRole.IDENTITY; + OntologyBindingRole objectRole = OntologyBindingRole.IDENTITY; + OntologyRowFilter subjectFilter; + OntologyRowFilter objectFilter; + boolean joinOnContributingTable; + boolean truncated; + int otherTables; + OntologyJoinStatus identityJoinStatus; + final Set deleted = new HashSet<>(); + List subjectRows; + + World() { + table = + new Table() + .withId(ORDERS_TABLE) + .withFullyQualifiedName(ORDERS_FQN) + .withServiceType(DatabaseServiceType.Postgres) + .withColumns( + List.of( + column(ORDERS_FQN, "id"), + column(ORDERS_FQN, "tenant"), + column(ORDERS_FQN, "customer_id"), + column(ORDERS_FQN, "region"))); + customers = + new Table() + .withId(CUSTOMERS_TABLE) + .withFullyQualifiedName(CUSTOMERS_FQN) + .withServiceType(DatabaseServiceType.Postgres) + .withColumns(List.of(column(CUSTOMERS_FQN, "id"), column(CUSTOMERS_FQN, "tenant"))); + tableProfile = new TableProfile().withTimestamp(PROFILED_AT); + tables.put(ORDERS_TABLE, table); + tables.put(CUSTOMERS_TABLE, customers); + tableProfiles.put(ORDERS_TABLE, tableProfile); + tableProfiles.put(CUSTOMERS_TABLE, new TableProfile().withTimestamp(PROFILED_AT)); + columnProfiles.put( + CUSTOMERS_FQN + ".id", + new ColumnProfile() + .withName("id") + .withTimestamp(PROFILED_AT) + .withValuesCount(50d) + .withNullCount(0d) + .withDistinctCount(50d)); + for (final String name : List.of("id", "tenant", "customer_id", "region")) { + metrics(name, 100, 0, name.equals("id") ? 100 : 40); + } + } + + static World twoColumnKey(final String engine) { + final World world = new World().engine(engine); + world.subjectKey = List.of(List.of("id"), List.of("tenant")); + world.tableConstraint(TableConstraint.ConstraintType.PRIMARY_KEY, "id", "tenant"); + world.metrics("id", 100, 0, 100); + world.metrics("tenant", 100, 0, 3); + return world; + } + + World engine(final String engine) { + table.withServiceType(DatabaseServiceType.fromValue(engine)); + return this; + } + + World targetEngine(final String engine) { + customers.withServiceType(DatabaseServiceType.fromValue(engine)); + return this; + } + + void metrics( + final String column, final double values, final double nulls, final double distinct) { + columnProfiles.put( + ORDERS_FQN + "." + column, + new ColumnProfile() + .withName(column) + .withTimestamp(PROFILED_AT) + .withValuesCount(values) + .withNullCount(nulls) + .withDistinctCount(distinct)); + } + + void noMetrics(final String column) { + columnProfiles.remove(ORDERS_FQN + "." + column); + } + + void tableConstraint(final TableConstraint.ConstraintType type, final String... columns) { + tableConstraints.add( + new TableConstraint().withConstraintType(type).withColumns(List.of(columns))); + } + + void columnConstraint(final String name, final ColumnConstraint constraint) { + table.getColumns().stream() + .filter(column -> column.getName().equals(name)) + .forEach(column -> column.setConstraint(constraint)); + } + + NativeOntologyCount records(final UUID type) { + return OntologyCountRules.records(classes().get(type), facts()); + } + + NativeOntologyCount links() { + return linksAmong(classes()); + } + + Relation relation() { + return new Relation(ORDER, CUSTOMER, PLACED_BY); + } + + void columnType(final String name, final ColumnDataType type) { + table.getColumns().stream() + .filter(column -> column.getName().equals(name)) + .forEach(column -> column.setDataType(type)); + } + + NativeOntologyCount linksAmong(final Map classes) { + return OntologyCountRules.links(new Relation(ORDER, CUSTOMER, PLACED_BY), classes, facts()); + } + + Facts facts() { + table.withTableConstraints(tableConstraints); + return new Facts(tables, profileViewable, tableProfiles, columnProfiles, deleted); + } + + Map classes() { + final Map classes = new LinkedHashMap<>(); + classes.put( + ORDER, new ClassRows(ORDER, subjectRows == null ? orderRows() : subjectRows, truncated)); + classes.put( + CUSTOMER, + new ClassRows( + CUSTOMER, + List.of( + row(CUSTOMER, CUSTOMERS_TABLE, objectRole, objectKey, objectFilter, List.of())), + false)); + return classes; + } + + private List orderRows() { + final var rows = new ArrayList(); + if (joinOnContributingTable) { + final var identityJoin = + identityJoinStatus == null + ? List.of() + : List.of(joinColumn(identityJoinStatus)); + rows.add(row(ORDER, ORDERS_TABLE, subjectRole, subjectKey, subjectFilter, identityJoin)); + rows.add( + row( + ORDER, + LINKS_TABLE, + OntologyBindingRole.CONTRIBUTING, + subjectKey, + null, + List.of(joinColumn(joinStatus)))); + } else { + rows.add( + row( + ORDER, + ORDERS_TABLE, + subjectRole, + subjectKey, + subjectFilter, + joinChildren.isEmpty() ? List.of() : List.of(joinColumn(joinStatus)))); + } + for (int index = 0; index < otherTables; index++) { + rows.add( + row( + ORDER, + new UUID(2, index + 1), + OntologyBindingRole.CONTRIBUTING, + subjectKey, + null, + List.of())); + } + return rows; + } + + private OntologyColumnBinding joinColumn(final OntologyJoinStatus status) { + return new OntologyColumnBinding() + .withPropertyId(PLACED_BY) + .withColumnPath(List.of(joinChildren.isEmpty() ? "customer_id" : joinChildren.getFirst())) + .withJoin( + new OntologyColumnJoin() + .withTargetAssetId(CUSTOMERS_TABLE) + .withStatus(status) + .withOn( + IntStream.range(0, joinChildren.size()) + .mapToObj( + part -> + new OntologyJoinColumnPair() + .withChild(List.of(joinChildren.get(part))) + .withParent(List.of(joinParents.get(part)))) + .toList())); + } + + private static Column column(final String table, final String name) { + return new Column().withName(name).withFullyQualifiedName(table + "." + name); + } + + private static BindingRow row( + final UUID type, + final UUID asset, + final OntologyBindingRole role, + final List> key, + final OntologyRowFilter filter, + final List columns) { + return new BindingRow( + type, asset, OntologyBindingAssetType.TABLE, "hash", columns, role, key, filter); + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedBindingShapeKeysTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedBindingShapeKeysTest.java new file mode 100644 index 000000000000..a5bfd43b7df8 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedBindingShapeKeysTest.java @@ -0,0 +1,213 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyColumnBindingChange; +import org.openmetadata.schema.type.OntologyJoinChange; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; + +class OntologyDeclinedBindingShapeKeysTest { + private static final URI ORDER = URI.create("https://example.org/sales/Order"); + private static final URI TOTAL = URI.create("https://example.org/sales/total"); + private static final URI PLACED_BY = URI.create("https://example.org/sales/placedBy"); + private static final UUID ORDERS = UUID.fromString("00000000-0000-0000-0000-0000000000c1"); + private static final UUID ARCHIVE = UUID.fromString("00000000-0000-0000-0000-0000000000c2"); + private static final UUID CUSTOMERS = UUID.fromString("00000000-0000-0000-0000-0000000000c3"); + + @Test + void aBindingStandsUnderItsClassAndTheSameBindingGivesTheSameKey() { + final OntologyDeclinedDefinitions.Key key = OntologyDeclinedDefinitions.keyOf(bind(binding())); + + assertEquals(OntologyChangeOperationType.UPSERT_BINDING, key.type()); + assertEquals(ORDER, key.iri()); + assertEquals( + "3340e728db85bac61ad750b27a4ed386e92603077584872306aa0a1489e36960", key.payloadDigest()); + assertEquals(key, OntologyDeclinedDefinitions.keyOf(bind(binding()))); + } + + @Test + void theOrderOfColumnsAndOfJoinPairsDoesNotChangeTheKey() { + final OntologyChangeOperation forward = bind(binding()); + final OntologyChangeOperation reversed = + bind( + binding() + .withColumns( + List.of( + column(PLACED_BY, "customer_id").withJoin(join(true)), + column(TOTAL, "total")))); + + assertEquals( + OntologyDeclinedDefinitions.keyOf(forward), OntologyDeclinedDefinitions.keyOf(reversed)); + } + + @Test + void aBindingThatMapsOtherColumnsOrOtherJoinsGivesTheSameKey() { + final String base = digest(bind(binding())); + + assertEquals(base, digest(bind(binding().withColumns(List.of(column(TOTAL, "total")))))); + assertEquals( + base, + digest( + bind( + binding() + .withColumns( + List.of(column(PLACED_BY, "customer_id").withJoin(join(false))))))); + assertEquals(base, digest(bind(binding().withColumns(List.of())))); + assertEquals(base, digest(bind(binding().withColumns(null)))); + assertEquals( + base, + digest( + bind( + binding() + .withColumns( + List.of( + column(TOTAL, "total"), + column(PLACED_BY, "region").withJoin(join(true))))))); + } + + @Test + void anotherTableKeyRoleOrFilterGivesAnotherKey() { + final String base = digest(bind(binding())); + + assertNotEquals(base, digest(bind(binding().withTableId(ARCHIVE)))); + assertNotEquals(base, digest(bind(binding().withSubjectKey(List.of(List.of("customer_id")))))); + assertNotEquals(base, digest(bind(binding().withRole(OntologyBindingRole.CONTRIBUTING)))); + assertNotEquals(base, digest(bind(binding().withRole(null).withSubjectKey(null)))); + assertNotEquals(base, digest(bind(binding().withRowFilter(filter("kind", "a"))))); + assertNotEquals( + digest(bind(binding().withRowFilter(filter("kind", "a")))), + digest(bind(binding().withRowFilter(filter("kind", "b"))))); + } + + @Test + void aBindingWithNoRoleKeysTheSameWhetherTheRoleIsAbsentOrNull() { + assertEquals( + digest(bind(binding().withRole(null).withSubjectKey(null))), + digest(bind(binding().withRole(null).withSubjectKey(List.of())))); + } + + @Test + void aBindingWithoutAClassOrAPayloadHasNoKey() { + assertNull(OntologyDeclinedDefinitions.keyOf(bind(binding().withClassIri(null)))); + assertNull(OntologyDeclinedDefinitions.keyOf(bind(null))); + } + + @Test + void aShapeStandsUnderItsTargetAndTheSameConstraintsGiveTheSameKeyUnderFreshIds() { + final OntologyDeclinedDefinitions.Key key = OntologyDeclinedDefinitions.keyOf(shape(1)); + + assertEquals(OntologyChangeOperationType.UPSERT_SHAPE, key.type()); + assertEquals(ORDER, key.iri()); + assertEquals( + "af92f5f77002c55066295abe459c9a12c9a4541ba6dc491296552bd1c80c5a7e", key.payloadDigest()); + assertEquals(key, OntologyDeclinedDefinitions.keyOf(shape(1))); + } + + @Test + void anotherConstraintGivesAnotherShapeKey() { + assertNotEquals(digest(shape(1)), digest(shape(2))); + final OntologyChangeOperation otherPath = shape(1); + otherPath.getShape().getConstraints().getFirst().setPath(PLACED_BY); + assertNotEquals(digest(shape(1)), digest(otherPath)); + } + + @Test + void aShapeWithoutATargetHasNoKey() { + final OntologyChangeOperation untargeted = shape(1); + untargeted.getShape().setTargetConcept(null); + assertNull(OntologyDeclinedDefinitions.keyOf(untargeted)); + } + + private static String digest(final OntologyChangeOperation operation) { + return OntologyDeclinedDefinitions.keyOf(operation).payloadDigest(); + } + + private static OntologyChangeOperation bind(final OntologyBindingChange binding) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBinding(binding); + } + + private static OntologyBindingChange binding() { + return new OntologyBindingChange() + .withClassIri(ORDER) + .withTableId(ORDERS) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of("order_id"))) + .withColumns( + List.of( + column(TOTAL, "total"), column(PLACED_BY, "customer_id").withJoin(join(false)))); + } + + private static OntologyRowFilter filter(final String column, final String value) { + return new OntologyRowFilter() + .withColumn(List.of(column)) + .withOperator(OntologyRowFilterOperator.EQUALS) + .withValue(value); + } + + private static OntologyColumnBindingChange column(final URI property, final String column) { + return new OntologyColumnBindingChange() + .withPropertyIri(property) + .withColumnPath(List.of(column)); + } + + private static OntologyJoinChange join(final boolean reversed) { + final List pairs = + List.of(pair("customer_id", "id"), pair("region", "region")); + return new OntologyJoinChange() + .withTargetAssetId(CUSTOMERS) + .withOn(reversed ? pairs.reversed() : pairs); + } + + private static OntologyJoinColumnPair pair(final String child, final String parent) { + return new OntologyJoinColumnPair().withChild(List.of(child)).withParent(List.of(parent)); + } + + private static OntologyChangeOperation shape(final int minCount) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_SHAPE) + .withShape( + new OntologyShape() + .withId(UUID.randomUUID()) + .withName("orderShape") + .withTargetConcept(ORDER) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints( + List.of( + new OntologyShapeConstraint() + .withId("stated") + .withPath(TOTAL) + .withMinCount(minCount)))); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitionsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitionsTest.java new file mode 100644 index 000000000000..e9441d32149b --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDeclinedDefinitionsTest.java @@ -0,0 +1,257 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyDeclinedDefinition; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionMatch; +import org.openmetadata.schema.type.OntologyDeclinedDefinitionPage; +import org.openmetadata.service.jdbi3.OntologyDeclinedDefinitionDAO; +import org.openmetadata.service.jdbi3.OntologyDeclinedDefinitionDAO.StoredDeclinedDefinition; + +class OntologyDeclinedDefinitionsTest { + private static final UUID ONTOLOGY = UUID.fromString("00000000-0000-0000-0000-0000000000b1"); + private static final EntityReference ONTOLOGY_REFERENCE = + new EntityReference().withId(ONTOLOGY).withType("ontology"); + + private final InMemoryRecords records = new InMemoryRecords(); + private final OntologyDeclinedDefinitions declined = + new OntologyDeclinedDefinitions( + records, Clock.fixed(Instant.ofEpochMilli(1_763_800_000_000L), ZoneOffset.UTC)); + + @Test + void decliningTwoOperationsWritesTwoRecordsAndDecliningThemAgainWritesNone() { + final OntologyChangeOperation order = concept("Order", "An order"); + final OntologyChangeOperation customer = concept("Customer", "A customer"); + final OntologyChangeSet draft = draft(order, customer); + + final OntologyDeclinedDefinitionPage first = + declined.decline(draft, List.of(order.getId(), customer.getId()), "not wanted", "ana"); + final OntologyDeclinedDefinitionPage again = + declined.decline(draft, List.of(order.getId(), customer.getId()), "other reason", "bo"); + + assertEquals(2, records.rows.size()); + assertEquals(first.getRecords(), again.getRecords()); + assertEquals( + List.of("ana", "ana"), + again.getRecords().stream().map(OntologyDeclinedDefinition::getDeclinedBy).toList()); + assertEquals( + List.of("not wanted", "not wanted"), + again.getRecords().stream().map(OntologyDeclinedDefinition::getReason).toList()); + assertEquals(draft.getId(), first.getRecords().getFirst().getChangeSetId()); + assertEquals(order.getId(), first.getRecords().getFirst().getOperationId()); + assertEquals(1_763_800_000_000L, first.getRecords().getFirst().getDeclinedAt()); + } + + @Test + void aNewDraftOfTheSameDefinitionsWithFreshIdsMatchesAndAChangedDefinitionDoesNot() { + final OntologyChangeOperation order = concept("Order", "An order"); + final OntologyChangeOperation customer = concept("Customer", "A customer"); + declined.decline(draft(order, customer), List.of(order.getId(), customer.getId()), null, "ana"); + + final OntologyChangeOperation freshOrder = concept("Order", "An order"); + final OntologyChangeOperation changedCustomer = concept("Customer", "A buyer"); + final List matches = + declined.match(ONTOLOGY, List.of(freshOrder, changedCustomer)).getMatches(); + + assertEquals( + List.of(freshOrder.getId(), changedCustomer.getId()), + matches.stream().map(OntologyDeclinedDefinitionMatch::getOperationId).toList()); + assertTrue(matches.get(0).getDeclined()); + assertEquals(order.getId(), matches.get(0).getRecord().getOperationId()); + assertFalse(matches.get(1).getDeclined()); + assertNull(matches.get(1).getRecord()); + assertEquals( + OntologyDefinitionDigest.of(changedCustomer.getConcept()), + matches.get(1).getPayloadDigest()); + } + + @Test + void aDeclinedDefinitionDoesNotMatchInAnotherOntology() { + final OntologyChangeOperation order = concept("Order", "An order"); + declined.decline(draft(order), List.of(order.getId()), null, "ana"); + + final UUID other = UUID.fromString("00000000-0000-0000-0000-0000000000b2"); + + assertFalse(declined.match(other, List.of(order)).getMatches().getFirst().getDeclined()); + } + + @Test + void anOperationWithoutADefinitionIsNeverDeclined() { + final OntologyChangeOperation delete = + new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.DELETE_CONCEPT) + .withTargetId(UUID.randomUUID()); + + final OntologyDeclinedDefinitionMatch match = + declined.match(ONTOLOGY, List.of(delete)).getMatches().getFirst(); + assertFalse(match.getDeclined()); + assertNull(match.getPayloadDigest()); + assertThrows( + BadRequestException.class, + () -> declined.decline(draft(delete), List.of(delete.getId()), null, "ana")); + } + + @Test + void refusesAnOperationThatIsNotInTheChangeSet() { + final OntologyChangeOperation order = concept("Order", "An order"); + final UUID stranger = UUID.randomUUID(); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> declined.decline(draft(order), List.of(order.getId(), stranger), null, "ana")); + + assertTrue(refusal.getMessage().startsWith("Operation '" + stranger + "' is not part of")); + assertTrue(records.rows.isEmpty(), "a refused request records nothing"); + } + + @Test + void listsInTheOrderDecidedAndPagesWithACursor() { + final List operations = new ArrayList<>(); + for (int index = 0; index < 5; index++) { + operations.add(concept("Class" + index, "Class " + index)); + } + final OntologyChangeSet draft = draft(operations.toArray(OntologyChangeOperation[]::new)); + declined.decline( + draft, operations.stream().map(OntologyChangeOperation::getId).toList(), null, "ana"); + + final OntologyDeclinedDefinitionPage first = declined.list(ONTOLOGY, 2, null); + final OntologyDeclinedDefinitionPage second = declined.list(ONTOLOGY, 2, first.getAfter()); + final OntologyDeclinedDefinitionPage third = declined.list(ONTOLOGY, 2, second.getAfter()); + + assertEquals( + List.of(2, 2, 1), + List.of(first.getRecords().size(), second.getRecords().size(), third.getRecords().size())); + assertNull(third.getAfter()); + assertEquals( + 5, + java.util.stream.Stream.of(first, second, third) + .flatMap(page -> page.getRecords().stream()) + .map(OntologyDeclinedDefinition::getOperationId) + .distinct() + .count()); + assertThrows(BadRequestException.class, () -> declined.list(ONTOLOGY, 2, "not-a-cursor")); + } + + private static OntologyChangeSet draft(final OntologyChangeOperation... operations) { + return new OntologyChangeSet() + .withId(UUID.randomUUID()) + .withOntology(ONTOLOGY_REFERENCE) + .withOperations(List.of(operations)); + } + + private static OntologyChangeOperation concept(final String name, final String description) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_CONCEPT) + .withConcept( + new OntologyConcept() + .withId(UUID.randomUUID()) + .withName(name) + .withDescription(description) + .withOntology(ONTOLOGY_REFERENCE) + .withIri(URI.create("https://example.org/sales/" + name))); + } + + /** Keeps rows as the database would, with its key and its list order. */ + private static final class InMemoryRecords implements OntologyDeclinedDefinitionDAO { + private final List rows = new ArrayList<>(); + + @Override + public void insertIfAbsent(final StoredDeclinedDefinition row) { + if (rows.stream().noneMatch(stored -> key(stored).equals(key(row)))) { + rows.add(row); + } + } + + @Override + public void deleteByOntology(final String ontologyId) { + rows.removeIf(row -> row.ontologyId().equals(ontologyId)); + } + + @Override + public List findByIriHashes( + final String ontologyId, final List iriHashes) { + return rows.stream() + .filter(row -> row.ontologyId().equals(ontologyId) && iriHashes.contains(row.iriHash())) + .map(InMemoryRecords::toRecord) + .toList(); + } + + @Override + public List listAfter( + final String ontologyId, + final boolean hasAfter, + final long afterAt, + final String afterType, + final String afterIriHash, + final String afterDigest, + final int limit) { + final String after = + "%020d|%s|%s|%s".formatted(afterAt, afterType, afterIriHash, afterDigest); + return rows.stream() + .filter(row -> row.ontologyId().equals(ontologyId)) + .sorted(Comparator.comparing(InMemoryRecords::order)) + .filter(row -> !hasAfter || order(row).compareTo(after) > 0) + .limit(limit) + .map(InMemoryRecords::toRecord) + .collect(Collectors.toList()); + } + + private static String order(final StoredDeclinedDefinition row) { + return "%020d|%s|%s|%s" + .formatted(row.declinedAt(), row.operationType(), row.iriHash(), row.payloadDigest()); + } + + private static String key(final StoredDeclinedDefinition row) { + return row.ontologyId() + row.operationType() + row.iriHash() + row.payloadDigest(); + } + + private static OntologyDeclinedDefinition toRecord(final StoredDeclinedDefinition row) { + return new OntologyDeclinedDefinition() + .withOntologyId(UUID.fromString(row.ontologyId())) + .withOperationType(OntologyChangeOperationType.fromValue(row.operationType())) + .withIri(URI.create(row.iri())) + .withPayloadDigest(row.payloadDigest()) + .withDeclinedBy(row.declinedBy()) + .withDeclinedAt(row.declinedAt()) + .withReason(row.reason()) + .withChangeSetId(UUID.fromString(row.changeSetId())) + .withOperationId(UUID.fromString(row.operationId())); + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDefinitionDigestTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDefinitionDigestTest.java new file mode 100644 index 000000000000..47a9de2744b8 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDefinitionDigestTest.java @@ -0,0 +1,457 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.UUID; +import java.util.stream.Stream; +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.entity.data.OntologyAxiom; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyConceptType; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.utils.JsonUtils; + +class OntologyDefinitionDigestTest { + private static final UUID ONTOLOGY = UUID.fromString("00000000-0000-0000-0000-0000000000a1"); + private static final String ONTOLOGY_JSON = + "{\"id\":\"00000000-0000-0000-0000-0000000000a1\",\"type\":\"ontology\"}"; + private static final String ORDER_CANONICAL = + "{\"abstract\":false,\"conceptType\":\"OWL_CLASS\",\"deleted\":false,\"deprecated\":false,\"description\":\"A purchase a customer placed\",\"displayName\":\"Order\",\"fullyQualifiedName\":\"sales.Order\",\"iri\":\"https://example.org/sales/Order\",\"name\":\"Order\",\"ontology\":{\"id\":\"00000000-0000-0000-0000-0000000000a1\",\"type\":\"ontology\"},\"provider\":\"user\"}"; + private static final String ORDER_DIGEST = + "d1bef0ebba86898d77e8b761c7d6c1c67a6de316a2d48a8e1595a714077b991b"; + private static final String TOTAL_CANONICAL = + "{\"deleted\":false,\"deprecated\":false,\"domain\":[\"https://example.org/sales/Order\"],\"fullyQualifiedName\":\"sales.total\",\"iri\":\"https://example.org/sales/total\",\"isIdentifier\":false,\"kind\":\"DATA\",\"name\":\"total\",\"ontology\":{\"id\":\"00000000-0000-0000-0000-0000000000a1\",\"type\":\"ontology\"},\"provider\":\"user\",\"range\":[\"http://www.w3.org/2001/XMLSchema#decimal\"]}"; + private static final String TOTAL_DIGEST = + "dede90b4844e19579b0fc16accf3937493626d37d4cc668960eb95bdece30d10"; + + /** The 21 fields that carry a schema default in a concept, a property or an axiom. */ + private static Stream fieldsWithADefault() { + return Stream.concat( + Stream.of( + "synonyms", + "conceptMappings", + "deleted", + "provider", + "abstract", + "deprecated", + "superClasses", + "subClasses") + .map(field -> Arguments.of(OntologyConcept.class, ORDER_JSON, field)), + Stream.concat( + Stream.of( + "deleted", + "provider", + "domain", + "range", + "enumValues", + "isIdentifier", + "characteristics", + "propertyChain", + "disjointWith", + "superProperties", + "deprecated") + .map(field -> Arguments.of(OntologyProperty.class, TOTAL_JSON, field)), + Stream.of("deleted", "provider") + .map(field -> Arguments.of(OntologyAxiom.class, AXIOM_JSON, field)))); + } + + private static final String ORDER_JSON = + "{\"name\":\"Order\",\"fullyQualifiedName\":\"sales.Order\",\"displayName\":\"Order\"," + + "\"description\":\"A purchase a customer placed\"," + + "\"iri\":\"https://example.org/sales/Order\",\"conceptType\":\"OWL_CLASS\"," + + "\"ontology\":" + + ONTOLOGY_JSON + + "}"; + private static final String TOTAL_JSON = + "{\"name\":\"total\",\"fullyQualifiedName\":\"sales.total\"," + + "\"iri\":\"https://example.org/sales/total\",\"kind\":\"DATA\"," + + "\"domain\":[\"https://example.org/sales/Order\"]," + + "\"range\":[\"http://www.w3.org/2001/XMLSchema#decimal\"],\"ontology\":" + + ONTOLOGY_JSON + + "}"; + private static final String AXIOM_JSON = + "{\"name\":\"orderIsAThing\",\"axiomType\":\"SUBCLASS_OF\"," + + "\"subjectIri\":\"https://example.org/sales/Order\"," + + "\"targetIri\":\"https://example.org/sales/Thing\",\"ontology\":" + + ONTOLOGY_JSON + + "}"; + + @Test + void aClassHasTheDigestOfItsCanonicalContent() { + assertEquals(ORDER_CANONICAL, OntologyDefinitionDigest.canonicalJson(order())); + assertEquals(ORDER_DIGEST, OntologyDefinitionDigest.of(order())); + } + + @Test + void aPropertyHasTheDigestOfItsCanonicalContent() { + assertEquals(TOTAL_CANONICAL, OntologyDefinitionDigest.canonicalJson(total())); + assertEquals(TOTAL_DIGEST, OntologyDefinitionDigest.of(total())); + } + + @Test + void theDigestIsTheSha256OfTheCompactUtf8Text() { + final OntologyConcept accented = order().withDisplayName("Commande été"); + final String canonical = OntologyDefinitionDigest.canonicalJson(accented); + + assertTrue(canonical.contains("\"displayName\":\"Commande été\""), canonical); + assertFalse(canonical.contains("\\u00e9"), canonical); + assertFalse(canonical.contains(": ") || canonical.contains(", "), canonical); + assertEquals( + DigestUtils.sha256Hex(canonical.getBytes(StandardCharsets.UTF_8)), + OntologyDefinitionDigest.of(accented)); + } + + @Test + void aNumberKeepsNoTrailingZerosSoTenIsWrittenAsOneETen() { + final OntologyAxiom restricted = + JsonUtils.readValue( + "{\"name\":\"r\",\"axiomType\":\"SUBCLASS_OF\"," + + "\"subjectIri\":\"https://example.org/sales/Order\",\"expressions\":[" + + "{\"kind\":\"RESTRICTION\",\"propertyIri\":\"https://example.org/sales/line\"," + + "\"restrictionKind\":\"MIN\",\"cardinality\":10}]}", + OntologyAxiom.class); + + assertTrue( + OntologyDefinitionDigest.canonicalJson(restricted).contains("\"cardinality\":1E+1"), + OntologyDefinitionDigest.canonicalJson(restricted)); + } + + @Test + void aFreshIdVersionAndAuthorshipDoNotChangeTheDigest() { + final OntologyConcept again = + order() + .withId(UUID.randomUUID()) + .withVersion(0.7) + .withUpdatedAt(1_763_800_000_000L) + .withUpdatedBy("a generator") + .withHref(URI.create("https://example.org/api/v1/ontologyConcepts/1")); + + assertEquals(ORDER_DIGEST, OntologyDefinitionDigest.of(again)); + } + + @Test + void theOntologyReferenceCountsOnlyThroughItsId() { + final OntologyConcept described = + order() + .withOntology( + new EntityReference() + .withId(ONTOLOGY) + .withType("ontology") + .withName("sales") + .withDisplayName("Sales model") + .withDescription("Renamed since the last run")); + + assertEquals(ORDER_DIGEST, OntologyDefinitionDigest.of(described)); + } + + @Test + void aChangedLabelOrDomainGivesANewDigest() { + final String relabeled = OntologyDefinitionDigest.of(order().withDisplayName("Purchase")); + final String redomained = + OntologyDefinitionDigest.of( + total().withDomain(List.of(URI.create("https://example.org/sales/Invoice")))); + + assertNotEquals(ORDER_DIGEST, relabeled); + assertNotEquals(TOTAL_DIGEST, redomained); + assertNotEquals(relabeled, redomained); + } + + @Test + void aChangedRangeParentClassOrOwnerGivesANewDigest() { + final String range = + OntologyDefinitionDigest.of( + total().withRange(List.of(URI.create("http://www.w3.org/2001/XMLSchema#string")))); + final String parent = + OntologyDefinitionDigest.of( + JsonUtils.readValue(AXIOM_JSON, OntologyAxiom.class) + .withTargetIri(URI.create("https://example.org/sales/Other"))); + final String owned = + OntologyDefinitionDigest.of( + order().withOwners(List.of(reference(UUID.randomUUID(), "user")))); + + assertNotEquals(TOTAL_DIGEST, range); + assertNotEquals( + OntologyDefinitionDigest.of(JsonUtils.readValue(AXIOM_JSON, OntologyAxiom.class)), parent); + assertNotEquals(ORDER_DIGEST, owned); + } + + @Test + void theOrderOfKeysInTheJsonDoesNotMatter() { + final String forward = + "{\"name\":\"Order\",\"iri\":\"https://example.org/sales/Order\",\"id\":\"%s\"}" + .formatted(UUID.randomUUID()); + final String backward = + "{\"id\":\"%s\",\"iri\":\"https://example.org/sales/Order\",\"name\":\"Order\"}" + .formatted(UUID.randomUUID()); + + assertEquals( + OntologyDefinitionDigest.of(JsonUtils.readValue(forward, OntologyConcept.class)), + OntologyDefinitionDigest.of(JsonUtils.readValue(backward, OntologyConcept.class))); + } + + @ParameterizedTest(name = "{1} of {0}") + @MethodSource("fieldsWithADefault") + void aFieldSentAsNullAndTheSameFieldLeftOutGiveOneDigest( + final Class type, final String json, final String field) { + final JsonNode withoutIt = JsonUtils.readTree(json); + ((com.fasterxml.jackson.databind.node.ObjectNode) withoutIt).remove(field); + final JsonNode withNull = withoutIt.deepCopy(); + ((com.fasterxml.jackson.databind.node.ObjectNode) withNull).putNull(field); + + assertEquals( + OntologyDefinitionDigest.of(JsonUtils.readValue(withoutIt.toString(), type)), + OntologyDefinitionDigest.of(JsonUtils.readValue(withNull.toString(), type)), + field); + } + + @Test + void aNullThatTurnsOffADefaultedFieldStillMatchesTheDefaultedDefinition() { + final OntologyConcept sentAsNulls = + JsonUtils.readValue( + ORDER_JSON.substring(0, ORDER_JSON.length() - 1) + + ",\"synonyms\":null,\"deleted\":null,\"provider\":null,\"abstract\":null}", + OntologyConcept.class); + + assertEquals(ORDER_DIGEST, OntologyDefinitionDigest.of(sentAsNulls)); + } + + @Test + void aConceptWithoutATypeTakesTheSchemaDefaultAndAnAxiomItsProvenance() { + final String concept = + OntologyDefinitionDigest.canonicalJson( + JsonUtils.readValue( + "{\"name\":\"Order\",\"iri\":\"https://example.org/sales/Order\"}", + OntologyConcept.class)); + final String axiom = + OntologyDefinitionDigest.canonicalJson( + JsonUtils.readValue(AXIOM_JSON, OntologyAxiom.class)); + + assertEquals( + "{\"abstract\":false,\"conceptType\":\"BOTH\",\"deleted\":false,\"deprecated\":false," + + "\"iri\":\"https://example.org/sales/Order\",\"name\":\"Order\",\"provider\":\"user\"}", + concept); + assertEquals( + "{\"axiomType\":\"SUBCLASS_OF\",\"deleted\":false,\"name\":\"orderIsAThing\"," + + "\"ontology\":" + + ONTOLOGY_JSON + + ",\"provenance\":\"Manual\",\"provider\":\"user\"," + + "\"subjectIri\":\"https://example.org/sales/Order\"," + + "\"targetIri\":\"https://example.org/sales/Thing\"}", + axiom); + } + + @Test + void theOrderOfAnArrayTheSchemaTreatsAsASetDoesNotMatter() { + final OntologyProperty forward = + total() + .withDomain( + List.of( + URI.create("https://example.org/sales/Order"), + URI.create("https://example.org/sales/Invoice"))) + .withRange( + List.of( + URI.create("http://www.w3.org/2001/XMLSchema#string"), + URI.create("http://www.w3.org/2001/XMLSchema#decimal"))); + final OntologyProperty backward = + total() + .withDomain( + List.of( + URI.create("https://example.org/sales/Invoice"), + URI.create("https://example.org/sales/Order"))) + .withRange( + List.of( + URI.create("http://www.w3.org/2001/XMLSchema#decimal"), + URI.create("http://www.w3.org/2001/XMLSchema#string"))); + final OntologyConcept synonymsForward = + order().withSynonyms(new java.util.LinkedHashSet<>(List.of("Purchase", "Sale"))); + final OntologyConcept synonymsBackward = + order().withSynonyms(new java.util.LinkedHashSet<>(List.of("Sale", "Purchase"))); + + assertEquals(OntologyDefinitionDigest.of(forward), OntologyDefinitionDigest.of(backward)); + assertEquals( + OntologyDefinitionDigest.of(synonymsForward), + OntologyDefinitionDigest.of(synonymsBackward)); + } + + @Test + void theOrderOfAnOrderedArrayDoesMatter() { + final OntologyProperty chain = + total() + .withPropertyChain( + List.of( + URI.create("https://example.org/sales/a"), + URI.create("https://example.org/sales/b"))); + final OntologyProperty reversed = + total() + .withPropertyChain( + List.of( + URI.create("https://example.org/sales/b"), + URI.create("https://example.org/sales/a"))); + + assertNotEquals(OntologyDefinitionDigest.of(chain), OntologyDefinitionDigest.of(reversed)); + } + + @Test + void everyArrayTheSchemasMarkUniqueIsASetField() throws IOException { + assertEquals(Set.of("synonyms"), OntologyDefinitionDigest.setFieldsOf(OntologyConcept.class)); + assertEquals( + Set.of( + "domain", "range", "enumValues", "characteristics", "disjointWith", "superProperties"), + OntologyDefinitionDigest.setFieldsOf(OntologyProperty.class)); + assertEquals(Set.of(), OntologyDefinitionDigest.setFieldsOf(OntologyAxiom.class)); + for (final String schema : List.of("ontologyConcept", "ontologyProperty", "ontologyAxiom")) { + final Set unique = new TreeSet<>(); + schemaProperties(schema) + .properties() + .forEach( + property -> { + if (property.getValue().path("uniqueItems").asBoolean(false)) { + unique.add(property.getKey()); + } + }); + final Class type = + switch (schema) { + case "ontologyConcept" -> OntologyConcept.class; + case "ontologyProperty" -> OntologyProperty.class; + default -> OntologyAxiom.class; + }; + assertEquals(unique, OntologyDefinitionDigest.setFieldsOf(type), schema); + } + } + + @Test + void anEmptyArrayAndAnAbsentFieldGiveOneDigest() { + final OntologyConcept withEmpty = order().withOwners(List.of()); + final OntologyConcept without = order().withOwners(null); + + assertEquals(OntologyDefinitionDigest.of(without), OntologyDefinitionDigest.of(withEmpty)); + assertEquals(ORDER_DIGEST, OntologyDefinitionDigest.of(withEmpty)); + } + + @Test + void aServerDerivedFieldDoesNotChangeTheDigest() { + final OntologyConcept read = + JsonUtils.readValue( + ORDER_JSON.substring(0, ORDER_JSON.length() - 1) + + ",\"impersonatedBy\":\"ingestion-bot\"," + + "\"incrementalChangeDescription\":{\"fieldsAdded\":[{\"name\":\"description\"}]}," + + "\"lifecycleStatus\":\"InReview\"," + + "\"superClasses\":[\"https://example.org/sales/Thing\"]," + + "\"subClasses\":[\"https://example.org/sales/Rush\"]," + + "\"owners\":[{\"id\":\"%s\",\"type\":\"team\",\"name\":\"sales\"," + .formatted(OWNER) + + "\"displayName\":\"Sales\",\"href\":\"https://example.org/api/v1/teams/x\"}]}", + OntologyConcept.class); + final OntologyConcept owned = order().withOwners(List.of(reference(OWNER, "team"))); + + assertEquals(OntologyDefinitionDigest.of(owned), OntologyDefinitionDigest.of(read)); + assertNotEquals(ORDER_DIGEST, OntologyDefinitionDigest.of(read)); + } + + @Test + void everyFieldTheSchemasMarkReadOnlyLeavesTheCanonicalForm() throws IOException { + for (final String schema : List.of("ontologyConcept", "ontologyProperty", "ontologyAxiom")) { + schemaProperties(schema) + .properties() + .forEach( + property -> { + if (property.getValue().path("readOnly").asBoolean(false)) { + assertTrue( + OntologyDefinitionDigest.DROPPED_FIELDS.contains(property.getKey()), + schema + "." + property.getKey()); + } + }); + } + } + + @Test + void theDroppedFieldsAreExactlyTheServerDerivedOnes() { + assertEquals( + new TreeSet<>( + Set.of( + "id", + "version", + "updatedAt", + "updatedBy", + "href", + "changeDescription", + "incrementalChangeDescription", + "impersonatedBy", + "lifecycleStatus", + "superClasses", + "subClasses")), + new TreeSet<>(OntologyDefinitionDigest.DROPPED_FIELDS)); + } + + private static final UUID OWNER = UUID.fromString("00000000-0000-0000-0000-0000000000b2"); + + private static EntityReference reference(final UUID id, final String type) { + return new EntityReference().withId(id).withType(type); + } + + private static JsonNode schemaProperties(final String schema) throws IOException { + try (InputStream stream = + OntologyDefinitionDigestTest.class.getResourceAsStream( + "/json/schema/entity/data/" + schema + ".json")) { + return JsonUtils.readTree(new String(stream.readAllBytes(), StandardCharsets.UTF_8)) + .get("properties"); + } + } + + private static OntologyConcept order() { + return new OntologyConcept() + .withId(UUID.randomUUID()) + .withName("Order") + .withFullyQualifiedName("sales.Order") + .withDisplayName("Order") + .withDescription("A purchase a customer placed") + .withOntology(new EntityReference().withId(ONTOLOGY).withType("ontology")) + .withIri(URI.create("https://example.org/sales/Order")) + .withConceptType(OntologyConceptType.OWL_CLASS) + .withVersion(0.1); + } + + private static OntologyProperty total() { + return new OntologyProperty() + .withId(UUID.randomUUID()) + .withName("total") + .withFullyQualifiedName("sales.total") + .withOntology(new EntityReference().withId(ONTOLOGY).withType("ontology")) + .withIri(URI.create("https://example.org/sales/total")) + .withKind(OntologyPropertyKind.DATA) + .withDomain(List.of(URI.create("https://example.org/sales/Order"))) + .withRange(List.of(URI.create("http://www.w3.org/2001/XMLSchema#decimal"))) + .withVersion(0.1); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftNarrowingTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftNarrowingTest.java new file mode 100644 index 000000000000..56cc6a5c0437 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftNarrowingTest.java @@ -0,0 +1,321 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyPropertyKind; + +class OntologyDraftNarrowingTest { + private static final URI ORDER = URI.create("https://example.org/sales/Order"); + private static final URI CUSTOMER = URI.create("https://example.org/sales/Customer"); + private static final URI STRING = URI.create("http://www.w3.org/2001/XMLSchema#string"); + private static final String REFUSAL_HEAD = + "Ontology operations need classes that only removed operations create: "; + + @Test + void refusesAPropertyKeptWithoutTheClassOnlyARemovedOperationCreates() { + final OntologyChangeOperation order = concept(ORDER); + final OntologyChangeOperation placedBy = objectProperty("placedBy", ORDER, CUSTOMER); + final OntologyChangeOperation customer = concept(CUSTOMER); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> narrow(List.of(placedBy), List.of(order, customer, placedBy), Set.of())); + + assertEquals( + REFUSAL_HEAD + + "https://example.org/sales/Customer, https://example.org/sales/Order." + + " Keep the operation that creates each class, or remove the operations that need" + + " it.", + refusal.getMessage()); + } + + @Test + void acceptsAPropertyKeptWithTheClassesItsKeptOperationsCreate() { + final OntologyChangeOperation order = concept(ORDER); + final OntologyChangeOperation customer = concept(CUSTOMER); + final OntologyChangeOperation placedBy = objectProperty("placedBy", ORDER, CUSTOMER); + final OntologyChangeOperation total = dataProperty("total", ORDER); + + assertDoesNotThrow( + () -> + narrow( + List.of(order, customer, placedBy), + List.of(order, customer, placedBy, total), + Set.of())); + } + + @Test + void acceptsAPropertyWhoseClassTheOntologyAlreadyDeclares() { + final OntologyChangeOperation order = concept(ORDER); + final OntologyChangeOperation total = dataProperty("total", ORDER); + + assertDoesNotThrow( + () -> narrow(List.of(total), List.of(order, total), Set.of(ORDER.toString()))); + } + + @Test + void namesOnlyTheClassesTheOntologyLacks() { + final OntologyChangeOperation order = concept(ORDER); + final OntologyChangeOperation customer = concept(CUSTOMER); + final OntologyChangeOperation placedBy = objectProperty("placedBy", ORDER, CUSTOMER); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> + narrow( + List.of(placedBy), + List.of(order, customer, placedBy), + Set.of(ORDER.toString()))); + + assertEquals( + REFUSAL_HEAD + + "https://example.org/sales/Customer. Keep the operation that creates each class," + + " or remove the operations that need it.", + refusal.getMessage()); + } + + @Test + void leavesAClassThatNothingCreatesToTheApplyCheck() { + final OntologyChangeOperation total = dataProperty("total", ORDER); + + assertDoesNotThrow(() -> narrow(List.of(total), List.of(total, concept(CUSTOMER)), Set.of())); + } + + @Test + void refusesAClassKeptPastTheUndoCursor() { + final OntologyChangeOperation order = concept(ORDER); + final OntologyChangeOperation total = dataProperty("total", ORDER); + + assertThrows( + BadRequestException.class, + () -> narrow(List.of(total, order), 1, List.of(order, total), Set.of())); + } + + @Test + void namesAClassKeptPastTheUndoCursorAsUndoneAndNotAsRemoved() { + final OntologyChangeOperation order = concept(ORDER); + final OntologyChangeOperation total = dataProperty("total", ORDER); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> narrow(List.of(total, order), 1, List.of(order, total), Set.of())); + + assertEquals( + "Ontology operations need classes that only kept operations past the undo cursor create: " + + "https://example.org/sales/Order. Move the undo cursor past the operation that" + + " creates each class, or remove the operations that need it.", + refusal.getMessage()); + } + + @Test + void namesBothKindsOfLostClassInOneRefusal() { + final OntologyChangeOperation order = concept(ORDER); + final OntologyChangeOperation customer = concept(CUSTOMER); + final OntologyChangeOperation placedBy = objectProperty("placedBy", ORDER, CUSTOMER); + final OntologyChangeOperation lateCustomer = concept(CUSTOMER); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> + narrow( + List.of(placedBy, lateCustomer), + 1, + List.of(order, customer, placedBy, lateCustomer), + Set.of())); + + assertEquals( + REFUSAL_HEAD + + "https://example.org/sales/Order. Keep the operation that creates each class, or" + + " remove the operations that need it." + + " Ontology operations need classes that only kept operations past the undo cursor" + + " create: https://example.org/sales/Customer. Move the undo cursor past the" + + " operation that creates each class, or remove the operations that need it.", + refusal.getMessage()); + } + + @Test + void refusesAClassOnlyARemovedOperationCreatedWhenARedoWouldActivateTheOperationThatNeedsIt() { + final OntologyChangeOperation order = concept(ORDER); + final OntologyChangeOperation total = dataProperty("total", ORDER); + + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> narrow(List.of(total), 0, List.of(order, total), Set.of())); + + assertEquals( + REFUSAL_HEAD + + "https://example.org/sales/Order. Keep the operation that creates each class, or" + + " remove the operations that need it.", + refusal.getMessage()); + } + + /** + * Over every subset of a six-operation draft, every undo cursor and every redo target, a + * narrowing that is accepted leaves a draft that applies at each of the cursors a redo can + * reach, and one that is refused would fail at one of them. + */ + @Test + void aNarrowingIsAcceptedExactlyWhenEveryRedoTargetApplies() { + final URI existing = URI.create("https://example.org/sales/Existing"); + final OntologyChangeOperation classA = concept(ORDER); + final OntologyChangeOperation classB = concept(CUSTOMER); + final OntologyChangeOperation axiom = subclassOf(CUSTOMER, ORDER); + final OntologyChangeOperation p1 = dataProperty("p1", ORDER); + final OntologyChangeOperation p2 = objectProperty("p2", CUSTOMER, ORDER); + final OntologyChangeOperation p3 = dataProperty("p3", existing); + final List draft = List.of(classA, classB, axiom, p1, p2, p3); + final Set declared = Set.of(existing.toString()); + int accepted = 0; + int refused = 0; + int accepting = 0; + + for (int mask = 0; mask < (1 << draft.size()); mask++) { + final List kept = new java.util.ArrayList<>(); + for (int bit = 0; bit < draft.size(); bit++) { + if ((mask & (1 << bit)) != 0) { + kept.add(draft.get(bit)); + } + } + for (int cursor = 0; cursor <= kept.size(); cursor++) { + boolean narrowed = true; + try { + narrow(kept, cursor, draft, declared); + } catch (BadRequestException refusal) { + narrowed = false; + } + boolean everyTargetApplies = true; + for (int target = cursor; target <= kept.size(); target++) { + everyTargetApplies &= applies(kept.subList(0, target), draft, declared); + } + assertEquals(everyTargetApplies, narrowed, "subset " + mask + " cursor " + cursor); + accepted += narrowed ? 1 : 0; + refused += narrowed ? 0 : 1; + accepting += narrowed && everyTargetApplies ? 1 : 0; + } + } + + assertEquals(100, accepted); + assertEquals(156, refused); + assertEquals(accepted, accepting); + } + + /** What apply decides for the active operations: each class a stored operation made is there. */ + private static boolean applies( + final List active, + final List stored, + final Set declared) { + final Set storedClasses = OntologyChangePreflight.createdConceptIris(stored); + final Set created = OntologyChangePreflight.createdConceptIris(active); + final var dataProperties = OntologyChangePreflight.dataProperties(active); + return active.stream() + .flatMap( + operation -> + OntologyChangePreflight.neededClassIris(operation, dataProperties).stream()) + .filter(storedClasses::contains) + .allMatch(iri -> created.contains(iri) || declared.contains(iri)); + } + + private static OntologyChangeOperation subclassOf(final URI child, final URI parent) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_AXIOM) + .withAxiom( + new org.openmetadata.schema.entity.data.OntologyAxiom() + .withId(UUID.randomUUID()) + .withAxiomType(org.openmetadata.schema.type.OntologyAxiomType.SUBCLASS_OF) + .withSubjectIri(child) + .withExpressions( + List.of( + new org.openmetadata.schema.type.OntologyExpression() + .withKind( + org.openmetadata.schema.type.OntologyExpressionKind.NAMED_CLASS) + .withClassIri(parent)))); + } + + private static void narrow( + final List kept, + final List stored, + final Set declared) { + narrow(kept, kept.size(), stored, declared); + } + + private static void narrow( + final List kept, + final int cursor, + final List stored, + final Set declared) { + final OntologyChangeSet replaced = + new OntologyChangeSet() + .withOntology(new EntityReference().withId(UUID.randomUUID()).withType("ontology")) + .withOperations(kept) + .withUndoCursor(cursor); + OntologyDraftNarrowing.requireNoLostClasses( + replaced, + stored, + (ontologyId, iris) -> + iris.stream().filter(declared::contains).collect(java.util.stream.Collectors.toSet())); + } + + private static OntologyChangeOperation concept(final URI iri) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_CONCEPT) + .withConcept(new OntologyConcept().withId(UUID.randomUUID()).withIri(iri)); + } + + private static OntologyChangeOperation dataProperty(final String name, final URI domain) { + return property(name, OntologyPropertyKind.DATA, domain, STRING); + } + + private static OntologyChangeOperation objectProperty( + final String name, final URI domain, final URI range) { + return property(name, OntologyPropertyKind.OBJECT, domain, range); + } + + private static OntologyChangeOperation property( + final String name, final OntologyPropertyKind kind, final URI domain, final URI range) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_PROPERTY) + .withProperty( + new OntologyProperty() + .withId(UUID.randomUUID()) + .withName(name) + .withIri(URI.create("https://example.org/sales/" + name)) + .withKind(kind) + .withDomain(List.of(domain)) + .withRange(List.of(range))); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftPreflightTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftPreflightTest.java new file mode 100644 index 000000000000..5dca94eef0b3 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyDraftPreflightTest.java @@ -0,0 +1,336 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import jakarta.ws.rs.BadRequestException; +import java.net.URI; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Consumer; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.OntologyBindingChange; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.schema.type.OntologyColumnBindingChange; +import org.openmetadata.schema.type.OntologyJoinChange; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; + +/** What a draft with binding and shape operations must name before it is saved. */ +class OntologyDraftPreflightTest { + private static final UUID ONTOLOGY_ID = UUID.fromString("2ecf752a-956d-4a44-95ec-cce029f5c1d7"); + private static final UUID OPERATION_ID = UUID.fromString("7a1c0f5e-3f0b-4f43-9a5c-6a0d6de0b001"); + private static final UUID ORDERS_ID = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0002"); + private static final UUID CUSTOMERS_ID = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0003"); + private static final UUID MISSING_ID = UUID.fromString("9d2f6f0a-51b7-4b0e-8a44-0f4a4a1c0004"); + private static final String ORDER = "https://example.org/sales/Order"; + private static final String CUSTOMER = "https://example.org/sales/Customer"; + private static final String TOTAL = "https://example.org/sales/total"; + private static final String PLACED_BY = "https://example.org/sales/placedBy"; + private static final String NEEDS = "Ontology operation '" + OPERATION_ID + "' needs the "; + private static final String NAMES = "Ontology operation '" + OPERATION_ID + "' names the "; + + private final Set declaredClasses = new HashSet<>(Set.of(ORDER, CUSTOMER)); + private final Set declaredProperties = new HashSet<>(Set.of(TOTAL, PLACED_BY)); + private final Map tables = new HashMap<>(); + private final OntologyDraftPreflight preflight = + new OntologyDraftPreflight(new Declared(), tables::get); + + OntologyDraftPreflightTest() { + tables.put( + ORDERS_ID, + table( + ORDERS_ID, + column("order_id"), + column("customer_id"), + column("total"), + column("status"), + column("shipping").withChildren(List.of(column("zip"))))); + tables.put(CUSTOMERS_ID, table(CUSTOMERS_ID, column("id"))); + } + + @Test + void acceptsABindingAndAShapeWhoseNamesAllExist() { + assertDoesNotThrow(() -> validate(binding(change -> {}), shape(CUSTOMER))); + } + + @Test + void acceptsAClassAndAPropertyThatAnEarlierOperationCreates() { + declaredClasses.remove(ORDER); + declaredProperties.remove(TOTAL); + + assertDoesNotThrow( + () -> validate(classOperation(ORDER), propertyOperation(TOTAL), binding(change -> {}))); + } + + @Test + void refusesABindingWhoseClassNothingDeclaresOrCreatesEarlier() { + declaredClasses.remove(ORDER); + + assertRefused( + NEEDS + + "class " + + ORDER + + ", which the ontology does not declare and no earlier operation creates", + binding(change -> {})); + assertRefused( + NEEDS + + "class " + + ORDER + + ", which the ontology does not declare and no earlier operation creates", + binding(change -> {}), + classOperation(ORDER)); + } + + @Test + void refusesAShapeWhoseTargetClassNothingDeclaresOrCreatesEarlier() { + declaredClasses.remove(CUSTOMER); + + assertRefused( + NEEDS + + "class " + + CUSTOMER + + ", which the ontology does not declare and no earlier operation creates", + shape(CUSTOMER).withId(OPERATION_ID)); + } + + @Test + void aShapeMayTargetAVocabularyClassButABindingNeedsADeclaredOne() { + final String thing = "http://www.w3.org/2002/07/owl#Thing"; + + assertDoesNotThrow(() -> validate(shape(thing))); + assertRefused( + NEEDS + + "class " + + thing + + ", which the ontology does not declare and no earlier operation creates", + binding(change -> change.setClassIri(URI.create(thing)))); + } + + @Test + void refusesAConceptAnOperationListsAsRequiredButNothingDeclares() { + final String region = "https://example.org/sales/Region"; + + assertRefused( + NEEDS + + "class " + + region + + ", which the ontology does not declare and no earlier operation creates", + binding(change -> {}).withRequiresConceptIris(List.of(URI.create(region)))); + assertDoesNotThrow( + () -> + validate( + binding(change -> {}) + .withRequiresConceptIris( + List.of( + URI.create("http://www.w3.org/2002/07/owl#Thing"), + URI.create("http://www.w3.org/2001/XMLSchema#string"))))); + } + + @Test + void refusesABindingWhosePropertyNothingDeclaresOrCreatesEarlier() { + declaredProperties.remove(TOTAL); + + assertRefused( + NEEDS + + "property " + + TOTAL + + ", which the ontology does not declare and no earlier operation creates", + binding(change -> {})); + } + + @Test + void refusesATableTheCatalogDoesNotHold() { + assertRefused( + NAMES + "table " + MISSING_ID + ", which does not exist", + binding(change -> change.setTableId(MISSING_ID))); + } + + @Test + void refusesEachColumnTheBoundTableDoesNotHave() { + final String missing = ", which table " + ORDERS_ID + " does not have"; + + assertRefused( + NAMES + "column order_number" + missing, + binding(change -> change.setSubjectKey(List.of(List.of("order_number"))))); + assertRefused( + NAMES + "column state" + missing, + binding( + change -> + change.setRowFilter( + new OntologyRowFilter() + .withColumn(List.of("state")) + .withOperator(OntologyRowFilterOperator.IS_NOT_NULL)))); + assertRefused( + NAMES + "column amount" + missing, + binding(change -> change.setColumns(List.of(column(TOTAL, List.of("amount"), null))))); + assertRefused( + NAMES + "column shipping.city" + missing, + binding( + change -> + change.setColumns(List.of(column(TOTAL, List.of("shipping", "city"), null))))); + } + + @Test + void acceptsANestedColumnByItsPath() { + assertDoesNotThrow( + () -> + validate( + binding( + change -> + change.setColumns( + List.of(column(TOTAL, List.of("shipping", "zip"), null)))))); + } + + @Test + void refusesAJoinWhoseTargetTableOrColumnsDoNotExist() { + assertRefused( + NAMES + "join target table " + MISSING_ID + ", which does not exist", + binding(change -> change.setColumns(List.of(joined(MISSING_ID, "customer_id", "id"))))); + assertRefused( + NAMES + "column buyer_id, which table " + ORDERS_ID + " does not have", + binding(change -> change.setColumns(List.of(joined(CUSTOMERS_ID, "buyer_id", "id"))))); + assertRefused( + NAMES + "column customer_key, which table " + CUSTOMERS_ID + " does not have", + binding( + change -> + change.setColumns(List.of(joined(CUSTOMERS_ID, "customer_id", "customer_key"))))); + assertDoesNotThrow( + () -> + validate( + binding( + change -> + change.setColumns(List.of(joined(CUSTOMERS_ID, "customer_id", "id")))))); + } + + private void validate(final OntologyChangeOperation... operations) { + preflight.validate(ONTOLOGY_ID, List.of(operations)); + } + + private void assertRefused(final String expected, final OntologyChangeOperation... operations) { + final BadRequestException refusal = + assertThrows(BadRequestException.class, () -> validate(operations)); + assertEquals(expected, refusal.getMessage()); + } + + /** Answers for one ontology only, so a lookup in another ontology finds nothing. */ + private final class Declared implements OntologyDraftPreflight.Declarations { + @Override + public Set classes(final UUID ontologyId, final Set iris) { + return known(ontologyId, iris, declaredClasses); + } + + @Override + public Set properties(final UUID ontologyId, final Set iris) { + return known(ontologyId, iris, declaredProperties); + } + + private Set known( + final UUID ontologyId, final Set iris, final Set declared) { + final Set known = new HashSet<>(iris); + known.retainAll(ONTOLOGY_ID.equals(ontologyId) ? declared : Set.of()); + return known; + } + } + + /** An identity binding of the orders table, changed by {@code edit} before it is sent. */ + private static OntologyChangeOperation binding(final Consumer edit) { + final OntologyBindingChange change = + new OntologyBindingChange() + .withClassIri(URI.create(ORDER)) + .withTableId(ORDERS_ID) + .withRole(OntologyBindingRole.IDENTITY) + .withSubjectKey(List.of(List.of("order_id"))) + .withRowFilter( + new OntologyRowFilter() + .withColumn(List.of("status")) + .withOperator(OntologyRowFilterOperator.EQUALS) + .withValue("placed")) + .withColumns(List.of(column(TOTAL, List.of("total"), null))); + edit.accept(change); + return new OntologyChangeOperation() + .withId(OPERATION_ID) + .withOperationType(OntologyChangeOperationType.UPSERT_BINDING) + .withBinding(change); + } + + private static OntologyColumnBindingChange column( + final String propertyIri, final List path, final OntologyJoinChange join) { + return new OntologyColumnBindingChange() + .withPropertyIri(URI.create(propertyIri)) + .withColumnPath(path) + .withJoin(join); + } + + private static OntologyColumnBindingChange joined( + final UUID target, final String child, final String parent) { + return column( + PLACED_BY, + List.of(child), + new OntologyJoinChange() + .withTargetAssetId(target) + .withOn( + List.of( + new OntologyJoinColumnPair() + .withChild(List.of(child)) + .withParent(List.of(parent))))); + } + + private static OntologyChangeOperation shape(final String targetClass) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_SHAPE) + .withShape( + new OntologyShape() + .withId(UUID.randomUUID()) + .withTargetConcept(URI.create(targetClass))); + } + + private static OntologyChangeOperation classOperation(final String iri) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_CONCEPT) + .withConcept(new OntologyConcept().withId(UUID.randomUUID()).withIri(URI.create(iri))); + } + + private static OntologyChangeOperation propertyOperation(final String iri) { + return new OntologyChangeOperation() + .withId(UUID.randomUUID()) + .withOperationType(OntologyChangeOperationType.UPSERT_PROPERTY) + .withProperty(new OntologyProperty().withId(UUID.randomUUID()).withIri(URI.create(iri))); + } + + private static Table table(final UUID id, final Column... columns) { + return new Table().withId(id).withColumns(List.of(columns)); + } + + private static Column column(final String name) { + return new Column().withName(name); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java new file mode 100644 index 000000000000..fc25fc3dfcae --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyExpandStatementTest.java @@ -0,0 +1,759 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.schema.api.data.OntologyStatementDirection.FORWARD; +import static org.openmetadata.schema.api.data.OntologyStatementDirection.INVERSE; +import static org.openmetadata.service.ontology.OntologyMappingShapeModel.plan; +import static org.openmetadata.service.ontology.OntologyMappingShapeModel.read; +import static org.openmetadata.service.ontology.OntologyMappingShapeModel.sql; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.PAGED_COMPOSITE_RELATED_KEY; + +import jakarta.ws.rs.ClientErrorException; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.RecordStatement; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyMappingShapes.TableSpec; +import org.openmetadata.service.security.AuthorizationException; + +/** + * The statement that lists the records one record relates to. It follows the confirmed join that + * the class binding the relation stores, between the identity tables of the two classes. + */ +class OntologyExpandStatementTest { + private static final String POSTGRES = "Postgres"; + private static final String ORDER = "https://example.org/columnRelation#Order"; + private static final String CUSTOMER = "https://example.org/columnRelation#Customer"; + private static final String PLACED_BY = "https://example.org/columnRelation#placedBy"; + + @Test + void aRelationHeldInAColumnJoinsTheIdentityTableOfTheRelatedClass() { + final RecordStatement expand = + expand(model(COLUMN_RELATION, POSTGRES), "Order", "placedBy", FORWARD, List.of(31)); + + assertEquals( + "SELECT t0.id, t1.id, t1.name\nFROM shop.orders t0\n" + + "JOIN shop.customers t1 ON t1.id = t0.customer_id\n" + + "WHERE t0.id = 31\n AND t1.id IS NOT NULL\nORDER BY t1.id\nLIMIT 26", + sql(expand)); + assertEquals( + List.of( + "0 key Order part 0", "1 key Customer part 0", "2 displayName Customer customerName"), + plan(expand)); + assertEquals(List.of("orders", "customers"), read(expand)); + assertEquals(25, expand.rowCap()); + assertTrue(expand.extraRow()); + } + + @Test + void aRelatedRecordTakesItsKeyFromItsIdentityTableAndNeverFromTheJoinColumn() { + final RecordStatement expand = + expand(model(COLUMN_RELATION, "Mysql"), "Customer", "placedBy", INVERSE, List.of(2)); + + assertEquals( + "SELECT t0.`id`, t1.`id`\nFROM `shop`.`customers` t0\n" + + "JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id`\n" + + "WHERE t0.`id` = 2\n AND t1.`id` IS NOT NULL\nORDER BY t1.`id`\nLIMIT 26", + sql(expand)); + assertEquals(List.of("0 key Customer part 0", "1 key Order part 0"), plan(expand)); + } + + @Test + void aLinkTableJoinsBetweenTheTwoIdentityTablesAndEveryTableKeepsItsRowFilter() { + final OntologyMappingShapeModel model = filteredLinkTable(POSTGRES); + + assertEquals( + "SELECT t0.id, t2.sku, t2.title\nFROM shop.orders t0\n" + + "JOIN shop.order_items t1 ON t1.order_id = t0.id\n" + + "JOIN shop.products t2 ON t2.sku = t1.product_sku\n" + + "WHERE t0.id = 1\n AND t0.channel = 'web'\n AND t1.quantity > 0\n" + + " AND t2.sku IS NOT NULL\n AND t2.title <> 'Drill'\nORDER BY t2.sku\nLIMIT 26", + sql(expand(model, "Order", "contains", FORWARD, List.of(1)))); + assertEquals( + "SELECT t0.sku, t2.id\nFROM shop.products t0\n" + + "JOIN shop.order_items t1 ON t1.product_sku = t0.sku\n" + + "JOIN shop.orders t2 ON t2.id = t1.order_id\n" + + "WHERE t0.sku = 'A-1'\n AND t0.title <> 'Drill'\n AND t1.quantity > 0\n" + + " AND t2.id IS NOT NULL\n AND t2.channel = 'web'\nORDER BY t2.id\nLIMIT 26", + sql(expand(model, "Product", "contains", INVERSE, List.of("A-1")))); + } + + @Test + void transactSqlAsksForTheExtraRowWithTop() { + assertEquals( + "SELECT TOP 26 t0.[id], t1.[id], t1.[name]\nFROM [shop].[orders] t0\n" + + "JOIN [shop].[customers] t1 ON t1.[id] = t0.[customer_id]\n" + + "WHERE t0.[id] = 31\n AND t1.[id] IS NOT NULL\nORDER BY t1.[id]", + sql(expand(model(COLUMN_RELATION, "Mssql"), "Order", "placedBy", FORWARD, List.of(31)))); + } + + @Test + void aRelationFromAClassToItselfJoinsItsIdentityTableToItself() { + final OntologyMappingShapeModel model = model(staff(), POSTGRES); + + assertEquals( + "SELECT t0.id, t1.id, t1.name\nFROM shop.employees t0\n" + + "JOIN shop.employees t1 ON t1.id = t0.manager_id\n" + + "WHERE t0.id = 5\n AND t1.id IS NOT NULL\nORDER BY t1.id\nLIMIT 26", + sql(expand(model, "Employee", "reportsTo", FORWARD, List.of(5)))); + assertEquals( + "SELECT t0.id, t1.id, t1.name\nFROM shop.employees t0\n" + + "JOIN shop.employees t1 ON t1.manager_id = t0.id\n" + + "WHERE t0.id = 1\n AND t1.id IS NOT NULL\nORDER BY t1.id\nLIMIT 26", + sql(expand(model, "Employee", "reportsTo", INVERSE, List.of(1)))); + } + + @Test + void aJoinOverSeveralColumnsEquatesEachPair() { + assertEquals( + "SELECT t0.id, t1.tenant_id, t1.account_id\nFROM shop.invoices t0\n" + + "JOIN shop.accounts t1 ON t1.tenant_id = t0.tenant AND t1.account_id = t0.account\n" + + "WHERE t0.id = 9\n AND t1.tenant_id IS NOT NULL\n AND t1.account_id IS NOT NULL\n" + + "ORDER BY t1.tenant_id, t1.account_id\nLIMIT 26", + sql(expand(model(billing(), POSTGRES), "Invoice", "billedTo", FORWARD, List.of(9)))); + } + + @Test + void aJoinThatIsOnlyInferredIsNotFollowed() { + final OntologyMappingShapeModel model = + new OntologyMappingShapeModel( + COLUMN_RELATION, + POSTGRES, + List.of( + COLUMN_RELATION.bindings().getFirst(), + orders(placedBy(OntologyJoinStatus.INFERRED)))); + + final ClientErrorException refused = + assertThrows( + ClientErrorException.class, + () -> expand(model, "Order", "placedBy", FORWARD, List.of(31))); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "The join of relation " + + PLACED_BY + + " from class " + + ORDER + + " to class " + + CUSTOMER + + " is not confirmed", + refused.getMessage()); + } + + @Test + void aConfirmedJoinOntoAnotherTableThanTheIdentityTableOfTheRelatedClassIsNeverFollowed() { + final ColumnBindingSpec ontoOrders = + new ColumnBindingSpec( + "placedBy", + "customer_id", + new JoinSpec( + "orders", OntologyJoinStatus.CONFIRMED, List.of("customer_id"), List.of("id"))); + final OntologyMappingShapeModel model = + new OntologyMappingShapeModel( + COLUMN_RELATION, + POSTGRES, + List.of(COLUMN_RELATION.bindings().getFirst(), orders(ontoOrders))); + final String message = + "Relation " + + PLACED_BY + + " has no join from class " + + ORDER + + " to the identity table of class " + + CUSTOMER; + + final ClientErrorException forward = + assertThrows( + ClientErrorException.class, + () -> expand(model, "Order", "placedBy", FORWARD, List.of(31))); + final ClientErrorException inverse = + assertThrows( + ClientErrorException.class, + () -> expand(model, "Customer", "placedBy", INVERSE, List.of(2))); + + assertEquals(409, forward.getResponse().getStatus()); + assertEquals(message, forward.getMessage()); + assertEquals(409, inverse.getResponse().getStatus()); + assertEquals(message, inverse.getMessage()); + } + + @Test + void aRelationWithNoJoinGivesNoStatementInEitherDirection() { + final OntologyMappingShapeModel model = + new OntologyMappingShapeModel( + COLUMN_RELATION, + POSTGRES, + List.of(COLUMN_RELATION.bindings().getFirst(), orders(null))); + final String message = + "Relation " + + PLACED_BY + + " has no join from class " + + ORDER + + " to the identity table of class " + + CUSTOMER; + + final ClientErrorException forward = + assertThrows( + ClientErrorException.class, + () -> expand(model, "Order", "placedBy", FORWARD, List.of(31))); + final ClientErrorException inverse = + assertThrows( + ClientErrorException.class, + () -> expand(model, "Customer", "placedBy", INVERSE, List.of(2))); + + assertEquals(409, forward.getResponse().getStatus()); + assertEquals(message, forward.getMessage()); + assertEquals(message, inverse.getMessage()); + } + + @Test + void aLinkTableTheReaderMayNotViewIsRefusedWithoutBeingNamed() { + final OntologyMappingShapeModel model = model(LINK_TABLE, POSTGRES).hide("order_items"); + + final AuthorizationException refused = + assertThrows( + AuthorizationException.class, + () -> expand(model, "Product", "contains", INVERSE, List.of("A-1"))); + + assertEquals( + "The table that links class https://example.org/linkTable#Order to class" + + " https://example.org/linkTable#Product for relation" + + " https://example.org/linkTable#contains is not visible to you", + refused.getMessage()); + } + + @Test + void theJoinThatIsFollowedNeverDependsOnWhichTablesTheReaderMayView() { + final Shape shape = twoLinkTables(); + + assertEquals( + List.of("orders", "order_items", "products"), + read(expand(model(shape, POSTGRES), "Order", "contains", FORWARD, List.of(1)))); + assertThrows( + AuthorizationException.class, + () -> + expand( + model(shape, POSTGRES).hide("order_items"), + "Order", + "contains", + FORWARD, + List.of(1))); + } + + @Test + void aLinkTableThatNoLongerExistsHoldsNoJoin() { + final OntologyMappingShapeModel model = model(LINK_TABLE, POSTGRES).delete("order_items"); + + final ClientErrorException refused = + assertThrows( + ClientErrorException.class, + () -> expand(model, "Order", "contains", FORWARD, List.of(1))); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "Relation https://example.org/linkTable#contains has no join from class" + + " https://example.org/linkTable#Order to the identity table of class" + + " https://example.org/linkTable#Product", + refused.getMessage()); + } + + @Test + void theIdentityTableOfTheRelatedClassMustExistAndBeVisible() { + final OntologyMappingShapeModel unbound = + new OntologyMappingShapeModel( + COLUMN_RELATION, POSTGRES, List.of(COLUMN_RELATION.bindings().getLast())); + final OntologyMappingShapeModel hidden = model(COLUMN_RELATION, POSTGRES).hide("customers"); + + final ClientErrorException missing = + assertThrows( + ClientErrorException.class, + () -> expand(unbound, "Order", "placedBy", FORWARD, List.of(31))); + final AuthorizationException refused = + assertThrows( + AuthorizationException.class, + () -> expand(hidden, "Order", "placedBy", FORWARD, List.of(31))); + + assertEquals(409, missing.getResponse().getStatus()); + assertEquals("Class " + CUSTOMER + " has no identity table", missing.getMessage()); + assertEquals( + "The identity table of class " + CUSTOMER + " is not visible to you", refused.getMessage()); + } + + @Test + void aJoinColumnThatLeftItsTableGivesNoStatement() { + final OntologyMappingShapeModel model = model(COLUMN_RELATION, POSTGRES); + model.table("orders").getColumns().removeIf(column -> column.getName().equals("customer_id")); + + final ClientErrorException refused = + assertThrows( + ClientErrorException.class, + () -> expand(model, "Order", "placedBy", FORWARD, List.of(31))); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "Column customer_id of warehouse.sales.shop.orders no longer exists", refused.getMessage()); + } + + @Test + void aRelatedTableInAnotherDatabaseGivesNoStatement() { + final OntologyMappingShapeModel model = model(COLUMN_RELATION, POSTGRES); + model.table("customers").setFullyQualifiedName("warehouse.marketing.shop.customers"); + + final ClientErrorException refused = + assertThrows( + ClientErrorException.class, + () -> expand(model, "Order", "placedBy", FORWARD, List.of(31))); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "Table warehouse.marketing.shop.customers is in another database than the identity table" + + " of class " + + ORDER, + refused.getMessage()); + } + + @Test + void theKeyOfTheStartRecordIsParsedAsTheKeyOfItsIdentityTable() { + final OntologyMappingShapeModel model = model(COLUMN_RELATION, POSTGRES); + + assertEquals( + "The key has 1 column but the request gives 2 values", + assertThrows( + BadRequestException.class, + () -> expand(model, "Order", "placedBy", FORWARD, List.of(31, 32))) + .getMessage()); + assertEquals( + "The value for column id does not parse as INT: a whole number is written in ASCII" + + " digits, with a leading minus sign when negative and no leading zeros", + assertThrows( + BadRequestException.class, + () -> expand(model, "Order", "placedBy", FORWARD, List.of("31 OR 1=1"))) + .getMessage()); + } + + @Test + void aKeyOfOneColumnPagesByTheRelatedKeyAndStartsAfterTheGivenOne() { + final OntologyMappingShapeModel model = model(COLUMN_RELATION, POSTGRES); + + assertEquals( + "SELECT t0.id, t1.id\nFROM shop.customers t0\n" + + "JOIN shop.orders t1 ON t1.customer_id = t0.id\n" + + "WHERE t0.id = 1\n AND t1.id IS NOT NULL\n AND t1.id > 25\n" + + "ORDER BY t1.id\nLIMIT 26", + sql(expand(model, "Customer", "placedBy", INVERSE, List.of(1), List.of(25)))); + } + + @Test + void aKeyOfTwoColumnsComparesTheFirstPartThenTheSecondWithoutARowValue() { + final OntologyMappingShapeModel model = model(PAGED_COMPOSITE_RELATED_KEY, POSTGRES); + + assertEquals( + "SELECT t0.id, t1.ledger, t1.seq\nFROM shop.accounts t0\n" + + "JOIN shop.entries t1 ON t1.account_id = t0.id\n" + + "WHERE t0.id = 1\n AND t1.ledger IS NOT NULL\n AND t1.seq IS NOT NULL\n" + + " AND (t1.ledger > 'a' OR (t1.ledger = 'a' AND t1.seq > 25))\n" + + "ORDER BY t1.ledger, t1.seq\nLIMIT 26", + sql(expand(model, "Account", "postedTo", INVERSE, List.of(1), List.of("a", 25)))); + assertEquals( + "SELECT TOP 26 t0.[id], t1.[ledger], t1.[seq]\nFROM [shop].[accounts] t0\n" + + "JOIN [shop].[entries] t1 ON t1.[account_id] = t0.[id]\n" + + "WHERE t0.[id] = 1\n AND t1.[ledger] IS NOT NULL\n AND t1.[seq] IS NOT NULL\n" + + " AND (t1.[ledger] > N'a' OR (t1.[ledger] = N'a' AND t1.[seq] > 25))\n" + + "ORDER BY t1.[ledger], t1.[seq]", + sql( + expand( + model(PAGED_COMPOSITE_RELATED_KEY, "Mssql"), + "Account", + "postedTo", + INVERSE, + List.of(1), + List.of("a", 25)))); + } + + @Test + void aKeyOfTwoColumnsOrdersByBothPartsInKeyOrderWhenNoKeyIsGiven() { + assertEquals( + "SELECT t0.`id`, t1.`ledger`, t1.`seq`\nFROM `shop`.`accounts` t0\n" + + "JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id`\n" + + "WHERE t0.`id` = 1\n AND t1.`ledger` IS NOT NULL\n AND t1.`seq` IS NOT NULL\n" + + "ORDER BY t1.`ledger`, t1.`seq`\nLIMIT 26", + sql( + expand( + model(PAGED_COMPOSITE_RELATED_KEY, "Mysql"), + "Account", + "postedTo", + INVERSE, + List.of(1)))); + } + + @Test + void theOrderIsTheKeyOfTheRelatedClassAndTheStartKeyNeverOrdersTheRows() { + final OntologyMappingShapeModel model = model(PAGED_COMPOSITE_RELATED_KEY, POSTGRES); + + assertEquals( + List.of(1, 2), expand(model, "Account", "postedTo", INVERSE, List.of(1), null).orderedBy()); + assertEquals( + List.of(2), expand(model, "Entry", "postedTo", FORWARD, List.of("b", 7), null).orderedBy()); + assertEquals( + "SELECT t0.ledger, t0.seq, t1.id, t1.name\nFROM shop.entries t0\n" + + "JOIN shop.accounts t1 ON t1.id = t0.account_id\n" + + "WHERE t0.ledger = 'b'\n AND t0.seq = 7\n AND t1.id IS NOT NULL\n" + + " AND t1.id > 0\nORDER BY t1.id\nLIMIT 26", + sql(expand(model, "Entry", "postedTo", FORWARD, List.of("b", 7), List.of(0)))); + } + + @Test + void aFindStatementStaysWithoutAnOrderAndOnlyAnExpandStatementIsOrdered() { + final OntologyMappingShapeModel model = model(COLUMN_RELATION, POSTGRES); + final RecordStatement find = OntologyConceptSqlGenerator.find(model.mapped("Customer"), null); + + assertEquals( + "SELECT t0.id, t0.name\nFROM shop.customers t0\nWHERE t0.id IS NOT NULL\nLIMIT 25", + sql(find)); + assertEquals(List.of(), find.orderedBy()); + assertEquals( + List.of(1), expand(model, "Customer", "placedBy", INVERSE, List.of(1), null).orderedBy()); + } + + @Test + void anAfterOfTheWrongTypeOrTheWrongLengthIsRefusedAsTheKeyIs() { + final OntologyMappingShapeModel model = model(PAGED_COMPOSITE_RELATED_KEY, POSTGRES); + + assertEquals( + "The value for column seq does not parse as INT: a whole number is written in ASCII" + + " digits, with a leading minus sign when negative and no leading zeros", + assertThrows( + BadRequestException.class, + () -> + expand( + model, + "Account", + "postedTo", + INVERSE, + List.of(1), + List.of("a", "25 OR 1=1"))) + .getMessage()); + assertEquals( + "The after key has 2 columns but the request gives 1 value", + assertThrows( + BadRequestException.class, + () -> expand(model, "Account", "postedTo", INVERSE, List.of(1), List.of("a"))) + .getMessage()); + assertEquals( + "The after key has 2 columns but the request gives 3 values", + assertThrows( + BadRequestException.class, + () -> expand(model, "Account", "postedTo", INVERSE, List.of(1), List.of("a", 1, 2))) + .getMessage()); + assertEquals( + sql(expand(model, "Account", "postedTo", INVERSE, List.of(1))), + sql(expand(model, "Account", "postedTo", INVERSE, List.of(1), List.of()))); + } + + @Test + void aKeyOfThreeColumnsKeepsEveryEqualityOfTheLeadingPartsInEachLaterDisjunct() { + final OntologyMappingShapeModel model = model(heldItems(tripleKey()), POSTGRES); + + final RecordStatement page = + expand(model, "Owner", "heldBy", INVERSE, List.of(1), List.of("m", 5, 5)); + + assertEquals( + "SELECT t0.id, t1.k1, t1.k2, t1.k3\nFROM shop.owners t0\n" + + "JOIN shop.items t1 ON t1.owner_id = t0.id\n" + + "WHERE t0.id = 1\n AND t1.k1 IS NOT NULL\n AND t1.k2 IS NOT NULL\n" + + " AND t1.k3 IS NOT NULL\n" + + " AND (t1.k1 > 'm' OR (t1.k1 = 'm' AND t1.k2 > 5)" + + " OR (t1.k1 = 'm' AND t1.k2 = 5 AND t1.k3 > 5))\n" + + "ORDER BY t1.k1, t1.k2, t1.k3\nLIMIT 26", + sql(page)); + assertEquals(List.of(1, 2, 3), page.orderedBy()); + } + + @Test + void aRelatedKeyWithAJsonColumnWritesNoOrderAndNoOrderedByAndTakesNoAfter() { + final OntologyMappingShapeModel model = + model(heldItems(List.of(new ColumnSpec("id", ColumnDataType.JSON))), POSTGRES); + + final RecordStatement first = expand(model, "Owner", "heldBy", INVERSE, List.of(1)); + + assertEquals( + "SELECT t0.id, t1.id\nFROM shop.owners t0\n" + + "JOIN shop.items t1 ON t1.owner_id = t0.id\n" + + "WHERE t0.id = 1\n AND t1.id IS NOT NULL\nLIMIT 26", + sql(first)); + assertEquals(List.of(), first.orderedBy()); + assertEquals( + "SQL generation does not support column type JSON of column id", + assertThrows( + BadRequestException.class, + () -> expand(model, "Owner", "heldBy", INVERSE, List.of(1), List.of(1))) + .getMessage()); + } + + @Test + void aRelatedKeyWithABlobOrAnArrayColumnAmongOthersWritesNoOrder() { + for (final ColumnDataType type : List.of(ColumnDataType.BLOB, ColumnDataType.ARRAY)) { + final OntologyMappingShapeModel model = + model( + heldItems( + List.of(new ColumnSpec("k1", ColumnDataType.INT), new ColumnSpec("k2", type))), + POSTGRES); + + final RecordStatement first = expand(model, "Owner", "heldBy", INVERSE, List.of(1)); + + assertEquals( + "SELECT t0.id, t1.k1, t1.k2\nFROM shop.owners t0\n" + + "JOIN shop.items t1 ON t1.owner_id = t0.id\n" + + "WHERE t0.id = 1\n AND t1.k1 IS NOT NULL\n AND t1.k2 IS NOT NULL\nLIMIT 26", + sql(first)); + assertEquals(List.of(), first.orderedBy()); + assertEquals( + "SQL generation does not support column type " + type.value() + " of column k2", + assertThrows( + BadRequestException.class, + () -> expand(model, "Owner", "heldBy", INVERSE, List.of(1), List.of(1, 1))) + .getMessage()); + } + } + + @Test + void aStartKeyWithAJsonColumnIsRefusedAsBefore() { + final OntologyMappingShapeModel model = + model(heldItems(List.of(new ColumnSpec("id", ColumnDataType.JSON))), POSTGRES); + + assertEquals( + "SQL generation does not support column type JSON of column id", + assertThrows( + BadRequestException.class, + () -> expand(model, "Item", "heldBy", FORWARD, List.of(1))) + .getMessage()); + } + + private static OntologyMappingShapeModel model(final Shape shape, final String serviceType) { + return new OntologyMappingShapeModel(shape, serviceType); + } + + private static RecordStatement expand( + final OntologyMappingShapeModel model, + final String type, + final String relation, + final OntologyStatementDirection direction, + final List key) { + return expand(model, type, relation, direction, key, null); + } + + private static RecordStatement expand( + final OntologyMappingShapeModel model, + final String type, + final String relation, + final OntologyStatementDirection direction, + final List key, + final List after) { + return OntologyConceptSqlGenerator.expand(model.path(type, relation, direction), key, after); + } + + /** The orders table of the column relation shape, with another join for its relation or none. */ + private static BindingSpec orders(final ColumnBindingSpec placedBy) { + final List columns = new ArrayList<>(); + columns.add(new ColumnBindingSpec("orderTotal", "total", null)); + if (placedBy != null) { + columns.add(placedBy); + } + return new BindingSpec( + "Order", "orders", OntologyBindingRole.IDENTITY, List.of("id"), null, columns); + } + + private static ColumnBindingSpec placedBy(final OntologyJoinStatus status) { + return new ColumnBindingSpec( + "placedBy", + "customer_id", + new JoinSpec("customers", status, List.of("customer_id"), List.of("id"))); + } + + /** The link table shape with a row filter on each of its three tables. */ + static OntologyMappingShapeModel filteredLinkTable(final String serviceType) { + return new OntologyMappingShapeModel( + LINK_TABLE, + serviceType, + List.of( + new BindingSpec( + "Order", + "orders", + OntologyBindingRole.IDENTITY, + List.of("id"), + new FilterSpec("channel", OntologyRowFilterOperator.EQUALS, "web"), + List.of(new ColumnBindingSpec("orderChannel", "channel", null))), + new BindingSpec( + "Product", + "products", + OntologyBindingRole.IDENTITY, + List.of("sku"), + new FilterSpec("title", OntologyRowFilterOperator.NOT_EQUALS, "Drill"), + List.of(new ColumnBindingSpec("productTitle", "title", null))), + new BindingSpec( + "Order", + "order_items", + OntologyBindingRole.CONTRIBUTING, + List.of("order_id"), + new FilterSpec("quantity", OntologyRowFilterOperator.GREATER_THAN, 0), + LINK_TABLE.bindings().getLast().columns()))); + } + + /** The link table shape with a second link table that holds the same relation. */ + private static Shape twoLinkTables() { + final List tables = new ArrayList<>(LINK_TABLE.tables()); + tables.add( + new TableSpec( + "order_lines", + List.of( + new ColumnSpec("order_id", ColumnDataType.INT), + new ColumnSpec("product_sku", ColumnDataType.VARCHAR)), + List.of())); + final List bindings = new ArrayList<>(LINK_TABLE.bindings()); + bindings.add( + new BindingSpec( + "Order", + "order_lines", + OntologyBindingRole.CONTRIBUTING, + List.of("order_id"), + null, + List.of( + new ColumnBindingSpec( + "contains", + "product_sku", + new JoinSpec( + "products", + OntologyJoinStatus.CONFIRMED, + List.of("product_sku"), + List.of("sku")))))); + return new Shape( + LINK_TABLE.name(), + tables, + LINK_TABLE.classes(), + LINK_TABLE.properties(), + bindings, + List.of()); + } + + /** One class whose relation reaches the same class: an employee reports to an employee. */ + private static Shape staff() { + return new Shape( + "staff", + List.of( + new TableSpec( + "employees", + List.of( + new ColumnSpec("id", ColumnDataType.INT), + new ColumnSpec("manager_id", ColumnDataType.INT), + new ColumnSpec("name", ColumnDataType.VARCHAR)), + List.of())), + List.of("Employee"), + List.of( + new PropertySpec("employeeName", true, "Employee", null), + new PropertySpec("reportsTo", false, "Employee", "Employee")), + List.of( + new BindingSpec( + "Employee", + "employees", + OntologyBindingRole.IDENTITY, + List.of("id"), + null, + List.of( + new ColumnBindingSpec("employeeName", "name", null), + new ColumnBindingSpec( + "reportsTo", + "manager_id", + new JoinSpec( + "employees", + OntologyJoinStatus.CONFIRMED, + List.of("manager_id"), + List.of("id")))))), + List.of()); + } + + private static List tripleKey() { + return List.of( + new ColumnSpec("k1", ColumnDataType.VARCHAR), + new ColumnSpec("k2", ColumnDataType.INT), + new ColumnSpec("k3", ColumnDataType.DECIMAL)); + } + + private static Shape heldItems(final List key) { + return OntologyMappingShapes.heldItems("heldItems", key, List.of(), List.of()); + } + + /** An invoice names its account with two columns, the two-column key of the accounts table. */ + private static Shape billing() { + return new Shape( + "billing", + List.of( + new TableSpec( + "accounts", + List.of( + new ColumnSpec("tenant_id", ColumnDataType.VARCHAR), + new ColumnSpec("account_id", ColumnDataType.INT)), + List.of()), + new TableSpec( + "invoices", + List.of( + new ColumnSpec("id", ColumnDataType.INT), + new ColumnSpec("tenant", ColumnDataType.VARCHAR), + new ColumnSpec("account", ColumnDataType.INT)), + List.of())), + List.of("Account", "Invoice"), + List.of(new PropertySpec("billedTo", false, "Invoice", "Account")), + List.of( + new BindingSpec( + "Account", + "accounts", + OntologyBindingRole.IDENTITY, + List.of("tenant_id", "account_id"), + null, + List.of()), + new BindingSpec( + "Invoice", + "invoices", + OntologyBindingRole.IDENTITY, + List.of("id"), + null, + List.of( + new ColumnBindingSpec( + "billedTo", + "account", + new JoinSpec( + "accounts", + OntologyJoinStatus.CONFIRMED, + List.of("tenant", "account"), + List.of("tenant_id", "account_id")))))), + List.of()); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyLinkShapes.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyLinkShapes.java new file mode 100644 index 000000000000..61a736ae42d0 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyLinkShapes.java @@ -0,0 +1,447 @@ +/* + * 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.ontology; + +import static org.openmetadata.service.ontology.OntologyMappingShapes.bound; +import static org.openmetadata.service.ontology.OntologyMappingShapes.columns; +import static org.openmetadata.service.ontology.OntologyMappingShapes.contributing; +import static org.openmetadata.service.ontology.OntologyMappingShapes.data; +import static org.openmetadata.service.ontology.OntologyMappingShapes.identity; +import static org.openmetadata.service.ontology.OntologyMappingShapes.integer; +import static org.openmetadata.service.ontology.OntologyMappingShapes.joined; +import static org.openmetadata.service.ontology.OntologyMappingShapes.relation; +import static org.openmetadata.service.ontology.OntologyMappingShapes.row; +import static org.openmetadata.service.ontology.OntologyMappingShapes.table; +import static org.openmetadata.service.ontology.OntologyMappingShapes.text; + +import java.util.List; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementMeasure; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; + +/** + * Seven mappings of one relation, each with the two link counts of its relation, one for each + * direction. Their tables hold the rows that a link count must treat each in its own way: a + * related key with a null part, a pair stored twice, a start row the row filter excludes, a key + * that no related row holds, and a link table that repeats a pair. Each count is a literal that a + * person worked out from the rows. + * + *

    These mappings are separate from {@link OntologyMappingShapes#all()} because their rows + * would change the rows that the other statements of those shapes return. + */ +public final class OntologyLinkShapes { + private static final List LINKS_TO_CUSTOMER = columns("count Customer"); + private static final List LINKS_TO_ORDER = columns("count Order"); + private static final List LINKS_TO_PRODUCT = columns("count Product"); + private static final List LINKS_TO_BRANCH = columns("count Branch"); + private static final List LINKS_TO_EMPLOYEE = columns("count Employee"); + private static final List LINKS_TO_ORGANIZATION = columns("count Organization"); + private static final List LINKS_TO_PERSON = columns("count Person"); + + private OntologyLinkShapes() {} + + /** + * 1. A relation held in a column of an unfiltered identity table. Order 3 is stored twice, order + * 4 names no customer, order 5 names a customer that no row holds, and one row has no id. + * + *

    Forward, the pairs are (1,1), (2,1), (3,2) and (5,9). Inverse, they are customer 1 with + * orders 1 and 2, and customer 2 with order 3, since customer 9 is no start record and the row + * with no id has no related key. + */ + public static final Shape COLUMN = + new Shape( + "linkColumn", + List.of( + table( + "customers", + List.of(integer("id"), text("name")), + row(1, "Ada Lovelace"), + row(2, "Grace Hopper"), + row(3, "Alan Turing")), + table( + "orders", + List.of(integer("id"), integer("customer_id")), + row(1, 1), + row(2, 1), + row(3, 2), + row(3, 2), + row(4, null), + row(5, 9), + row(null, 1))), + List.of("Order", "Customer"), + List.of(relation("placedBy", "Order", "Customer")), + List.of( + identity("Customer", "customers", List.of("id"), null), + identity( + "Order", + "orders", + List.of("id"), + null, + joined("placedBy", "customer_id", "customers", "id"))), + both("Order", "Customer", "placedBy", LINKS_TO_CUSTOMER, 4, LINKS_TO_ORDER, 3)); + + /** + * 2. Two classes over one table, each with a row filter. A person works for an organization, and + * the relation is held in the column {@code employer_id}. Person 1 is stored twice, person 3 has + * no employer, person 4 names an employer that no row holds, person 6 names a vendor that is no + * organization, and the vendor row 5 is no person. + * + *

    Forward, the pairs are (1,10), (2,10), (4,99) and (6,11). Inverse, only organization 10 is + * a start record, and a link is a pair with a person, so persons 1 and 2 count and vendor 5, + * which the person filter excludes, does not. + */ + public static final Shape FILTERED_START = + new Shape( + "linkFilteredStart", + List.of( + table( + "parties", + List.of(integer("id"), text("kind"), text("name"), integer("employer_id")), + row(1, "person", "Ada Lovelace", 10), + row(1, "person", "Ada Lovelace", 10), + row(2, "person", "Grace Hopper", 10), + row(3, "person", "Alan Turing", null), + row(4, "person", "Edsger Dijkstra", 99), + row(5, "vendor", "Initech", 10), + row(6, "person", "Barbara Liskov", 11), + row(10, "organization", "Acme", null), + row(11, "vendor", "Globex", null))), + List.of("Person", "Organization"), + List.of(relation("worksFor", "Person", "Organization")), + List.of( + identity( + "Person", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "person"), + joined("worksFor", "employer_id", "parties", "id")), + identity( + "Organization", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "organization"))), + both("Person", "Organization", "worksFor", LINKS_TO_ORGANIZATION, 4, LINKS_TO_PERSON, 2)); + + /** + * 3. A relation held in two columns, with a key of two columns at its far end. Employee 4 has no + * tenant, employee 5 has no branch, employee 6 names a branch that no row holds, employee 1 is + * stored twice, and one row has no id. + * + *

    Forward, the pairs are (1,eu,1), (2,eu,1), (3,us,1) and (6,eu,7). Inverse, they are branch + * (eu,1) with employees 1 and 2, and branch (us,1) with employee 3. + */ + public static final Shape COMPOSITE_KEY = + new Shape( + "linkCompositeKey", + List.of( + table( + "branches", + List.of(text("tenant_id"), integer("branch_id"), text("name")), + row("eu", 1, "Berlin"), + row("eu", 2, "Paris"), + row("us", 1, "Austin")), + table( + "employees", + List.of(integer("id"), text("tenant"), integer("branch")), + row(1, "eu", 1), + row(1, "eu", 1), + row(2, "eu", 1), + row(3, "us", 1), + row(4, null, 1), + row(5, "eu", null), + row(6, "eu", 7), + row(null, "eu", 1))), + List.of("Employee", "Branch"), + List.of(relation("worksAt", "Employee", "Branch")), + List.of( + identity("Branch", "branches", List.of("tenant_id", "branch_id"), null), + identity( + "Employee", + "employees", + List.of("id"), + null, + twoColumnJoin( + "worksAt", + "branches", + List.of("tenant", "branch"), + List.of("tenant_id", "branch_id")))), + both("Employee", "Branch", "worksAt", LINKS_TO_BRANCH, 4, LINKS_TO_EMPLOYEE, 3)); + + /** + * 4. A relation held in a link table that repeats a pair. Order 1 holds product A-1 twice, one + * row has no order, one has no product, and order 3 names a product that no row holds. + * + *

    Forward, the pairs are (1,A-1), (1,B-2), (2,A-1) and (3,Z-9). Inverse, they are product A-1 + * with orders 1 and 2, and product B-2 with order 1. + */ + public static final Shape LINK_TABLE = + new Shape( + "linkLinkTable", + List.of( + table( + "orders", + List.of(integer("id"), text("channel")), + row(1, "web"), + row(2, "store"), + row(3, "web")), + table( + "products", + List.of(text("sku"), text("title")), + row("A-1", "Anvil"), + row("B-2", "Bolt"), + row("C-3", "Crate"), + row("D-4", "Drill")), + table( + "order_items", + List.of(integer("order_id"), text("product_sku"), integer("quantity")), + row(1, "A-1", 2), + row(1, "A-1", 7), + row(1, "B-2", 1), + row(2, "A-1", 1), + row(null, "B-2", 1), + row(2, null, 3), + row(3, "Z-9", 1), + row(7, "A-1", 1))), + List.of("Order", "Product"), + List.of(relation("contains", "Order", "Product")), + List.of( + identity("Order", "orders", List.of("id"), null), + identity("Product", "products", List.of("sku"), null), + contributing( + "Order", + "order_items", + List.of("order_id"), + joined("contains", "product_sku", "products", "sku"))), + both("Order", "Product", "contains", LINKS_TO_PRODUCT, 4, LINKS_TO_ORDER, 3)); + + /** + * 5. A link table whose class has a key of two columns, so the table pairs two columns with it. + * Line (eu,1,A-1) is stored twice, one line has no product, one names a product that no row + * holds, and one has no order number. + * + *

    Forward, the pairs are (eu,1,A-1), (eu,1,B-2), (eu,2,A-1) and (us,1,Q-0). Inverse, they + * are product A-1 with orders (eu,1) and (eu,2), and product B-2 with order (eu,1). + */ + public static final Shape COMPOSITE_LINK_TABLE = + new Shape( + "linkCompositeLinkTable", + List.of( + table( + "orders", + List.of(text("tenant"), integer("order_no"), text("channel")), + row("eu", 1, "web"), + row("eu", 2, "web"), + row("us", 1, "store")), + table( + "products", + List.of(text("sku"), text("title")), + row("A-1", "Anvil"), + row("B-2", "Bolt")), + table( + "order_lines", + List.of(text("tenant"), integer("order_no"), text("sku")), + row("eu", 1, "A-1"), + row("eu", 1, "A-1"), + row("eu", 1, "B-2"), + row("eu", 2, "A-1"), + row("us", 1, null), + row("us", 1, "Q-0"), + row("eu", null, "B-2"))), + List.of("Order", "Product"), + List.of(relation("contains", "Order", "Product")), + List.of( + identity("Order", "orders", List.of("tenant", "order_no"), null), + identity("Product", "products", List.of("sku"), null), + contributing( + "Order", + "order_lines", + List.of("tenant", "order_no"), + joined("contains", "sku", "products", "sku"))), + both("Order", "Product", "contains", LINKS_TO_PRODUCT, 4, LINKS_TO_ORDER, 3)); + + /** + * 6. A link table whose class holds a row filter. Order 2 is a store order that the filter + * excludes, and its line links product A-1. Order 3 holds Z-9 twice and one line with no product. + * + *

    Forward, the pairs are (1,A-1), (1,B-2) and (3,Z-9). Inverse, the pairs are product A-1 with + * order 1 and product B-2 with order 1, because order 2 is no record of the filtered class. + */ + public static final Shape FILTERED_LINK_TABLE = + new Shape( + "linkFilteredLinkTable", + List.of( + table( + "orders", + List.of(integer("id"), text("channel")), + row(1, "web"), + row(2, "store"), + row(3, "web"), + row(4, "web")), + table( + "products", + List.of(text("sku"), text("title")), + row("A-1", "Anvil"), + row("B-2", "Bolt")), + table( + "order_items", + List.of(integer("order_id"), text("product_sku")), + row(1, "A-1"), + row(1, "B-2"), + row(2, "A-1"), + row(3, null), + row(3, "Z-9"), + row(3, "Z-9"))), + List.of("Order", "Product"), + List.of(relation("contains", "Order", "Product")), + List.of( + identity( + "Order", + "orders", + List.of("id"), + new FilterSpec("channel", OntologyRowFilterOperator.EQUALS, "web")), + identity("Product", "products", List.of("sku"), null), + contributing( + "Order", + "order_items", + List.of("order_id"), + joined("contains", "product_sku", "products", "sku"))), + both("Order", "Product", "contains", LINKS_TO_PRODUCT, 3, LINKS_TO_ORDER, 2)); + + /** + * 7. A relation held by a table that is no link table: it carries a data column and a row filter + * of its own, over a class that holds a row filter. Detail (1,us) is a web order that the detail + * filter excludes, order 2 is a store order, order 9 has no order row, and order 3 names no + * customer once and customer 30, which no row holds, once. + * + *

    Forward, the pairs are (1,10) and (3,30). Inverse, they are customer 10 with order 1, since + * order 2 is a store order, order 9 is no order, and customer 30 is no start record. + */ + public static final Shape FILTERED_CONTRIBUTING = + new Shape( + "linkFilteredContributing", + List.of( + table( + "orders", + List.of(integer("id"), text("channel")), + row(1, "web"), + row(2, "store"), + row(3, "web")), + table("customers", List.of(integer("id")), row(10), row(20)), + table( + "order_details", + List.of( + integer("order_id"), text("region"), text("note"), integer("customer_id")), + row(1, "eu", "a", 10), + row(1, "us", "b", 20), + row(2, "eu", "c", 10), + row(3, "eu", "d", null), + row(9, "eu", "e", 20), + row(3, "eu", "f", 30))), + List.of("Order", "Customer"), + List.of(relation("placedBy", "Order", "Customer"), data("note", false, "Order")), + List.of( + identity( + "Order", + "orders", + List.of("id"), + new FilterSpec("channel", OntologyRowFilterOperator.EQUALS, "web")), + identity("Customer", "customers", List.of("id"), null), + new BindingSpec( + "Order", + "order_details", + OntologyBindingRole.CONTRIBUTING, + List.of("order_id"), + new FilterSpec("region", OntologyRowFilterOperator.EQUALS, "eu"), + List.of( + bound("note", "note"), + joined("placedBy", "customer_id", "customers", "id")))), + both("Order", "Customer", "placedBy", LINKS_TO_CUSTOMER, 2, LINKS_TO_ORDER, 1)); + + public static List all() { + return List.of( + COLUMN, + FILTERED_START, + COMPOSITE_KEY, + LINK_TABLE, + COMPOSITE_LINK_TABLE, + FILTERED_LINK_TABLE, + FILTERED_CONTRIBUTING); + } + + /** The link count of a relation from the class that binds it, and from the class it reaches. */ + private static List both( + final String subject, + final String object, + final String relation, + final List forwardColumns, + final int forward, + final List inverseColumns, + final int inverse) { + return List.of( + links( + "links-forward", + subject, + relation, + OntologyStatementDirection.FORWARD, + forwardColumns, + forward), + links( + "links-inverse", + object, + relation, + OntologyStatementDirection.INVERSE, + inverseColumns, + inverse)); + } + + private static Ask links( + final String name, + final String type, + final String relation, + final OntologyStatementDirection direction, + final List columns, + final int count) { + return new Ask( + name, + OntologyStatementKind.AGGREGATE, + type, + null, + null, + relation, + direction, + columns, + List.of(List.of(String.valueOf(count))), + OntologyStatementMeasure.LINK_COUNT); + } + + private static ColumnBindingSpec twoColumnJoin( + final String property, + final String target, + final List child, + final List parent) { + return new ColumnBindingSpec( + property, + child.getFirst(), + new JoinSpec(target, OntologyJoinStatus.CONFIRMED, child, parent)); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingAdviceRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingAdviceRulesTest.java new file mode 100644 index 000000000000..ea0fc4870794 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingAdviceRulesTest.java @@ -0,0 +1,721 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.openmetadata.schema.api.data.OntologyMappingHealthEntry; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.TagLabel; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.BoundTable; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Context; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Identity; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Progress; + +/** The advice about sensitive key columns and about columns whose type cannot hold a property. */ +class OntologyMappingAdviceRulesTest { + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + private static final EntityReference SALES = reference("database", "sales"); + private static final EntityReference CUSTOMER = reference("ontologyConcept", "Customer"); + + @Test + void aTaggedKeyColumnIsReportedAndAnUntaggedOneIsNot() { + final Table table = + table( + "customers", + column("id", ColumnDataType.BIGINT), + tagged(column("email", ColumnDataType.VARCHAR), "PII.Sensitive")); + + assertEquals( + List.of("sensitiveKeyColumn [email]"), + advice(table, OntologyBindingRole.IDENTITY, List.of(List.of("email")), List.of())); + assertEquals( + List.of(), advice(table, OntologyBindingRole.IDENTITY, List.of(List.of("id")), List.of())); + } + + @Test + void aKeyColumnUnderATaggedParentIsReportedAndSoIsAKeyThatCoversATaggedChild() { + final Table table = + table( + "customers", + tagged( + column("contact", ColumnDataType.STRUCT) + .withChildren(List.of(column("phone", ColumnDataType.VARCHAR))), + "PII.Sensitive"), + column("profile", ColumnDataType.STRUCT) + .withChildren( + List.of(tagged(column("ssn", ColumnDataType.VARCHAR), "PII.Sensitive")))); + + assertEquals( + List.of("sensitiveKeyColumn [contact, phone]"), + advice( + table, OntologyBindingRole.IDENTITY, List.of(List.of("contact", "phone")), List.of())); + assertEquals( + List.of("sensitiveKeyColumn [profile]"), + advice(table, OntologyBindingRole.IDENTITY, List.of(List.of("profile")), List.of())); + assertEquals( + List.of(), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(List.of("profile", "missing")), + List.of())); + } + + @Test + void aTaggedTableReportsEveryKeyColumnInKeyOrder() { + final Table table = + tagged( + table( + "customers", + column("tenant", ColumnDataType.VARCHAR), + column("id", ColumnDataType.BIGINT)), + "PII.Sensitive"); + + assertEquals( + List.of("sensitiveKeyColumn [id]", "sensitiveKeyColumn [tenant]"), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(List.of("id"), List.of("tenant")), + List.of())); + } + + @Test + void aKeyOfTwoColumnsWithOneTaggedReportsThatColumnOnly() { + final Table table = + table( + "customers", + column("tenant", ColumnDataType.VARCHAR), + tagged(column("id", ColumnDataType.BIGINT), "PII.Sensitive")); + + assertEquals( + List.of("sensitiveKeyColumn [id]"), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(List.of("tenant"), List.of("id")), + List.of())); + } + + @Test + void aContributingTableIsCheckedAndABindingWithNoRoleIsNot() { + final Table table = + table("customers", tagged(column("id", ColumnDataType.BIGINT), "PII.Sensitive")); + + assertEquals( + List.of("sensitiveKeyColumn [id]"), + advice(table, OntologyBindingRole.CONTRIBUTING, List.of(List.of("id")), List.of())); + assertEquals(List.of(), advice(table, null, List.of(List.of("id")), List.of())); + } + + @Test + void aKeyColumnThatWasDroppedIsNoFinding() { + final Table table = + tagged(table("customers", column("id", ColumnDataType.BIGINT)), "PII.Sensitive"); + + assertEquals( + List.of(), + advice(table, OntologyBindingRole.IDENTITY, List.of(List.of("gone")), List.of())); + } + + @Test + void otherTagsAreNotSensitive() { + final Table table = + tagged( + table( + "customers", + tagged( + column("id", ColumnDataType.BIGINT), + "PII.NonSensitive", + "Tier.Tier1", + "PII.SensitiveData")), + "PII.NonSensitive"); + + assertEquals( + List.of(), advice(table, OntologyBindingRole.IDENTITY, List.of(List.of("id")), List.of())); + } + + @ParameterizedTest(name = "{0} against {1} is a mismatch: {2}") + @CsvSource( + delimiter = ',', + value = { + "integer,INT,false", + "integer,VARCHAR,true", + "integer,DATE,true", + "integer,TIMESTAMP,true", + "integer,TIME,true", + "integer,BOOLEAN,true", + "integer,BIT,true", + "integer,JSON,false", + "integer,UNKNOWN,false", + "int,INT,false", + "int,VARCHAR,true", + "int,DATE,true", + "int,TIMESTAMP,true", + "int,TIME,true", + "int,BOOLEAN,true", + "int,BIT,true", + "int,JSON,false", + "int,UNKNOWN,false", + "long,INT,false", + "long,VARCHAR,true", + "long,DATE,true", + "long,TIMESTAMP,true", + "long,TIME,true", + "long,BOOLEAN,true", + "long,BIT,true", + "long,JSON,false", + "long,UNKNOWN,false", + "short,INT,false", + "short,VARCHAR,true", + "short,DATE,true", + "short,TIMESTAMP,true", + "short,TIME,true", + "short,BOOLEAN,true", + "short,BIT,true", + "short,JSON,false", + "short,UNKNOWN,false", + "byte,INT,false", + "byte,VARCHAR,true", + "byte,DATE,true", + "byte,TIMESTAMP,true", + "byte,TIME,true", + "byte,BOOLEAN,true", + "byte,BIT,true", + "byte,JSON,false", + "byte,UNKNOWN,false", + "nonNegativeInteger,INT,false", + "nonNegativeInteger,VARCHAR,true", + "nonNegativeInteger,DATE,true", + "nonNegativeInteger,TIMESTAMP,true", + "nonNegativeInteger,TIME,true", + "nonNegativeInteger,BOOLEAN,true", + "nonNegativeInteger,BIT,true", + "nonNegativeInteger,JSON,false", + "nonNegativeInteger,UNKNOWN,false", + "positiveInteger,INT,false", + "positiveInteger,VARCHAR,true", + "positiveInteger,DATE,true", + "positiveInteger,TIMESTAMP,true", + "positiveInteger,TIME,true", + "positiveInteger,BOOLEAN,true", + "positiveInteger,BIT,true", + "positiveInteger,JSON,false", + "positiveInteger,UNKNOWN,false", + "negativeInteger,INT,false", + "negativeInteger,VARCHAR,true", + "negativeInteger,DATE,true", + "negativeInteger,TIMESTAMP,true", + "negativeInteger,TIME,true", + "negativeInteger,BOOLEAN,true", + "negativeInteger,BIT,true", + "negativeInteger,JSON,false", + "negativeInteger,UNKNOWN,false", + "nonPositiveInteger,INT,false", + "nonPositiveInteger,VARCHAR,true", + "nonPositiveInteger,DATE,true", + "nonPositiveInteger,TIMESTAMP,true", + "nonPositiveInteger,TIME,true", + "nonPositiveInteger,BOOLEAN,true", + "nonPositiveInteger,BIT,true", + "nonPositiveInteger,JSON,false", + "nonPositiveInteger,UNKNOWN,false", + "unsignedLong,INT,false", + "unsignedLong,VARCHAR,true", + "unsignedLong,DATE,true", + "unsignedLong,TIMESTAMP,true", + "unsignedLong,TIME,true", + "unsignedLong,BOOLEAN,true", + "unsignedLong,BIT,true", + "unsignedLong,JSON,false", + "unsignedLong,UNKNOWN,false", + "unsignedInt,INT,false", + "unsignedInt,VARCHAR,true", + "unsignedInt,DATE,true", + "unsignedInt,TIMESTAMP,true", + "unsignedInt,TIME,true", + "unsignedInt,BOOLEAN,true", + "unsignedInt,BIT,true", + "unsignedInt,JSON,false", + "unsignedInt,UNKNOWN,false", + "unsignedShort,INT,false", + "unsignedShort,VARCHAR,true", + "unsignedShort,DATE,true", + "unsignedShort,TIMESTAMP,true", + "unsignedShort,TIME,true", + "unsignedShort,BOOLEAN,true", + "unsignedShort,BIT,true", + "unsignedShort,JSON,false", + "unsignedShort,UNKNOWN,false", + "unsignedByte,INT,false", + "unsignedByte,VARCHAR,true", + "unsignedByte,DATE,true", + "unsignedByte,TIMESTAMP,true", + "unsignedByte,TIME,true", + "unsignedByte,BOOLEAN,true", + "unsignedByte,BIT,true", + "unsignedByte,JSON,false", + "unsignedByte,UNKNOWN,false", + "decimal,INT,false", + "decimal,VARCHAR,true", + "decimal,DATE,true", + "decimal,TIMESTAMP,true", + "decimal,TIME,true", + "decimal,BOOLEAN,true", + "decimal,BIT,true", + "decimal,JSON,false", + "decimal,UNKNOWN,false", + "float,INT,false", + "float,VARCHAR,true", + "float,DATE,true", + "float,TIMESTAMP,true", + "float,TIME,true", + "float,BOOLEAN,true", + "float,BIT,true", + "float,JSON,false", + "float,UNKNOWN,false", + "double,INT,false", + "double,VARCHAR,true", + "double,DATE,true", + "double,TIMESTAMP,true", + "double,TIME,true", + "double,BOOLEAN,true", + "double,BIT,true", + "double,JSON,false", + "double,UNKNOWN,false", + "date,INT,true", + "date,VARCHAR,true", + "date,DATE,false", + "date,TIMESTAMP,false", + "date,TIME,true", + "date,BOOLEAN,true", + "date,BIT,true", + "date,JSON,false", + "date,UNKNOWN,false", + "dateTime,INT,true", + "dateTime,VARCHAR,true", + "dateTime,DATE,false", + "dateTime,TIMESTAMP,false", + "dateTime,TIME,true", + "dateTime,BOOLEAN,true", + "dateTime,BIT,true", + "dateTime,JSON,false", + "dateTime,UNKNOWN,false", + "dateTimeStamp,INT,true", + "dateTimeStamp,VARCHAR,true", + "dateTimeStamp,DATE,false", + "dateTimeStamp,TIMESTAMP,false", + "dateTimeStamp,TIME,true", + "dateTimeStamp,BOOLEAN,true", + "dateTimeStamp,BIT,true", + "dateTimeStamp,JSON,false", + "dateTimeStamp,UNKNOWN,false", + "time,INT,true", + "time,VARCHAR,true", + "time,DATE,false", + "time,TIMESTAMP,false", + "time,TIME,false", + "time,BOOLEAN,true", + "time,BIT,true", + "time,JSON,false", + "time,UNKNOWN,false", + "boolean,INT,false", + "boolean,VARCHAR,true", + "boolean,DATE,true", + "boolean,TIMESTAMP,true", + "boolean,TIME,true", + "boolean,BOOLEAN,false", + "boolean,BIT,false", + "boolean,JSON,false", + "boolean,UNKNOWN,false", + "string,INT,false", + "string,VARCHAR,false", + "string,DATE,false", + "string,TIMESTAMP,false", + "string,TIME,false", + "string,BOOLEAN,false", + "string,BIT,false", + "string,JSON,false", + "string,UNKNOWN,false", + "anyURI,INT,false", + "anyURI,VARCHAR,false", + "anyURI,DATE,false", + "anyURI,TIMESTAMP,false", + "anyURI,TIME,false", + "anyURI,BOOLEAN,false", + "anyURI,BIT,false", + "anyURI,JSON,false", + "anyURI,UNKNOWN,false", + "duration,INT,false", + "duration,VARCHAR,false", + "duration,DATE,false", + "duration,TIMESTAMP,false", + "duration,TIME,false", + "duration,BOOLEAN,false", + "duration,BIT,false", + "duration,JSON,false", + "duration,UNKNOWN,false", + "hexBinary,INT,false", + "hexBinary,VARCHAR,false", + "hexBinary,DATE,false", + "hexBinary,TIMESTAMP,false", + "hexBinary,TIME,false", + "hexBinary,BOOLEAN,false", + "hexBinary,BIT,false", + "hexBinary,JSON,false", + "hexBinary,UNKNOWN,false", + "gYear,INT,false", + "gYear,VARCHAR,false", + "gYear,DATE,false", + "gYear,TIMESTAMP,false", + "gYear,TIME,false", + "gYear,BOOLEAN,false", + "gYear,BIT,false", + "gYear,JSON,false", + "gYear,UNKNOWN,false", + }) + void aColumnTypeIsCheckedAgainstTheDatatypeOfItsProperty( + final String datatype, final ColumnDataType type, final boolean mismatch) { + final Table table = table("customers", column("c", type)); + final OntologyProperty property = dataProperty("p", XSD + datatype); + + assertEquals( + mismatch ? List.of("columnTypeMismatch [c] " + type + " " + XSD + datatype) : List.of(), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(), + List.of(binding(property, "c")), + property)); + } + + @ParameterizedTest + @CsvSource({"VARCHAR,true", "INT,true", "DATE,false", "TIMESTAMP,false", "DATETIME,false"}) + void aColumnTypeIsCheckedAgainstThePlatformDateType( + final ColumnDataType type, final boolean mismatch) { + final Table table = table("customers", column("c", type)); + final OntologyProperty property = dataProperty("p", OwlDatatypeSupport.DATE.toString()); + + assertEquals( + mismatch + ? List.of("columnTypeMismatch [c] " + type + " " + OwlDatatypeSupport.DATE) + : List.of(), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(), + List.of(binding(property, "c")), + property)); + } + + @Test + void aPropertyWithNoSingleDatatypeIsNeverChecked() { + final Table table = table("customers", column("c", ColumnDataType.VARCHAR)); + final OntologyProperty noRange = dataProperty("noRange"); + final OntologyProperty twoRanges = dataProperty("twoRanges", XSD + "integer", XSD + "decimal"); + final OntologyProperty classRange = dataProperty("classRange", "urn:Customer"); + final OntologyProperty relation = + property("relation", OntologyPropertyKind.OBJECT) + .withRange(List.of(URI.create(XSD + "integer"))); + + for (final OntologyProperty property : List.of(noRange, twoRanges, classRange, relation)) { + assertEquals( + List.of(), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(), + List.of(binding(property, "c")), + property), + property.getName()); + } + } + + @Test + void aColumnThatWasDroppedAndADeprecatedPropertyAreHandledLikeAnyOther() { + final Table table = table("customers", column("c", ColumnDataType.VARCHAR)); + final OntologyProperty deprecated = dataProperty("old", XSD + "integer").withDeprecated(true); + + assertEquals( + List.of("columnTypeMismatch [c] VARCHAR " + XSD + "integer"), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(), + List.of(binding(deprecated, "c")), + deprecated)); + assertEquals( + List.of(), + advice( + table, + OntologyBindingRole.IDENTITY, + List.of(), + List.of(binding(deprecated, "gone")), + deprecated)); + } + + @Test + void aPropertyTheCallerMayNotViewGivesNoTypeFinding() { + final Table table = table("customers", column("c", ColumnDataType.VARCHAR)); + final OntologyProperty hidden = dataProperty("hidden", XSD + "integer"); + + assertEquals( + List.of(), + advice(table, OntologyBindingRole.IDENTITY, List.of(), List.of(binding(hidden, "c")))); + } + + @Test + void theFindingsOfOneTableComeInTheOrderExistingThenSensitiveKeysThenTypes() { + final Table customers = table("customers", column("id", ColumnDataType.BIGINT)); + final Table table = + tagged( + table( + "orders", + column("tenant", ColumnDataType.VARCHAR), + column("order_id", ColumnDataType.BIGINT), + column("customer_id", ColumnDataType.BIGINT), + column("placed", ColumnDataType.VARCHAR), + column("quantity", ColumnDataType.VARCHAR)), + "PII.Sensitive"); + final OntologyProperty placedBy = property("placedBy", OntologyPropertyKind.OBJECT); + final OntologyProperty placedOn = dataProperty("placedOn", XSD + "dateTime"); + final OntologyProperty quantity = dataProperty("quantity", XSD + "integer"); + final OntologyColumnJoin inferred = + new OntologyColumnJoin() + .withTargetAssetId(customers.getId()) + .withStatus(OntologyJoinStatus.INFERRED) + .withOn( + List.of( + new OntologyJoinColumnPair() + .withChild(List.of("customer_id")) + .withParent(List.of("id")))); + final BindingRow row = + row( + table, + OntologyBindingRole.IDENTITY, + List.of(List.of("tenant"), List.of("order_id")), + List.of( + binding(placedOn, "placed"), + binding(placedBy, "customer_id").withJoin(inferred), + binding(quantity, "quantity"))); + + final var entries = + OntologyMappingHealthRules.check( + List.of(new BoundTable(row, CUSTOMER, table)), + new Context( + null, + Map.of(CUSTOMER.getId(), new Identity(row, table)), + Map.of( + placedBy.getId(), + placedBy, + placedOn.getId(), + placedOn, + quantity.getId(), + quantity), + Map.of(customers.getId(), customers)), + Progress.start()) + .entries(); + + assertEquals( + List.of( + "joinNotConfirmed [customer_id]", + "sensitiveKeyColumn [tenant]", + "sensitiveKeyColumn [order_id]", + "columnTypeMismatch [placed]", + "columnTypeMismatch [quantity]"), + entries.stream() + .map(entry -> entry.getType().value() + " " + entry.getColumnPath()) + .toList()); + } + + @Test + void theEntriesCarryTheFieldsTheirTypesPromise() { + final Table table = + table( + "customers", + tagged(column("id", ColumnDataType.BIGINT), "PII.Sensitive"), + column("age", ColumnDataType.VARCHAR)); + final OntologyProperty age = dataProperty("age", XSD + "integer"); + final BindingRow row = + row( + table, + OntologyBindingRole.IDENTITY, + List.of(List.of("id")), + List.of(binding(age, "age"))); + + final List entries = + OntologyMappingHealthRules.check( + List.of(new BoundTable(row, CUSTOMER, table)), + new Context( + null, + Map.of(CUSTOMER.getId(), new Identity(row, table)), + Map.of(age.getId(), age), + Map.of()), + Progress.start()) + .entries(); + + assertEquals( + "{\"type\":\"sensitiveKeyColumn\",\"concept\":\"Customer\",\"asset\":\"customers\"," + + "\"columnPath\":[\"id\"]}", + render(entries.get(0))); + assertEquals( + "{\"type\":\"columnTypeMismatch\",\"concept\":\"Customer\",\"asset\":\"customers\"," + + "\"property\":\"age\",\"columnPath\":[\"age\"],\"dataType\":\"VARCHAR\"," + + "\"propertyDatatype\":\"http://www.w3.org/2001/XMLSchema#integer\"}", + render(entries.get(1))); + } + + private static String render(final OntologyMappingHealthEntry entry) { + final StringBuilder json = new StringBuilder("{\"type\":\"" + entry.getType().value() + "\""); + json.append(",\"concept\":\"").append(entry.getConcept().getName()).append("\""); + json.append(",\"asset\":\"").append(entry.getAsset().getName()).append("\""); + if (entry.getProperty() != null) { + json.append(",\"property\":\"").append(entry.getProperty().getName()).append("\""); + } + json.append(",\"columnPath\":[\"") + .append(String.join("\",\"", entry.getColumnPath())) + .append("\"]"); + if (entry.getDataType() != null) { + json.append(",\"dataType\":\"").append(entry.getDataType()).append("\""); + } + if (entry.getPropertyDatatype() != null) { + json.append(",\"propertyDatatype\":\"").append(entry.getPropertyDatatype()).append("\""); + } + return json.append("}").toString(); + } + + /** + * The sensitive-key and type findings of one table bound to Customer, as the type, the column + * path, and for a type finding the column type and the datatype. Properties listed in {@code + * visible} are the ones the caller may view. + */ + private static List advice( + final Table table, + final OntologyBindingRole role, + final List> key, + final List columns, + final OntologyProperty... visible) { + final BindingRow row = row(table, role, key, columns); + final Map properties = new java.util.HashMap<>(); + for (final OntologyProperty property : visible) { + properties.put(property.getId(), property); + } + return OntologyMappingHealthRules.check( + List.of(new BoundTable(row, CUSTOMER, table)), + new Context( + null, Map.of(CUSTOMER.getId(), new Identity(row, table)), properties, Map.of()), + Progress.start()) + .entries() + .stream() + .filter( + entry -> + entry.getType().value().equals("sensitiveKeyColumn") + || entry.getType().value().equals("columnTypeMismatch")) + .map( + entry -> + entry.getPropertyDatatype() == null + ? entry.getType().value() + " " + entry.getColumnPath() + : entry.getType().value() + + " " + + entry.getColumnPath() + + " " + + entry.getDataType() + + " " + + entry.getPropertyDatatype()) + .toList(); + } + + private static BindingRow row( + final Table table, + final OntologyBindingRole role, + final List> key, + final List columns) { + return new BindingRow( + CUSTOMER.getId(), + table.getId(), + OntologyBindingAssetType.TABLE, + "hash", + columns, + role, + key, + null); + } + + private static OntologyColumnBinding binding( + final OntologyProperty property, final String column) { + return new OntologyColumnBinding() + .withPropertyId(property.getId()) + .withColumnPath(List.of(column)); + } + + private static OntologyProperty dataProperty(final String name, final String... range) { + return property(name, OntologyPropertyKind.DATA) + .withRange(java.util.Arrays.stream(range).map(URI::create).toList()); + } + + private static OntologyProperty property(final String name, final OntologyPropertyKind kind) { + return new OntologyProperty() + .withId(UUID.randomUUID()) + .withName(name) + .withKind(kind) + .withFullyQualifiedName("ontology." + name); + } + + private static Table table(final String name, final Column... columns) { + return new Table() + .withId(UUID.randomUUID()) + .withName(name) + .withFullyQualifiedName("service.sales.public." + name) + .withDatabase(SALES) + .withColumns(List.of(columns)) + .withTags(List.of()); + } + + private static Table tagged(final Table table, final String tag) { + return table.withTags(List.of(new TagLabel().withTagFQN(tag))); + } + + private static Column tagged(final Column column, final String... tags) { + return column.withTags( + java.util.Arrays.stream(tags).map(tag -> new TagLabel().withTagFQN(tag)).toList()); + } + + private static Column column(final String name, final ColumnDataType type) { + return new Column().withName(name).withDataType(type); + } + + private static EntityReference reference(final String type, final String name) { + return new EntityReference().withId(UUID.randomUUID()).withType(type).withName(name); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingHealthRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingHealthRulesTest.java new file mode 100644 index 000000000000..d31d5f166990 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingHealthRulesTest.java @@ -0,0 +1,429 @@ +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.api.data.OntologyMappingHealthEntry; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.BoundTable; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Context; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Identity; +import org.openmetadata.service.ontology.OntologyMappingHealthRules.Progress; + +class OntologyMappingHealthRulesTest { + private static final EntityReference SALES = database("sales"); + private static final EntityReference MARKETING = database("marketing"); + private static final EntityReference CUSTOMER = reference("ontologyConcept", "Customer"); + private static final EntityReference ORDER = reference("ontologyConcept", "Order"); + private static final Table CUSTOMERS = + table( + "customers", + SALES, + column("tenant", ColumnDataType.VARCHAR), + column("id", ColumnDataType.BIGINT)); + private static final Table ADDRESSES = + table( + "addresses", + SALES, + column("tenant_code", ColumnDataType.INT), + column("customer_id", ColumnDataType.INT)); + private static final Table LEADS = table("leads", MARKETING, column("id", ColumnDataType.UUID)); + + @Test + void aClassWithTablesAndNoIdentityTableIsReportedOnceAndEachUnassignedTableOnItsOwn() { + final var page = + check( + List.of( + bound(CUSTOMER, row(CUSTOMER, CUSTOMERS, null, null)), + bound(CUSTOMER, row(CUSTOMER, ADDRESSES, null, null))), + context(null, Map.of()), + Progress.start()); + + assertEquals( + List.of( + "noIdentityTable Customer -", + "unassignedBinding Customer customers", + "unassignedBinding Customer addresses"), + summary(page.entries())); + assertEquals(Set.of(CUSTOMER.getId()), page.progress().settledConcepts()); + } + + @Test + void aClassCheckedOnAnEarlierPageIsNotReportedAgain() { + final var page = + check( + List.of(bound(CUSTOMER, row(CUSTOMER, ADDRESSES, null, null))), + context(null, Map.of()), + new Progress(Set.of(CUSTOMER.getId()), List.of(CUSTOMERS))); + + assertEquals(List.of("unassignedBinding Customer addresses"), summary(page.entries())); + } + + @Test + void anIdentityTableTheCallerCannotViewStillCountsAndIsNeverNamed() { + final var hidden = + new Identity(row(CUSTOMER, CUSTOMERS, OntologyBindingRole.IDENTITY, 2), null); + final var contributing = + row(CUSTOMER, ADDRESSES, OntologyBindingRole.CONTRIBUTING, List.of(List.of("customer_id"))); + + final var page = + check( + List.of(bound(CUSTOMER, contributing)), + context(null, Map.of(CUSTOMER.getId(), hidden)), + Progress.start()); + + assertEquals(List.of(), page.entries()); + } + + @Test + void aContributingKeyOfAnotherLengthIsReportedWithBothLengths() { + final var contributing = + row(CUSTOMER, ADDRESSES, OntologyBindingRole.CONTRIBUTING, List.of(List.of("customer_id"))); + + final var entries = + check(List.of(bound(CUSTOMER, contributing)), context(null, identities()), Progress.start()) + .entries(); + + assertEquals(List.of("keyLengthMismatch Customer addresses"), summary(entries)); + assertEquals(1, entries.getFirst().getKeyLength()); + assertEquals(2, entries.getFirst().getRelatedKeyLength()); + assertEquals(CUSTOMERS.getId(), entries.getFirst().getRelatedAsset().getId()); + } + + @Test + void pairedKeyColumnsOfDifferentKindsAreReportedAndTypesOfOneFamilyAreNot() { + final var contributing = + row( + CUSTOMER, + ADDRESSES, + OntologyBindingRole.CONTRIBUTING, + List.of(List.of("tenant_code"), List.of("customer_id"))); + + final var entries = + check(List.of(bound(CUSTOMER, contributing)), context(null, identities()), Progress.start()) + .entries(); + + assertEquals(List.of("keyTypeMismatch Customer addresses"), summary(entries)); + final var mismatch = entries.getFirst(); + assertEquals(List.of("tenant_code"), mismatch.getColumnPath()); + assertEquals(ColumnDataType.INT, mismatch.getDataType()); + assertEquals(List.of("tenant"), mismatch.getRelatedColumnPath()); + assertEquals(ColumnDataType.VARCHAR, mismatch.getRelatedDataType()); + assertEquals(CUSTOMERS.getId(), mismatch.getRelatedAsset().getId()); + } + + @Test + void aKeyColumnThatNoLongerExistsIsNoTypeFinding() { + final var contributing = + row( + CUSTOMER, + ADDRESSES, + OntologyBindingRole.CONTRIBUTING, + List.of(List.of("dropped"), List.of("customer_id"))); + + assertEquals( + List.of(), + check(List.of(bound(CUSTOMER, contributing)), context(null, identities()), Progress.start()) + .entries()); + } + + @Test + void aRelationColumnWithoutAJoinIsReportedAndAnAttributeColumnIsNot() { + final var placedBy = property("placedBy", OntologyPropertyKind.OBJECT); + final var total = property("total", OntologyPropertyKind.DATA); + final var identity = + row( + ORDER, + ADDRESSES, + OntologyBindingRole.IDENTITY, + List.of(List.of("customer_id")), + binding(placedBy, "customer_id", null), + binding(total, "tenant_code", null)); + + final var entries = + check( + List.of(bound(ORDER, identity)), + new Context( + null, + Map.of(ORDER.getId(), new Identity(identity, ADDRESSES)), + Map.of(placedBy.getId(), placedBy, total.getId(), total), + Map.of()), + Progress.start()) + .entries(); + + assertEquals(List.of("relationColumnWithoutJoin Order addresses"), summary(entries)); + assertEquals(placedBy.getId(), entries.getFirst().getProperty().getId()); + assertEquals(List.of("customer_id"), entries.getFirst().getColumnPath()); + } + + @Test + void anInferredJoinIsReportedUntilItIsConfirmed() { + final var placedBy = property("placedBy", OntologyPropertyKind.OBJECT); + final var inferred = join(OntologyJoinStatus.INFERRED, CUSTOMERS, "customer_id", "id"); + final var confirmed = join(OntologyJoinStatus.CONFIRMED, CUSTOMERS, "customer_id", "id"); + + final var open = joinEntries(placedBy, inferred, Map.of(CUSTOMERS.getId(), CUSTOMERS)); + assertEquals(List.of("joinNotConfirmed Order addresses"), summary(open)); + assertEquals(CUSTOMERS.getId(), open.getFirst().getRelatedAsset().getId()); + assertEquals(placedBy.getId(), open.getFirst().getProperty().getId()); + assertEquals(List.of("customer_id"), open.getFirst().getColumnPath()); + + assertEquals(List.of(), joinEntries(placedBy, confirmed, Map.of(CUSTOMERS.getId(), CUSTOMERS))); + + final var hiddenTarget = joinEntries(placedBy, inferred, Map.of()); + assertEquals(List.of("joinNotConfirmed Order addresses"), summary(hiddenTarget)); + assertNull(hiddenTarget.getFirst().getRelatedAsset()); + } + + @Test + void joinColumnsOfDifferentKindsAreReported() { + final var placedBy = property("placedBy", OntologyPropertyKind.OBJECT); + final var join = join(OntologyJoinStatus.CONFIRMED, CUSTOMERS, "customer_id", "tenant"); + + final var entries = joinEntries(placedBy, join, Map.of(CUSTOMERS.getId(), CUSTOMERS)); + + assertEquals(List.of("joinTypeMismatch Order addresses"), summary(entries)); + final var mismatch = entries.getFirst(); + assertEquals(List.of("customer_id"), mismatch.getColumnPath()); + assertEquals(ColumnDataType.INT, mismatch.getDataType()); + assertEquals(List.of("tenant"), mismatch.getRelatedColumnPath()); + assertEquals(ColumnDataType.VARCHAR, mismatch.getRelatedDataType()); + assertEquals(CUSTOMERS.getId(), mismatch.getRelatedAsset().getId()); + assertEquals(placedBy.getId(), mismatch.getProperty().getId()); + } + + @Test + void aTableOutsideTheMappingSourceIsReportedWithItsDatabase() { + final var page = + check( + List.of( + bound(CUSTOMER, row(CUSTOMER, CUSTOMERS, OntologyBindingRole.IDENTITY, 2)), + bound(ORDER, row(ORDER, LEADS, OntologyBindingRole.IDENTITY, 1))), + context(SALES, bothIdentities()), + Progress.start()); + + assertEquals(List.of("outsideMappingSource Order leads"), summary(page.entries())); + assertEquals(List.of(MARKETING), page.entries().getFirst().getDatabases()); + } + + @Test + void withoutAMappingSourceTablesInTwoDatabasesAreReportedWithBothDatabases() { + final var page = + check( + List.of( + bound(CUSTOMER, row(CUSTOMER, CUSTOMERS, OntologyBindingRole.IDENTITY, 2)), + bound(ORDER, row(ORDER, LEADS, OntologyBindingRole.IDENTITY, 1))), + context(null, bothIdentities()), + Progress.start()); + + assertEquals(List.of("multipleDatabases - -"), summary(page.entries())); + assertEquals(List.of(SALES, MARKETING), page.entries().getFirst().getDatabases()); + assertEquals(List.of(CUSTOMERS, LEADS), page.progress().databaseWitnesses()); + } + + @Test + void aDatabaseFirstFoundOnALaterPageIsReportedWithTheOnesFoundBefore() { + final var leads = List.of(bound(ORDER, row(ORDER, LEADS, OntologyBindingRole.IDENTITY, 1))); + final var identities = + Map.of( + ORDER.getId(), new Identity(row(ORDER, LEADS, OntologyBindingRole.IDENTITY, 1), LEADS)); + + final var second = + check(leads, context(null, identities), new Progress(Set.of(), List.of(CUSTOMERS))); + assertEquals(List.of("multipleDatabases - -"), summary(second.entries())); + assertEquals(List.of(SALES, MARKETING), second.entries().getFirst().getDatabases()); + + final var third = + check(leads, context(null, identities), new Progress(Set.of(), List.of(CUSTOMERS, LEADS))); + assertEquals(List.of(), third.entries()); + + final var single = check(leads, context(null, identities), Progress.start()); + assertEquals(List.of(), single.entries()); + } + + @Test + void typesOfOneFamilyPairAndOtherTypesPairOnlyWithThemselves() { + assertTrue(OntologyMappingHealthRules.sameFamily(ColumnDataType.INT, ColumnDataType.BIGINT)); + assertTrue(OntologyMappingHealthRules.sameFamily(ColumnDataType.DECIMAL, ColumnDataType.INT)); + assertTrue(OntologyMappingHealthRules.sameFamily(ColumnDataType.VARCHAR, ColumnDataType.TEXT)); + assertTrue( + OntologyMappingHealthRules.sameFamily(ColumnDataType.TIMESTAMP, ColumnDataType.DATETIME)); + assertTrue(OntologyMappingHealthRules.sameFamily(ColumnDataType.UUID, ColumnDataType.UUID)); + assertFalse(OntologyMappingHealthRules.sameFamily(ColumnDataType.INT, ColumnDataType.VARCHAR)); + assertFalse(OntologyMappingHealthRules.sameFamily(ColumnDataType.UUID, ColumnDataType.STRING)); + assertFalse( + OntologyMappingHealthRules.sameFamily(ColumnDataType.DATE, ColumnDataType.TIMESTAMP)); + assertFalse(OntologyMappingHealthRules.sameFamily(ColumnDataType.BOOLEAN, ColumnDataType.INT)); + } + + private static OntologyMappingHealthRules.Page check( + final List tables, final Context context, final Progress earlier) { + return OntologyMappingHealthRules.check(tables, context, earlier); + } + + /** The findings for an Order class whose identity table carries one relation column. */ + private static List joinEntries( + final OntologyProperty property, + final OntologyColumnJoin join, + final Map joinTargets) { + final var identity = + row( + ORDER, + ADDRESSES, + OntologyBindingRole.IDENTITY, + List.of(List.of("customer_id")), + binding(property, "customer_id", join)); + return check( + List.of(bound(ORDER, identity)), + new Context( + null, + Map.of(ORDER.getId(), new Identity(identity, ADDRESSES)), + Map.of(property.getId(), property), + joinTargets), + Progress.start()) + .entries(); + } + + /** The Customer class with `customers` as its identity table, keyed by tenant then id. */ + private static Map identities() { + return Map.of( + CUSTOMER.getId(), + new Identity(row(CUSTOMER, CUSTOMERS, OntologyBindingRole.IDENTITY, 2), CUSTOMERS)); + } + + /** Customer with `customers` and Order with `leads`, each as its class's identity table. */ + private static Map bothIdentities() { + return Map.of( + CUSTOMER.getId(), + new Identity(row(CUSTOMER, CUSTOMERS, OntologyBindingRole.IDENTITY, 2), CUSTOMERS), + ORDER.getId(), + new Identity(row(ORDER, LEADS, OntologyBindingRole.IDENTITY, 1), LEADS)); + } + + private static Context context( + final EntityReference mappingSource, final Map identities) { + return new Context(mappingSource, identities, Map.of(), Map.of()); + } + + private static List summary(final List entries) { + return entries.stream() + .map( + entry -> + "%s %s %s" + .formatted( + entry.getType().value(), + entry.getConcept() == null ? "-" : entry.getConcept().getName(), + entry.getAsset() == null ? "-" : entry.getAsset().getName())) + .toList(); + } + + private static BoundTable bound(final EntityReference concept, final BindingRow row) { + final Table table = + List.of(CUSTOMERS, ADDRESSES, LEADS).stream() + .filter(candidate -> candidate.getId().equals(row.assetId())) + .findFirst() + .orElseThrow(); + return new BoundTable(row, concept, table); + } + + /** A row whose key is the first {@code keyColumns} columns of the table, in column order. */ + private static BindingRow row( + final EntityReference concept, + final Table table, + final OntologyBindingRole role, + final int keyColumns) { + return row( + concept, + table, + role, + table.getColumns().stream() + .limit(keyColumns) + .map(column -> List.of(column.getName())) + .toList()); + } + + private static BindingRow row( + final EntityReference concept, + final Table table, + final OntologyBindingRole role, + final List> key, + final OntologyColumnBinding... columns) { + return new BindingRow( + concept.getId(), + table.getId(), + OntologyBindingAssetType.TABLE, + "hash", + List.of(columns), + role, + key, + null); + } + + private static OntologyColumnBinding binding( + final OntologyProperty property, final String column, final OntologyColumnJoin join) { + return new OntologyColumnBinding() + .withPropertyId(property.getId()) + .withColumnPath(List.of(column)) + .withJoin(join); + } + + private static OntologyColumnJoin join( + final OntologyJoinStatus status, + final Table target, + final String child, + final String parent) { + return new OntologyColumnJoin() + .withTargetAssetId(target.getId()) + .withStatus(status) + .withOn( + List.of( + new OntologyJoinColumnPair() + .withChild(List.of(child)) + .withParent(List.of(parent)))); + } + + private static OntologyProperty property(final String name, final OntologyPropertyKind kind) { + return new OntologyProperty().withId(UUID.randomUUID()).withName(name).withKind(kind); + } + + private static Table table( + final String name, final EntityReference database, final Column... columns) { + return new Table() + .withId(UUID.randomUUID()) + .withName(name) + .withFullyQualifiedName("service." + database.getName() + ".public." + name) + .withDatabase(database) + .withColumns(List.of(columns)); + } + + private static Column column(final String name, final ColumnDataType type) { + return new Column().withName(name).withDataType(type); + } + + private static EntityReference database(final String name) { + return reference("database", name); + } + + private static EntityReference reference(final String type, final String name) { + return new EntityReference().withId(UUID.randomUUID()).withType(type).withName(name); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingReaderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingReaderTest.java new file mode 100644 index 000000000000..8ea43b10f01d --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingReaderTest.java @@ -0,0 +1,238 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import jakarta.ws.rs.ClientErrorException; +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.LiveAsset; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.ontology.OntologyMappingReader.Bindings; +import org.openmetadata.service.ontology.OntologyMappingReader.SearchStart.IdentityTable; +import org.openmetadata.service.ontology.OntologyMappingReader.SearchStart.OnlyTable; +import org.openmetadata.service.ontology.OntologyMappingReader.Tables; + +/** + * The binding rows a statement is built from, and the binding revisions that a plan reports for + * them. + */ +class OntologyMappingReaderTest { + private static final UUID CUSTOMER = UUID.fromString("00000000-0000-0000-0000-00000000000c"); + private static final URI CUSTOMER_IRI = URI.create("https://example.org/shop#Customer"); + private final OntologyConceptBindingStore store = mock(OntologyConceptBindingStore.class); + private final OntologyMappingReader reader = new OntologyMappingReader(store, null); + + @Test + void aPlanReportsTheRevisionItsRowsWereReadUnder() { + final BindingRow customers = row(1, OntologyBindingRole.IDENTITY); + final BindingRow addresses = row(2, OntologyBindingRole.CONTRIBUTING); + when(store.revisions(anyCollection())).thenReturn(Map.of(CUSTOMER, 4L)); + when(store.identityRows(anyCollection())).thenReturn(List.of(customers)); + when(store.contributingRows(CUSTOMER, 33)).thenReturn(List.of(addresses)); + + final Bindings read = reader.bindings(List.of(CUSTOMER), List.of(CUSTOMER)); + + assertEquals(Map.of(CUSTOMER, 4L), read.revisions()); + assertEquals(Map.of(CUSTOMER, customers), read.identity()); + assertEquals(Map.of(CUSTOMER, List.of(addresses)), read.contributing()); + assertEquals(List.of(customers, addresses), read.rows()); + } + + @Test + void aBindingWriteThatLandsWhileTheRowsAreReadMakesTheReaderReadThemAgain() { + final BindingRow before = row(1, OntologyBindingRole.IDENTITY); + final BindingRow after = row(2, OntologyBindingRole.IDENTITY); + when(store.revisions(anyCollection())) + .thenReturn(Map.of(CUSTOMER, 4L), Map.of(CUSTOMER, 5L), Map.of(CUSTOMER, 5L)); + when(store.identityRows(anyCollection())).thenReturn(List.of(before), List.of(after)); + + final Bindings read = reader.bindings(List.of(CUSTOMER), List.of()); + + assertEquals(Map.of(CUSTOMER, 5L), read.revisions()); + assertEquals(Map.of(CUSTOMER, after), read.identity()); + } + + @Test + void bindingsThatChangeOnEveryReadGiveNoStatement() { + when(store.revisions(anyCollection())) + .thenReturn( + Map.of(CUSTOMER, 1L), + Map.of(CUSTOMER, 2L), + Map.of(CUSTOMER, 3L), + Map.of(CUSTOMER, 4L), + Map.of(CUSTOMER, 5L), + Map.of(CUSTOMER, 6L)); + when(store.identityRows(anyCollection())).thenReturn(List.of()); + + final ClientErrorException refused = + assertThrows( + ClientErrorException.class, () -> reader.bindings(List.of(CUSTOMER), List.of())); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "The table bindings changed while the statement was built. Ask again", + refused.getMessage()); + } + + @Test + void aClassThatBindsMoreContributingTablesThanAStatementReadsGivesNoStatement() { + final List rows = + IntStream.rangeClosed(1, 33) + .mapToObj(table -> row(table, OntologyBindingRole.CONTRIBUTING)) + .toList(); + final Tables tables = + new Tables(Set.copyOf(rows.stream().map(BindingRow::assetId).toList()), Map.of()); + + final ClientErrorException refused = + assertThrows( + ClientErrorException.class, + () -> OntologyMappingReader.contributing(CUSTOMER_IRI, rows, tables)); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "Class https://example.org/shop#Customer binds more than 32 contributing tables", + refused.getMessage()); + assertEquals( + rows.subList(0, 32), + OntologyMappingReader.contributing(CUSTOMER_IRI, rows.subList(0, 32), tables)); + } + + @Test + void aContributingTableThatNoLongerExistsIsLeftOut() { + final BindingRow kept = row(1, OntologyBindingRole.CONTRIBUTING); + final BindingRow gone = row(2, OntologyBindingRole.CONTRIBUTING); + + assertEquals( + List.of(kept), + OntologyMappingReader.contributing( + CUSTOMER_IRI, List.of(kept, gone), new Tables(Set.of(kept.assetId()), Map.of()))); + } + + @Test + void aClassThatBindsNoTableHasNoTableToStartItsSearchFrom() { + bound(); + + assertEquals(new OnlyTable(List.of()), reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + } + + @Test + void aClassWithOneTableBindingStartsItsSearchFromThatTableWhateverItsRole() { + final BindingRow withoutRole = row(1, null); + final BindingRow contributing = row(2, OntologyBindingRole.CONTRIBUTING); + final BindingRow identity = row(3, OntologyBindingRole.IDENTITY); + + bound(withoutRole); + assertEquals(new OnlyTable(List.of(withoutRole)), reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + bound(contributing); + assertEquals(new OnlyTable(List.of(contributing)), reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + bound(identity); + assertEquals(new OnlyTable(List.of(identity)), reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + } + + @Test + void aBindingWhoseTableNoLongerExistsIsNoTableBindingOfItsClass() { + final BindingRow gone = row(1, null); + final BindingRow kept = row(2, null); + bound(gone, kept); + deleted(gone); + + assertEquals(new OnlyTable(List.of(kept)), reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + } + + @Test + void aClassWithSeveralTableBindingsStartsItsSearchFromItsIdentityTable() { + final BindingRow identity = row(3, OntologyBindingRole.IDENTITY); + bound(row(1, null), row(2, OntologyBindingRole.CONTRIBUTING), identity); + + assertEquals(new IdentityTable(identity), reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + } + + @Test + void aClassWithSeveralTableBindingsAndNoIdentityTableGivesNoSearchStatement() { + bound(row(1, null), row(2, OntologyBindingRole.CONTRIBUTING)); + + assertAsksForTheIdentityTable(); + } + + @Test + void anIdentityBindingWhoseTableNoLongerExistsIsNoIdentityTableOfItsClass() { + final BindingRow identity = row(3, OntologyBindingRole.IDENTITY); + bound(row(1, null), row(2, OntologyBindingRole.CONTRIBUTING), identity); + deleted(identity); + + assertAsksForTheIdentityTable(); + } + + private void assertAsksForTheIdentityTable() { + final ClientErrorException refused = + assertThrows(ClientErrorException.class, () -> reader.searchStart(CUSTOMER, CUSTOMER_IRI)); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "Class https://example.org/shop#Customer binds several tables and none is its identity" + + " table. Pick its identity table", + refused.getMessage()); + } + + /** Makes these rows the table bindings of the class, each over a table that exists. */ + private void bound(final BindingRow... rows) { + when(store.firstTables(List.of(CUSTOMER), 100)).thenReturn(List.of(rows)); + when(store.identityRows(anyCollection())) + .thenReturn( + Stream.of(rows).filter(row -> row.role() == OntologyBindingRole.IDENTITY).toList()); + deleted(); + } + + /** Makes the store answer that every table exists except the tables of these rows. */ + private void deleted(final BindingRow... gone) { + final Set missing = Stream.of(gone).map(BindingRow::assetId).collect(Collectors.toSet()); + when(store.liveAssets(anyList())) + .thenAnswer( + call -> + call.>getArgument(0).stream() + .filter(row -> !missing.contains(row.assetId())) + .collect( + Collectors.toMap( + BindingRow::assetId, row -> new LiveAsset(row.assetId(), "Postgres")))); + } + + private static BindingRow row(final int table, final OntologyBindingRole role) { + return new BindingRow( + CUSTOMER, + new UUID(0, table), + OntologyBindingAssetType.TABLE, + "hash" + table, + List.of(), + role, + List.of(List.of("id")), + null); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapeModel.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapeModel.java new file mode 100644 index 000000000000..c17ee73e5895 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapeModel.java @@ -0,0 +1,281 @@ +/* + * 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.ontology; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.api.data.OntologyStatementMeasure; +import org.openmetadata.schema.api.services.CreateDatabaseService.DatabaseServiceType; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.RecordStatement; +import org.openmetadata.service.ontology.OntologyMappingReader.Bindings; +import org.openmetadata.service.ontology.OntologyMappingReader.Tables; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.PropertySpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyMappingShapes.TableSpec; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedClass; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyRelationPath.End; +import org.openmetadata.service.ontology.OntologyRelationPath.Ends; + +/** + * One mapping shape as the generator reads it: its tables on a service of one type, its binding + * rows and its properties. A test hides a table or removes it to see what the generator does then. + */ +final class OntologyMappingShapeModel { + static final String SCHEMA = "warehouse.sales." + OntologyMappingShapes.GOLDEN_SCHEMA; + private final Shape shape; + private final String serviceType; + private final Set hidden = new HashSet<>(); + private final Set deleted = new HashSet<>(); + private final Set omitted = new HashSet<>(); + private final Map tables = new HashMap<>(); + private final List bindings; + + OntologyMappingShapeModel(final Shape shape, final String serviceType) { + this(shape, serviceType, shape.bindings()); + } + + /** The shape with other bindings than its own, to see what a changed mapping gives. */ + OntologyMappingShapeModel( + final Shape shape, final String serviceType, final List bindings) { + this.shape = shape; + this.serviceType = serviceType; + this.bindings = bindings; + } + + /** The reader may not view the table. */ + OntologyMappingShapeModel hide(final String table) { + hidden.add(table); + return this; + } + + /** The table no longer exists, though a binding row still names it. */ + OntologyMappingShapeModel delete(final String table) { + deleted.add(table); + return this; + } + + /** The version the statement reads lacks the property, or the reader may not view it. */ + OntologyMappingShapeModel omit(final String property) { + omitted.add(property); + return this; + } + + /** The table as the catalog holds it. A test changes its columns to see what follows. */ + Table table(final String name) { + return tables.computeIfAbsent(name, this::newTable); + } + + UUID id(final String term) { + return UUID.nameUUIDFromBytes((shape.name() + "/" + term).getBytes(StandardCharsets.UTF_8)); + } + + URI iri(final String term) { + return shape.iri(term); + } + + /** The statement as a person reads it. */ + static String sql(final RecordStatement statement) { + return statement.family().finish(statement.text()).sql(); + } + + /** The column plan of a statement, one line for each result column. */ + static List plan(final RecordStatement statement) { + return OntologyMappingShapes.columnPlan(statement.columns()); + } + + /** The names of the tables a statement reads, in join order. */ + static List read(final RecordStatement statement) { + return statement.read().stream().map(table -> table.table().getName()).toList(); + } + + RecordStatement statement(final Ask ask) { + return switch (ask.kind()) { + case FIND -> OntologyConceptSqlGenerator.find(mapped(ask.type()), ask.matchText()); + case OPEN -> OntologyConceptSqlGenerator.open( + mapped(ask.type()), contributing(ask.type()), ask.key()); + case EXPAND -> OntologyConceptSqlGenerator.expand( + path(ask.type(), ask.relation(), ask.direction()), ask.key(), ask.after()); + case AGGREGATE -> aggregate(ask); + }; + } + + private RecordStatement aggregate(final Ask ask) { + if (ask.relation() == null) { + return OntologyConceptSqlGenerator.count(mapped(ask.type())); + } + final OntologyRelationPath path = path(ask.type(), ask.relation(), ask.direction()); + return ask.measure() == OntologyStatementMeasure.LINK_COUNT + ? OntologyConceptSqlGenerator.links(path) + : OntologyConceptSqlGenerator.top(path); + } + + MappedClass mapped(final String type) { + return new MappedClass( + id(type), + iri(type), + OntologyMappingReader.identity(iri(type), bindings().identity().get(id(type)), catalog()), + properties()); + } + + /** The contributing tables of a class that exist and that the reader may view. */ + List contributing(final String type) { + final Tables catalog = catalog(); + return OntologyMappingReader.contributing( + iri(type), bindings().contributing().get(id(type)), catalog) + .stream() + .filter(catalog::shows) + .map(catalog::mapped) + .toList(); + } + + OntologyRelationPath path( + final String type, final String relation, final OntologyStatementDirection direction) { + final PropertySpec spec = shape.property(relation); + final boolean forward = direction == OntologyStatementDirection.FORWARD; + final String related = forward ? spec.range() : spec.domain(); + final MappedClass start = mapped(type); + final MappedClass end = mapped(related); + final Ends ends = + new Ends( + id(relation), + iri(relation), + new End(id(spec.domain()), iri(spec.domain())), + new End(id(spec.range()), iri(spec.range()))); + return OntologyRelationPath.of( + properties().get(id(relation)), + direction, + start, + end, + OntologyMappingReader.join(ends, bindings(), catalog())); + } + + Bindings bindings() { + final Map identity = new HashMap<>(); + final Map> contributing = new HashMap<>(); + shape.classes().forEach(type -> contributing.put(id(type), new ArrayList<>())); + for (final BindingSpec spec : bindings) { + if (spec.role() == OntologyBindingRole.IDENTITY) { + identity.put(id(spec.type()), row(spec)); + } else { + contributing.get(id(spec.type())).add(row(spec)); + } + } + return new Bindings(Map.of(), identity, contributing); + } + + Tables catalog() { + final Map> viewable = new HashMap<>(); + final Set live = new HashSet<>(); + for (final TableSpec spec : shape.tables()) { + if (!deleted.contains(spec.name())) { + live.add(id(spec.name())); + } + if (!deleted.contains(spec.name()) && !hidden.contains(spec.name())) { + viewable.put(id(spec.name()), table(spec.name())); + } + } + return new Tables(live, viewable); + } + + Map properties() { + return shape.properties().stream() + .filter(spec -> !omitted.contains(spec.name())) + .map( + spec -> + new OntologyProperty() + .withId(id(spec.name())) + .withName(spec.name()) + .withIri(iri(spec.name())) + .withKind(spec.kind()) + .withIsDisplayName(spec.displayName())) + .collect(Collectors.toMap(OntologyProperty::getId, Function.identity())); + } + + private Table newTable(final String name) { + return new Table() + .withId(id(name)) + .withName(name) + .withFullyQualifiedName(SCHEMA + "." + name) + .withServiceType(DatabaseServiceType.fromValue(serviceType)) + .withColumns( + new ArrayList<>( + shape.table(name).columns().stream() + .map(column -> new Column().withName(column.name()).withDataType(column.type())) + .toList())); + } + + private BindingRow row(final BindingSpec spec) { + return new BindingRow( + id(spec.type()), + id(spec.table()), + OntologyBindingAssetType.TABLE, + spec.table(), + spec.columns().stream().map(this::column).toList(), + spec.role(), + spec.key().stream().map(List::of).toList(), + spec.filter() == null + ? null + : new OntologyRowFilter() + .withColumn(List.of(spec.filter().column())) + .withOperator(spec.filter().operator()) + .withValue(spec.filter().value())); + } + + private OntologyColumnBinding column(final ColumnBindingSpec spec) { + final OntologyColumnBinding binding = + new OntologyColumnBinding() + .withPropertyId(id(spec.property())) + .withColumnPath(List.of(spec.column())); + return spec.join() == null + ? binding + : binding.withJoin( + new OntologyColumnJoin() + .withTargetAssetId(id(spec.join().target())) + .withStatus(spec.join().status()) + .withOn( + IntStream.range(0, spec.join().child().size()) + .mapToObj( + pair -> + new OntologyJoinColumnPair() + .withChild(List.of(spec.join().child().get(pair))) + .withParent(List.of(spec.join().parent().get(pair)))) + .toList())); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java new file mode 100644 index 000000000000..479c3515dbb0 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyMappingShapes.java @@ -0,0 +1,1113 @@ +/* + * 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.ontology; + +import java.math.BigDecimal; +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import org.openmetadata.schema.api.data.OntologyStatementColumn; +import org.openmetadata.schema.api.data.OntologyStatementDirection; +import org.openmetadata.schema.api.data.OntologyStatementKind; +import org.openmetadata.schema.api.data.OntologyStatementMeasure; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilterOperator; + +/** + * Seven small mappings, one for each shape that the table bindings of a class take. Each names its + * tables with their rows, its classes, its properties, its bindings, and the statements to ask of + * it with the rows each one returns when the tables hold exactly those rows. + * + *

    The shapes are data only. A unit test turns one into the model the generator reads, and an + * integration test creates it through the API over real tables. + */ +public final class OntologyMappingShapes { + /** The schema that every golden statement names, which holds the tables of every shape. */ + public static final String GOLDEN_SCHEMA = "shop"; + + /** The directory under the test resources that holds the golden statements. */ + public static final String GOLDEN_STATEMENTS = "ontology/statements"; + + private OntologyMappingShapes() {} + + /** + * A column plan as text, one line for each result column: its index, its kind, the class it + * describes, then its key part or its property. Each term is named by the fragment of its IRI. + */ + public static List columnPlan(final List columns) { + return columns.stream() + .map( + column -> + String.join( + " ", + Stream.of( + column.getIndex().toString(), + column.getKind().value(), + column.getClassIri().getFragment(), + column.getKeyPart() == null ? null : "part " + column.getKeyPart(), + column.getPropertyIri() == null + ? null + : column.getPropertyIri().getFragment()) + .filter(Objects::nonNull) + .toList())) + .toList(); + } + + public record ColumnSpec(String name, ColumnDataType type) {} + + /** A table with the rows it holds, each row in column order. A null is a SQL null. */ + public record TableSpec(String name, List columns, List> rows) {} + + /** + * @param domain the class that the property describes + * @param range for a relation, the class it reaches, and null for a data property + */ + public record PropertySpec(String name, boolean displayName, String domain, String range) { + public OntologyPropertyKind kind() { + return range == null ? OntologyPropertyKind.DATA : OntologyPropertyKind.OBJECT; + } + } + + /** + * @param child the join columns of the table that holds the relation, in pair order + * @param parent the columns of the target table that they equal + */ + public record JoinSpec( + String target, OntologyJoinStatus status, List child, List parent) {} + + /** @param join the join of a relation column, and null for a data column */ + public record ColumnBindingSpec(String property, String column, JoinSpec join) {} + + public record FilterSpec(String column, OntologyRowFilterOperator operator, Object value) {} + + /** @param filter the row filter, or null */ + public record BindingSpec( + String type, + String table, + OntologyBindingRole role, + List key, + FilterSpec filter, + List columns) {} + + /** + * One statement to ask of a shape. + * + * @param name what the statement is called in a file name + * @param type the class the request is made on + * @param matchText for find, the text to match, or null + * @param key for open and expand, the key of the record + * @param after for expand, the key of the last related record already held, or null + * @param relation for expand and a relation aggregate, the relation to follow + * @param columns what each result column holds, one line for each as {@link #columnPlan} writes + * it + * @param rows the rows the statement can return, each value as text. It returns all of them, or + * as many as its row limit when there are more. The rows of a relation aggregate and of an + * expand come in a fixed order, the expand rows in the key order of the related class + * @param measure for an aggregate over a relation, what it counts, or null for the default + */ + public record Ask( + String name, + OntologyStatementKind kind, + String type, + String matchText, + List key, + String relation, + OntologyStatementDirection direction, + List columns, + List> rows, + OntologyStatementMeasure measure, + List after) { + /** An ask that names no measure and no key to start after. */ + public Ask( + final String name, + final OntologyStatementKind kind, + final String type, + final String matchText, + final List key, + final String relation, + final OntologyStatementDirection direction, + final List columns, + final List> rows) { + this(name, kind, type, matchText, key, relation, direction, columns, rows, null, null); + } + + /** An ask that names no key to start after. */ + public Ask( + final String name, + final OntologyStatementKind kind, + final String type, + final String matchText, + final List key, + final String relation, + final OntologyStatementDirection direction, + final List columns, + final List> rows, + final OntologyStatementMeasure measure) { + this(name, kind, type, matchText, key, relation, direction, columns, rows, measure, null); + } + + /** The same ask with another measure. */ + public Ask withMeasure(final OntologyStatementMeasure counted) { + return new Ask( + name, kind, type, matchText, key, relation, direction, columns, rows, counted, after); + } + + /** The same ask about another record. */ + public Ask withKey(final List record) { + return new Ask( + name, kind, type, matchText, record, relation, direction, columns, rows, measure, after); + } + + /** The same ask that starts after another key. */ + public Ask withAfter(final List last) { + return new Ask( + name, kind, type, matchText, key, relation, direction, columns, rows, measure, last); + } + } + + public record Shape( + String name, + List tables, + List classes, + List properties, + List bindings, + List asks) { + public URI iri(final String term) { + return URI.create("https://example.org/" + name + "#" + term); + } + + public TableSpec table(final String tableName) { + return tables.stream() + .filter(table -> table.name().equals(tableName)) + .findFirst() + .orElseThrow(); + } + + public PropertySpec property(final String propertyName) { + return properties.stream() + .filter(property -> property.name().equals(propertyName)) + .findFirst() + .orElseThrow(); + } + + /** The binding of {@code tableName} to the class {@code type}. */ + public BindingSpec binding(final String type, final String tableName) { + return bindings.stream() + .filter(binding -> binding.type().equals(type) && binding.table().equals(tableName)) + .findFirst() + .orElseThrow(); + } + + public Ask ask(final String askName) { + return asks.stream().filter(ask -> ask.name().equals(askName)).findFirst().orElseThrow(); + } + + /** + * The test resource that holds one statement of this shape as one engine family writes it. + * + * @param family the engine family in lowercase, such as {@code postgres} + */ + public String golden(final String family, final Ask ask) { + return String.format("%s/%s/%s-%s.sql", GOLDEN_STATEMENTS, family, name, ask.name()); + } + } + + private static final List CUSTOMER_WITH_EMAIL = + columns( + "key Customer part 0", + "displayName Customer customerName", + "property Customer customerEmail"); + + /** + * 1. An identity table with a one-column key and no row filter. It binds the display name after + * another column, and a statement still lists the display name first. + */ + public static final Shape UNFILTERED_IDENTITY = + new Shape( + "unfilteredIdentity", + List.of( + table( + "customers", + List.of(integer("id"), text("name"), text("email")), + row(1, "Ada Lovelace", "ada@example.org"), + row(2, "Grace Hopper", "grace@example.org"), + row(3, "alan turing", null), + row(null, "No Key", "nokey@example.org"))), + List.of("Customer"), + List.of(data("customerName", true, "Customer"), data("customerEmail", false, "Customer")), + List.of( + identity( + "Customer", + "customers", + List.of("id"), + null, + bound("customerEmail", "email"), + bound("customerName", "name"))), + List.of( + find( + "find", + "Customer", + null, + CUSTOMER_WITH_EMAIL, + texts("1", "Ada Lovelace", "ada@example.org"), + texts("2", "Grace Hopper", "grace@example.org"), + texts("3", "alan turing", null)), + find( + "find-match", + "Customer", + "hopper", + CUSTOMER_WITH_EMAIL, + texts("2", "Grace Hopper", "grace@example.org")), + open( + "open", + "Customer", + List.of(2), + CUSTOMER_WITH_EMAIL, + texts("2", "Grace Hopper", "grace@example.org")), + count("count", "Customer", 3))); + + private static final List PERSON = + columns("key Person part 0", "displayName Person personName"); + + /** 2. Two classes that bind one table as their identity table, each with its own row filter. */ + public static final Shape FILTERED_IDENTITY = + new Shape( + "filteredIdentity", + List.of( + table( + "parties", + List.of(integer("id"), text("kind"), text("name")), + row(1, "person", "Ada Lovelace"), + row(2, "organization", "Acme"), + row(3, "person", "Grace Hopper"), + row(4, "organization", "Globex"), + row(5, "vendor", "Initech"))), + List.of("Person", "Organization"), + List.of( + data("personName", true, "Person"), data("organizationName", true, "Organization")), + List.of( + identity( + "Person", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "person"), + bound("personName", "name")), + identity( + "Organization", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "organization"), + bound("organizationName", "name"))), + List.of( + find( + "person-find", + "Person", + null, + PERSON, + texts("1", "Ada Lovelace"), + texts("3", "Grace Hopper")), + find("person-find-match", "Person", "ada", PERSON, texts("1", "Ada Lovelace")), + open("person-open", "Person", List.of(3), PERSON, texts("3", "Grace Hopper")), + count("person-count", "Person", 2), + find( + "organization-find", + "Organization", + null, + columns("key Organization part 0", "displayName Organization organizationName"), + texts("2", "Acme"), + texts("4", "Globex")), + count("organization-count", "Organization", 2))); + + private static final List ACCOUNT = + columns("key Account part 0", "key Account part 1", "displayName Account accountName"); + + /** 3. A two-column key, with a contributing table whose key pairs with it by position. */ + public static final Shape COMPOSITE_KEY = + new Shape( + "compositeKey", + List.of( + table( + "crm_customers", + List.of(text("tenant_id"), integer("customer_id"), text("name")), + row("eu", 42, "Northwind"), + row("us", 42, "Contoso"), + row("eu", 7, "Fabrikam"), + row("eu", null, "Half Key")), + table( + "crm_customer_profile", + List.of(text("tenant"), integer("customer"), text("tier")), + row("eu", 42, "gold"), + row("us", 42, "silver"))), + List.of("Account"), + List.of(data("accountName", true, "Account"), data("accountTier", false, "Account")), + List.of( + identity( + "Account", + "crm_customers", + List.of("tenant_id", "customer_id"), + null, + bound("accountName", "name")), + contributing( + "Account", + "crm_customer_profile", + List.of("tenant", "customer"), + bound("accountTier", "tier"))), + List.of( + find( + "find", + "Account", + null, + ACCOUNT, + texts("eu", "42", "Northwind"), + texts("us", "42", "Contoso"), + texts("eu", "7", "Fabrikam")), + find("find-match", "Account", "north", ACCOUNT, texts("eu", "42", "Northwind")), + open( + "open", + "Account", + List.of("eu", 42), + columns( + "key Account part 0", + "key Account part 1", + "displayName Account accountName", + "property Account accountTier"), + texts("eu", "42", "Northwind", "gold")), + count("count", "Account", 3))); + + private static final List CUSTOMER = + columns("key Customer part 0", "displayName Customer customerName"); + + /** 4. A contributing table that holds several rows for one key. */ + public static final Shape REPEATED_CONTRIBUTION = + new Shape( + "repeatedContribution", + List.of( + table( + "customers", + List.of(integer("id"), text("name")), + row(1, "Ada Lovelace"), + row(2, "Grace Hopper")), + table( + "customer_addresses", + List.of(integer("customer_id"), text("city"), text("country")), + row(1, "London", "UK"), + row(1, "Paris", "FR"), + row(1, "Turin", "IT"), + row(2, "New York", "US"))), + List.of("Customer"), + List.of( + data("customerName", true, "Customer"), + data("addressCity", false, "Customer"), + data("addressCountry", false, "Customer")), + List.of( + identity("Customer", "customers", List.of("id"), null, bound("customerName", "name")), + contributing( + "Customer", + "customer_addresses", + List.of("customer_id"), + bound("addressCity", "city"), + bound("addressCountry", "country"))), + List.of( + find( + "find", + "Customer", + null, + CUSTOMER, + texts("1", "Ada Lovelace"), + texts("2", "Grace Hopper")), + find("find-match", "Customer", "grace", CUSTOMER, texts("2", "Grace Hopper")), + open( + "open", + "Customer", + List.of(1), + columns( + "key Customer part 0", + "displayName Customer customerName", + "property Customer addressCity", + "property Customer addressCountry"), + texts("1", "Ada Lovelace", "London", "UK"), + texts("1", "Ada Lovelace", "Paris", "FR"), + texts("1", "Ada Lovelace", "Turin", "IT")), + count("count", "Customer", 2))); + + /** The orders of the first customer of {@link #COLUMN_RELATION}: more than one page holds. */ + public static final int ORDERS_OF_FIRST_CUSTOMER = 30; + + private static final List ORDER_WITH_TOTAL = + columns("key Order part 0", "property Order orderTotal"); + private static final List CUSTOMER_THEN_ORDER = + columns("key Customer part 0", "key Order part 0"); + + /** 5. A relation held in one column of the table of the class that binds it. */ + public static final Shape COLUMN_RELATION = + new Shape( + "columnRelation", + List.of( + table( + "customers", + List.of(integer("id"), text("name")), + row(1, "Ada Lovelace"), + row(2, "Grace Hopper"), + row(3, "Alan Turing")), + new TableSpec( + "orders", + List.of(integer("id"), integer("customer_id"), decimal("total")), + orders())), + List.of("Order", "Customer"), + List.of( + data("customerName", true, "Customer"), + data("orderTotal", false, "Order"), + relation("placedBy", "Order", "Customer")), + List.of( + identity("Customer", "customers", List.of("id"), null, bound("customerName", "name")), + identity( + "Order", + "orders", + List.of("id"), + null, + bound("orderTotal", "total"), + joined("placedBy", "customer_id", "customers", "id"))), + List.of( + new Ask( + "find", + OntologyStatementKind.FIND, + "Order", + null, + null, + null, + null, + ORDER_WITH_TOTAL, + orderRows()), + open("open", "Order", List.of(31), ORDER_WITH_TOTAL, texts("31", "25.50")), + count("count", "Order", 33), + expand( + "expand-forward", + "Order", + List.of(31), + "placedBy", + OntologyStatementDirection.FORWARD, + columns( + "key Order part 0", + "key Customer part 0", + "displayName Customer customerName"), + texts("31", "2", "Grace Hopper")), + expand( + "expand-forward-after", + "Order", + List.of(31), + "placedBy", + OntologyStatementDirection.FORWARD, + columns( + "key Order part 0", + "key Customer part 0", + "displayName Customer customerName"), + texts("31", "2", "Grace Hopper")) + .withAfter(List.of(1)), + expand( + "expand-inverse", + "Customer", + List.of(2), + "placedBy", + OntologyStatementDirection.INVERSE, + CUSTOMER_THEN_ORDER, + texts("2", "31"), + texts("2", "32")), + new Ask( + "expand-inverse-page", + OntologyStatementKind.EXPAND, + "Customer", + null, + List.of(1), + "placedBy", + OntologyStatementDirection.INVERSE, + CUSTOMER_THEN_ORDER, + IntStream.rangeClosed(1, ORDERS_OF_FIRST_CUSTOMER) + .mapToObj(order -> texts("1", String.valueOf(order))) + .toList()), + new Ask( + "expand-inverse-after", + OntologyStatementKind.EXPAND, + "Customer", + null, + List.of(1), + "placedBy", + OntologyStatementDirection.INVERSE, + CUSTOMER_THEN_ORDER, + IntStream.rangeClosed(26, ORDERS_OF_FIRST_CUSTOMER) + .mapToObj(order -> texts("1", String.valueOf(order))) + .toList(), + null, + List.of(25)), + top( + "aggregate-forward", + "Order", + "placedBy", + OntologyStatementDirection.FORWARD, + columns("key Order part 0", "count Customer"), + IntStream.rangeClosed(1, 8) + .mapToObj(order -> texts(String.valueOf(order), "1")) + .toList()), + top( + "aggregate-inverse", + "Customer", + "placedBy", + OntologyStatementDirection.INVERSE, + columns( + "key Customer part 0", "displayName Customer customerName", "count Order"), + List.of(texts("1", "Ada Lovelace", "30"), texts("2", "Grace Hopper", "2"))))); + + /** 6. A relation held in a link table between two classes. */ + public static final Shape LINK_TABLE = + new Shape( + "linkTable", + List.of( + table( + "orders", + List.of(integer("id"), text("channel")), + row(1, "web"), + row(2, "store"), + row(3, "web")), + table( + "products", + List.of(text("sku"), text("title")), + row("A-1", "Anvil"), + row("B-2", "Bolt"), + row("C-3", "Crate"), + row("D-4", "Drill")), + table( + "order_items", + List.of(integer("order_id"), text("product_sku"), integer("quantity")), + row(1, "A-1", 2), + row(1, "B-2", 1), + row(1, "C-3", 5), + row(2, "A-1", 1), + row(null, "B-2", 1), + row(2, null, 3))), + List.of("Order", "Product"), + List.of( + data("orderChannel", false, "Order"), + data("productTitle", true, "Product"), + data("itemQuantity", false, "Order"), + relation("contains", "Order", "Product")), + List.of( + identity("Order", "orders", List.of("id"), null, bound("orderChannel", "channel")), + identity("Product", "products", List.of("sku"), null, bound("productTitle", "title")), + contributing( + "Order", + "order_items", + List.of("order_id"), + bound("itemQuantity", "quantity"), + joined("contains", "product_sku", "products", "sku"))), + List.of( + find( + "find", + "Order", + null, + columns("key Order part 0", "property Order orderChannel"), + texts("1", "web"), + texts("2", "store"), + texts("3", "web")), + open( + "open", + "Order", + List.of(1), + columns( + "key Order part 0", + "property Order orderChannel", + "property Order itemQuantity"), + texts("1", "web", "2"), + texts("1", "web", "1"), + texts("1", "web", "5")), + count("count", "Product", 4), + expand( + "expand-forward", + "Order", + List.of(1), + "contains", + OntologyStatementDirection.FORWARD, + columns( + "key Order part 0", "key Product part 0", "displayName Product productTitle"), + texts("1", "A-1", "Anvil"), + texts("1", "B-2", "Bolt"), + texts("1", "C-3", "Crate")), + expand( + "expand-forward-after", + "Order", + List.of(1), + "contains", + OntologyStatementDirection.FORWARD, + columns( + "key Order part 0", + "key Product part 0", + "displayName Product productTitle"), + texts("1", "B-2", "Bolt"), + texts("1", "C-3", "Crate")) + .withAfter(List.of("A-1")), + expand( + "expand-inverse", + "Product", + List.of("A-1"), + "contains", + OntologyStatementDirection.INVERSE, + columns("key Product part 0", "key Order part 0"), + texts("A-1", "1"), + texts("A-1", "2")), + expand( + "expand-inverse-after", + "Product", + List.of("A-1"), + "contains", + OntologyStatementDirection.INVERSE, + columns("key Product part 0", "key Order part 0"), + texts("A-1", "2")) + .withAfter(List.of(1)), + top( + "aggregate-forward", + "Order", + "contains", + OntologyStatementDirection.FORWARD, + columns("key Order part 0", "count Product"), + List.of(texts("1", "3"), texts("2", "1"))), + top( + "aggregate-inverse", + "Product", + "contains", + OntologyStatementDirection.INVERSE, + columns("key Product part 0", "displayName Product productTitle", "count Order"), + List.of( + texts("A-1", "Anvil", "2"), + texts("B-2", "Bolt", "1"), + texts("C-3", "Crate", "1"))))); + + /** The entries of account 1: sixty, so that three pages of 25 hold them. */ + public static final int ENTRIES_OF_FIRST_ACCOUNT = 60; + + private static final List ACCOUNT_THEN_ENTRY = + columns("key Account part 0", "key Entry part 0", "key Entry part 1"); + + /** + * 7. A relation whose related class has a two-column key, text then number. Account 1 holds 40 + * entries of ledger {@code a} and 20 of ledger {@code b}, so the first part of the key repeats + * across the end of each page of 25. Account 2 holds entries of a ledger written in mixed case. + * Two rows have a null part in their key and are no records. + */ + public static final Shape PAGED_COMPOSITE_RELATED_KEY = + new Shape( + "pagedCompositeRelatedKey", + List.of( + table( + "accounts", + List.of(integer("id"), text("name")), + row(1, "Main Ledger"), + row(2, "Mixed Ledger")), + new TableSpec( + "entries", + List.of(text("ledger"), integer("seq"), integer("account_id")), + entries())), + List.of("Entry", "Account"), + List.of(data("accountName", true, "Account"), relation("postedTo", "Entry", "Account")), + List.of( + identity("Account", "accounts", List.of("id"), null, bound("accountName", "name")), + identity( + "Entry", + "entries", + List.of("ledger", "seq"), + null, + joined("postedTo", "account_id", "accounts", "id"))), + List.of( + expandRows( + "expand-inverse", + "Account", + List.of(1), + "postedTo", + OntologyStatementDirection.INVERSE, + ACCOUNT_THEN_ENTRY, + firstAccountEntries()), + expandRows( + "expand-inverse-after", + "Account", + List.of(1), + "postedTo", + OntologyStatementDirection.INVERSE, + ACCOUNT_THEN_ENTRY, + firstAccountEntries().subList(25, 60)) + .withAfter(List.of("a", 25)), + expand( + "expand-forward", + "Entry", + List.of("b", 7), + "postedTo", + OntologyStatementDirection.FORWARD, + columns( + "key Entry part 0", + "key Entry part 1", + "key Account part 0", + "displayName Account accountName"), + texts("b", "7", "1", "Main Ledger")), + expand( + "expand-forward-after", + "Entry", + List.of("b", 7), + "postedTo", + OntologyStatementDirection.FORWARD, + columns( + "key Entry part 0", + "key Entry part 1", + "key Account part 0", + "displayName Account accountName"), + texts("b", "7", "1", "Main Ledger")) + .withAfter(List.of(0)))); + + /** + * The items of two owners, over a related key of three columns. Not in {@link #all()}, so it has + * no goldens. Owner 1 holds eight records and three rows with a null part of the key, and owner 2 + * holds three records whose keys satisfy the later disjuncts of an {@code after} that owner 1 + * starts from. + */ + public static final Shape TRIPLE_KEY_ITEMS = + heldItems( + "tripleKeyItems", + List.of(text("k1"), integer("k2"), decimal("k3")), + tripleKeyRows(), + List.of( + expandRows( + "expand-inverse", + "Owner", + List.of(1), + "heldBy", + OntologyStatementDirection.INVERSE, + columns( + "key Owner part 0", "key Item part 0", "key Item part 1", "key Item part 2"), + List.of( + texts("1", "l", "5", "6.00"), + texts("1", "l", "9", "9.00"), + texts("1", "m", "4", "9.00"), + texts("1", "m", "5", "4.00"), + texts("1", "m", "5", "5.00"), + texts("1", "m", "5", "6.00"), + texts("1", "m", "6", "0.00"), + texts("1", "n", "0", "0.00"))))); + + /** + * The items of one owner whose key is a JSON column, a type that takes no value. Not in {@link + * #all()}. The one record the table holds is no record on an engine that cannot compare JSON. + */ + public static final Shape JSON_KEY_ITEMS = + heldItems( + "jsonKeyItems", + List.of(new ColumnSpec("id", ColumnDataType.JSON)), + List.of(row("{\"a\": 1}", 1), row("{\"a\": 2}", 1)), + List.of( + expandRows( + "expand-inverse", + "Owner", + List.of(1), + "heldBy", + OntologyStatementDirection.INVERSE, + columns("key Owner part 0", "key Item part 0"), + List.of()))); + + /** + * An item names its owner. The items table holds the key columns, in order, and then the owner + * column, and the identity of an item is its key. + * + * @param rows the rows of the items table, each in column order + */ + public static Shape heldItems( + final String name, + final List key, + final List> rows, + final List asks) { + final List columns = new ArrayList<>(key); + columns.add(integer("owner_id")); + return new Shape( + name, + List.of( + new TableSpec( + "owners", + List.of(integer("id"), text("name")), + List.of(row(1, "One"), row(2, "Two"))), + new TableSpec("items", columns, rows)), + List.of("Owner", "Item"), + List.of(relation("heldBy", "Item", "Owner")), + List.of( + identity("Owner", "owners", List.of("id"), null), + identity( + "Item", + "items", + key.stream().map(ColumnSpec::name).toList(), + null, + joined("heldBy", "owner_id", "owners", "id"))), + asks); + } + + /** The rows of the items table of {@link #TRIPLE_KEY_ITEMS}, in an order that is not key order. */ + private static List> tripleKeyRows() { + return List.of( + row("m", 5, new BigDecimal("5"), 1), + row("m", 5, new BigDecimal("7"), 2), + row("n", 0, new BigDecimal("0"), 1), + row("l", 5, new BigDecimal("6"), 1), + row("m", null, new BigDecimal("1"), 1), + row("m", 5, new BigDecimal("6"), 1), + row("o", 0, new BigDecimal("0"), 2), + row("m", 4, new BigDecimal("9"), 1), + row(null, 1, new BigDecimal("1"), 1), + row("m", 6, new BigDecimal("0"), 1), + row("m", 5, new BigDecimal("4"), 1), + row("l", 9, new BigDecimal("9"), 1), + row("m", 7, new BigDecimal("0"), 2), + row("m", 1, null, 1)); + } + + public static List all() { + return List.of( + UNFILTERED_IDENTITY, + FILTERED_IDENTITY, + COMPOSITE_KEY, + REPEATED_CONTRIBUTION, + COLUMN_RELATION, + LINK_TABLE, + PAGED_COMPOSITE_RELATED_KEY); + } + + /** The 60 entries of account 1 in key order, each with the key of its account. */ + private static List> firstAccountEntries() { + final List> rows = new ArrayList<>(); + IntStream.rangeClosed(1, 40).forEach(seq -> rows.add(texts("1", "a", String.valueOf(seq)))); + IntStream.rangeClosed(1, 20).forEach(seq -> rows.add(texts("1", "b", String.valueOf(seq)))); + return List.copyOf(rows); + } + + /** + * The rows of the entries table, in an order that is not the key order: the 60 entries of + * account 1, six entries of account 2, and two rows with a null part in their key. + */ + private static List> entries() { + final List> ordered = new ArrayList<>(); + IntStream.rangeClosed(1, 40).forEach(seq -> ordered.add(row("a", seq, 1))); + IntStream.rangeClosed(1, 20).forEach(seq -> ordered.add(row("b", seq, 1))); + final List> rows = new ArrayList<>(); + for (int index = 0; index < ordered.size(); index++) { + rows.add(ordered.get(index * 7 % ordered.size())); + } + rows.add(row("x", 1, 2)); + rows.add(row("Y", 2, 2)); + rows.add(row("z", 1, 2)); + rows.add(row("Y", 1, 2)); + rows.add(row("x", 2, 2)); + rows.add(row("z", 2, 2)); + rows.add(row("c", null, 1)); + rows.add(row(null, 3, 1)); + return List.copyOf(rows); + } + + /** The 33 orders that are records, each with its total: more than one page of find. */ + private static List> orderRows() { + return orders().stream() + .filter(order -> order.getFirst() != null) + .map(order -> texts(order.getFirst().toString(), order.getLast().toString())) + .toList(); + } + + /** + * Thirty orders of customer 1, two of customer 2, one that names no customer, and one row with + * no id, which is no record. + */ + private static List> orders() { + final List> rows = new ArrayList<>(); + for (int order = 1; order <= ORDERS_OF_FIRST_CUSTOMER; order++) { + rows.add(row(order, 1, new BigDecimal("10.00"))); + } + rows.add(row(31, 2, new BigDecimal("25.50"))); + rows.add(row(32, 2, new BigDecimal("12.25"))); + rows.add(row(33, null, new BigDecimal("99.00"))); + rows.add(row(null, 1, new BigDecimal("5.00"))); + return List.copyOf(rows); + } + + static ColumnSpec integer(final String name) { + return new ColumnSpec(name, ColumnDataType.INT); + } + + static ColumnSpec text(final String name) { + return new ColumnSpec(name, ColumnDataType.VARCHAR); + } + + static ColumnSpec decimal(final String name) { + return new ColumnSpec(name, ColumnDataType.DECIMAL); + } + + @SafeVarargs + static TableSpec table( + final String name, final List columns, final List... rows) { + return new TableSpec(name, columns, List.of(rows)); + } + + /** A row that may hold nulls, which {@code List.of} refuses. */ + static List row(final Object... values) { + return Arrays.asList(values); + } + + static List texts(final String... values) { + return Arrays.asList(values); + } + + static PropertySpec data(final String name, final boolean displayName, final String domain) { + return new PropertySpec(name, displayName, domain, null); + } + + static PropertySpec relation(final String name, final String domain, final String range) { + return new PropertySpec(name, false, domain, range); + } + + static ColumnBindingSpec bound(final String property, final String column) { + return new ColumnBindingSpec(property, column, null); + } + + static ColumnBindingSpec joined( + final String property, final String column, final String target, final String parent) { + return new ColumnBindingSpec( + property, + column, + new JoinSpec(target, OntologyJoinStatus.CONFIRMED, List.of(column), List.of(parent))); + } + + static BindingSpec identity( + final String type, + final String table, + final List key, + final FilterSpec filter, + final ColumnBindingSpec... columns) { + return new BindingSpec( + type, table, OntologyBindingRole.IDENTITY, key, filter, List.of(columns)); + } + + static BindingSpec contributing( + final String type, + final String table, + final List key, + final ColumnBindingSpec... columns) { + return new BindingSpec( + type, table, OntologyBindingRole.CONTRIBUTING, key, null, List.of(columns)); + } + + /** The lines of a column plan, each with its index in front. */ + static List columns(final String... held) { + return IntStream.range(0, held.length).mapToObj(index -> index + " " + held[index]).toList(); + } + + @SafeVarargs + private static Ask find( + final String name, + final String type, + final String matchText, + final List columns, + final List... rows) { + return new Ask( + name, + OntologyStatementKind.FIND, + type, + matchText, + null, + null, + null, + columns, + List.of(rows)); + } + + @SafeVarargs + private static Ask open( + final String name, + final String type, + final List key, + final List columns, + final List... rows) { + return new Ask( + name, OntologyStatementKind.OPEN, type, null, key, null, null, columns, List.of(rows)); + } + + /** The count of a class: one row with one column, the number of its records. */ + private static Ask count(final String name, final String type, final int records) { + return new Ask( + name, + OntologyStatementKind.AGGREGATE, + type, + null, + null, + null, + null, + columns("count " + type), + List.of(List.of(String.valueOf(records)))); + } + + @SafeVarargs + private static Ask expand( + final String name, + final String type, + final List key, + final String relation, + final OntologyStatementDirection direction, + final List columns, + final List... rows) { + return new Ask( + name, + OntologyStatementKind.EXPAND, + type, + null, + key, + relation, + direction, + columns, + List.of(rows)); + } + + private static Ask expandRows( + final String name, + final String type, + final List key, + final String relation, + final OntologyStatementDirection direction, + final List columns, + final List> rows) { + return new Ask( + name, OntologyStatementKind.EXPAND, type, null, key, relation, direction, columns, rows); + } + + private static Ask top( + final String name, + final String type, + final String relation, + final OntologyStatementDirection direction, + final List columns, + final List> rows) { + return new Ask( + name, + OntologyStatementKind.AGGREGATE, + type, + null, + null, + relation, + direction, + columns, + rows); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java new file mode 100644 index 000000000000..8e998e3b5736 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPortablePatternTest.java @@ -0,0 +1,208 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Optional; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Which regular expressions are written for Postgres and how, one pattern for each rule. The + * integration tests run the written patterns on the engine. + */ +class OntologyPortablePatternTest { + @ParameterizedTest + @ValueSource( + strings = { + "^$", + "^abc 123$", + "^a\\.b\\-c\\$\\^\\\\$", + "^[a-z]$", + "^[A-Z0-9 ]+$", + "^[^0-9]*$", + "^[abc]{3}$", + "^a?b*c+$", + "^a{2}b{2,}c{2,5}$", + "^(ab|cd)$", + "^(a(b|c))+d$", + "^(a|b)(c|d)$", + "^[0-9]{4}\\-[0-9]{2}\\-[0-9]{2}$", + "^O'Brien$", + "^a:b$", + "^:name$", + "^[^@ ]+@[^@ ]+$", + "^[A-Z]{2}-[0-9]{4}$", + "^a_b$", + "^a\\tb$", + "^a\\nb\\rc$", + "^[^\\n\\r]*$", + "^[\\t ]+$", + "^[a\\-z]+$", + "^x'\\); DROP TABLE t; --$", + "^x'\\) OR 1=1 --$", + "^a\\\\b$", + "^\\$1$", + "^[!\"#%&',/:;<=>@_`~]+$" + }) + void writesAPatternInsideTheCommonCoreAsItIsGiven(final String pattern) { + assertEquals(Optional.of(pattern), OntologyPortablePattern.forPostgres(pattern)); + } + + @ParameterizedTest + @CsvSource( + delimiterString = " => ", + value = { + "^a.c$ => ^a[^\\n\\r]c$", + "^.$ => ^[^\\n\\r]$", + "^.*$ => ^[^\\n\\r]*$", + "^a\\.b.$ => ^a\\.b[^\\n\\r]$", + "^(a|.)+.{2,3}$ => ^(a|[^\\n\\r])+[^\\n\\r]{2,3}$", + "^[a-z]+.[0-9]$ => ^[a-z]+[^\\n\\r][0-9]$", + "^O'Brien.$ => ^O'Brien[^\\n\\r]$", + "^a.\\tb$ => ^a[^\\n\\r]\\tb$" + }) + void writesAWildcardAsEveryCharacterButALineBreak(final String pattern, final String written) { + assertEquals(Optional.of(written), OntologyPortablePattern.forPostgres(pattern)); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + "abc", + "^abc", + "abc$", + "^abc\\$", + "^a|b$", + "^a^b$", + "^a$b$", + "^\\d+$", + "^\\w$", + "^a\\1$", + "^(?:a)$", + "^(?=a)a$", + "^(?i)a$", + "^a*?$", + "^a+?$", + "^a??$", + "^a*+$", + "^a{2}?$", + "^a**$", + "^*a$", + "^a{,2}$", + "^a{3,2}$", + "^a{256}$", + "^a{2$", + "^(a$", + "^a)$", + "^()$", + "^(a|)$", + "^[]$", + "^[a$", + "^[z-a]$", + "^[a-Z]$", + "^[a-]$", + "^[a-é]$", + "^[0-٣]$", + "^[\\d]$", + "^[.]$", + "^[[:alpha:]]$", + "^café$", + "^a\tb$", + "^a}$", + "^a]$", + "^{2}$", + "^a{$", + "^[a-]$", + "^[-a]$", + "^[a^]$", + "^[a$]$", + "^[a|b]$", + "^[(]$", + "^[?]$", + "^[a{]$", + "^[\\d]$", + "^\\D$", + "^\\s$", + "^\\S$", + "^\\W$", + "^\\i$", + "^\\I$", + "^\\c$", + "^\\C$", + "^\\p{L}$", + "^\\P{L}$", + "^O\\'Brien$", + "^a\\:b$", + "^\\@$", + "^\\;$", + "^\\=$", + "^\\_$", + "^\\ $", + "^\\é$", + "^a\\é$", + "^[\\@]$", + "^x\\'\\)\\; DROP TABLE t\\; \\-\\-$" + }) + void refusesAPatternOutsideTheCommonCore(final String pattern) { + assertEquals(Optional.empty(), OntologyPortablePattern.forPostgres(pattern), pattern); + } + + /** The escapes of XPath's single characters: XPath and XQuery Functions and Operators 3.1, 5.6.1. */ + private static final String XPATH_ESCAPES = "nrt\\|.?*+(){}-[]^$"; + + private static final String METACHARACTERS = ".\\?*+{}()[]|^$"; + + @ParameterizedTest + @MethodSource("asciiAfterABackslash") + void takesABackslashBeforeACharacterOfTheXPathEscapeSetOnly(final char escaped) { + final boolean read = XPATH_ESCAPES.indexOf(escaped) >= 0; + assertEquals( + read, + OntologyPortablePattern.forPostgres("^\\" + escaped + "$").isPresent(), + "outside a class, backslash then " + escaped); + assertEquals( + read, + OntologyPortablePattern.forPostgres("^[a\\" + escaped + "]$").isPresent(), + "inside a class, backslash then " + escaped); + } + + @ParameterizedTest + @MethodSource("asciiPunctuationWithoutMetacharacters") + void takesAnAsciiPunctuationCharacterThatIsNoMetacharacterAsItself(final char punctuation) { + final String outside = "^a" + punctuation + "b$"; + assertEquals(Optional.of(outside), OntologyPortablePattern.forPostgres(outside)); + final String inside = "^[a" + punctuation + "b]$"; + if (punctuation != '-') { + assertEquals(Optional.of(inside), OntologyPortablePattern.forPostgres(inside)); + } + } + + static Stream asciiAfterABackslash() { + return IntStream.rangeClosed(' ', '~').mapToObj(code -> (char) code); + } + + static Stream asciiPunctuationWithoutMetacharacters() { + return IntStream.rangeClosed('!', '~') + .mapToObj(code -> (char) code) + .filter(character -> !Character.isLetterOrDigit(character)) + .filter(character -> METACHARACTERS.indexOf(character) < 0); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPropertyRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPropertyRulesTest.java index f2ebd796ea79..d3607f1d84cc 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPropertyRulesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyPropertyRulesTest.java @@ -42,6 +42,29 @@ void everyPropertyKindMayNameSuperproperties() { } } + @Test + void onlyADataPropertyMayBeADisplayName() { + final OntologyProperty property = + new OntologyProperty() + .withIri(PROPERTY) + .withKind(OntologyPropertyKind.DATA) + .withIsDisplayName(true); + assertNull(OntologyPropertyRules.firstViolation(property, () -> false)); + for (final OntologyPropertyKind kind : + List.of(OntologyPropertyKind.OBJECT, OntologyPropertyKind.ANNOTATION)) { + assertEquals( + new OntologyPropertyRules.Violation( + "isDisplayName", + "Only data properties can define enum values, units, identifier intent or" + + " display-name intent"), + OntologyPropertyRules.firstViolation(property.withKind(kind), () -> false), + kind.toString()); + } + assertNull( + OntologyPropertyRules.firstViolation( + property.withKind(OntologyPropertyKind.OBJECT).withIsDisplayName(null), () -> false)); + } + private static OntologyPropertyRules.Violation violation(final List superProperties) { return OntologyPropertyRules.firstViolation( new OntologyProperty() diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyRecordStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyRecordStatementTest.java new file mode 100644 index 000000000000..6071a8ccae86 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyRecordStatementTest.java @@ -0,0 +1,431 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.service.ontology.OntologyMappingShapeModel.plan; +import static org.openmetadata.service.ontology.OntologyMappingShapeModel.read; +import static org.openmetadata.service.ontology.OntologyMappingShapeModel.sql; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.FILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; + +import jakarta.ws.rs.ClientErrorException; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.api.data.OntologyStatementEngineFamily; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.RecordStatement; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.sql.FinishedStatement; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.security.AuthorizationException; + +/** + * The statements that find the records of a class and open one record. Each starts from the + * identity table of the class, whoever asks. + */ +class OntologyRecordStatementTest { + private static final String POSTGRES = "Postgres"; + private static final String MYSQL = "Mysql"; + private static final String ACCOUNT = "https://example.org/compositeKey#Account"; + + @Test + void findListsTheKeyThenTheDisplayNameThenTheOtherColumnsOfTheIdentityTable() { + final RecordStatement find = find(model(UNFILTERED_IDENTITY, POSTGRES), "Customer", null); + + assertEquals( + "SELECT t0.id, t0.name, t0.email\nFROM shop.customers t0\nWHERE t0.id IS NOT NULL\nLIMIT 25", + sql(find)); + assertEquals( + List.of( + "0 key Customer part 0", + "1 displayName Customer customerName", + "2 property Customer customerEmail"), + plan(find)); + assertEquals(25, find.rowCap()); + assertFalse(find.extraRow()); + } + + @Test + void findReadsOnlyTheIdentityTableAndAppliesItsRowFilter() { + final RecordStatement people = find(model(FILTERED_IDENTITY, MYSQL), "Person", null); + final RecordStatement customers = find(model(REPEATED_CONTRIBUTION, MYSQL), "Customer", null); + + assertEquals( + "SELECT t0.`id`, t0.`name`\nFROM `shop`.`parties` t0\nWHERE t0.`id` IS NOT NULL\n" + + " AND t0.`kind` = 'person'\nLIMIT 25", + sql(people)); + assertEquals(List.of("customers"), read(customers)); + assertEquals( + List.of("0 key Customer part 0", "1 displayName Customer customerName"), plan(customers)); + } + + @Test + void matchTextWithNoUppercaseLetterMatchesWithoutRegardToCase() { + assertEquals( + "SELECT t0.id, t0.name, t0.email\nFROM shop.customers t0\nWHERE t0.id IS NOT NULL\n" + + " AND LOWER(t0.name) LIKE '%hopper%' ESCAPE '!'\nLIMIT 25", + sql(find(model(UNFILTERED_IDENTITY, POSTGRES), "Customer", "hopper"))); + } + + @Test + void matchTextWithAnUppercaseLetterIsComparedAsItIsWritten() { + assertEquals( + "SELECT t0.id, t0.name, t0.email\nFROM shop.customers t0\nWHERE t0.id IS NOT NULL\n" + + " AND t0.name LIKE '%Hopper%' ESCAPE '!'\nLIMIT 25", + sql(find(model(UNFILTERED_IDENTITY, POSTGRES), "Customer", "Hopper"))); + } + + @Test + void emptyMatchTextMatchesEveryRecord() { + final OntologyMappingShapeModel model = model(UNFILTERED_IDENTITY, POSTGRES); + + assertEquals(sql(find(model, "Customer", null)), sql(find(model, "Customer", ""))); + } + + @Test + void matchTextThatIsTooLongOrHoldsAControlCharacterIsRefused() { + final OntologyMappingShapeModel model = model(UNFILTERED_IDENTITY, POSTGRES); + + assertEquals( + "Search text must have at most 256 characters", + assertThrows(BadRequestException.class, () -> find(model, "Customer", "a".repeat(257))) + .getMessage()); + assertEquals( + "Search text must not hold a control character", + assertThrows(BadRequestException.class, () -> find(model, "Customer", "a\nb")) + .getMessage()); + } + + @Test + void aClassThatBindsNoDisplayNameOnItsIdentityTableTakesNoMatchText() { + final OntologyMappingShapeModel model = model(COLUMN_RELATION, POSTGRES); + + final ClientErrorException refused = + assertThrows(ClientErrorException.class, () -> find(model, "Order", "ada")); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "Class https://example.org/columnRelation#Order binds no display name column on its" + + " identity table, so it takes no match text", + refused.getMessage()); + } + + @Test + void openJoinsAContributingTableOnTheSubjectKeyByPosition() { + final RecordStatement open = open(model(COMPOSITE_KEY, MYSQL), "Account", List.of("eu", 42)); + + assertEquals( + "SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name`, t1.`tier`\n" + + "FROM `shop`.`crm_customers` t0\n" + + "LEFT JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id`" + + " AND t1.`customer` = t0.`customer_id`\n" + + "WHERE t0.`tenant_id` = 'eu'\n AND t0.`customer_id` = 42\nLIMIT 101", + sql(open)); + assertEquals( + List.of( + "0 key Account part 0", + "1 key Account part 1", + "2 displayName Account accountName", + "3 property Account accountTier"), + plan(open)); + assertEquals(List.of("crm_customers", "crm_customer_profile"), read(open)); + assertEquals(100, open.rowCap()); + assertTrue(open.extraRow()); + } + + @Test + void theRowFilterOfAContributingTableStaysInItsJoinSoThatARecordWithoutSuchARowStillOpens() { + final OntologyMappingShapeModel model = + new OntologyMappingShapeModel( + COMPOSITE_KEY, + POSTGRES, + List.of( + COMPOSITE_KEY.bindings().getFirst(), + profile( + List.of("tenant", "customer"), + new FilterSpec("tier", OntologyRowFilterOperator.NOT_EQUALS, "none")))); + + assertEquals( + "SELECT t0.tenant_id, t0.customer_id, t0.name, t1.tier\nFROM shop.crm_customers t0\n" + + "LEFT JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id" + + " AND t1.customer = t0.customer_id AND t1.tier <> 'none'\n" + + "WHERE t0.tenant_id = 'eu'\n AND t0.customer_id = 42\nLIMIT 101", + sql(open(model, "Account", List.of("eu", 42)))); + } + + @Test + void aContributingTableTheReaderMayNotViewLeavesTheStatementAndThePlan() { + final RecordStatement open = + open( + model(COMPOSITE_KEY, POSTGRES).hide("crm_customer_profile"), + "Account", + List.of("eu", 42)); + + assertEquals( + "SELECT t0.tenant_id, t0.customer_id, t0.name\nFROM shop.crm_customers t0\n" + + "WHERE t0.tenant_id = 'eu'\n AND t0.customer_id = 42\nLIMIT 101", + sql(open)); + assertEquals( + List.of( + "0 key Account part 0", "1 key Account part 1", "2 displayName Account accountName"), + plan(open)); + assertEquals(List.of("crm_customers"), read(open)); + } + + @Test + void aContributingTableThatAddsNoResultColumnIsNotJoined() { + final RecordStatement open = + open(model(LINK_TABLE, POSTGRES).omit("itemQuantity"), "Order", List.of(1)); + + assertEquals( + "SELECT t0.id, t0.channel\nFROM shop.orders t0\nWHERE t0.id = 1\nLIMIT 101", sql(open)); + assertEquals(List.of("0 key Order part 0", "1 property Order orderChannel"), plan(open)); + assertEquals(List.of("orders"), read(open)); + } + + @Test + void aKeyTakesOneValueForEachColumnOfTheSubjectKey() { + final OntologyMappingShapeModel model = model(COMPOSITE_KEY, POSTGRES); + + assertEquals( + "The key has 2 columns but the request gives 1 value", + assertThrows(BadRequestException.class, () -> open(model, "Account", List.of(42))) + .getMessage()); + assertEquals( + "The value for column customer_id does not parse as INT: a whole number is written in" + + " ASCII digits, with a leading minus sign when negative and no leading zeros", + assertThrows(BadRequestException.class, () -> open(model, "Account", List.of("eu", "x"))) + .getMessage()); + assertEquals( + "The value for column tenant_id is null", + assertThrows( + BadRequestException.class, () -> open(model, "Account", Arrays.asList(null, 42))) + .getMessage()); + } + + @Test + void aValueWithAColonIsBareForAPersonAndEscapedForAReaderOfParameters() { + final RecordStatement open = + open( + model(COMPOSITE_KEY, POSTGRES).hide("crm_customer_profile"), + "Account", + List.of("eu:west", 42)); + + final FinishedStatement text = open.family().finish(open.text()); + + assertEquals( + "SELECT t0.tenant_id, t0.customer_id, t0.name\nFROM shop.crm_customers t0\n" + + "WHERE t0.tenant_id = 'eu:west'\n AND t0.customer_id = 42\nLIMIT 101", + text.sql()); + assertEquals( + "SELECT t0.tenant_id, t0.customer_id, t0.name\nFROM shop.crm_customers t0\n" + + "WHERE t0.tenant_id = 'eu\\:west'\n AND t0.customer_id = 42\nLIMIT 101", + text.escapedSql()); + } + + @Test + void aClassWithoutAnIdentityTableGivesNoStatement() { + final OntologyMappingShapeModel unbound = + new OntologyMappingShapeModel( + COMPOSITE_KEY, POSTGRES, List.of(COMPOSITE_KEY.bindings().getLast())); + final OntologyMappingShapeModel dropped = + model(COMPOSITE_KEY, POSTGRES).delete("crm_customers"); + + for (final OntologyMappingShapeModel model : List.of(unbound, dropped)) { + final ClientErrorException refused = + assertThrows(ClientErrorException.class, () -> find(model, "Account", null)); + assertEquals(409, refused.getResponse().getStatus()); + assertEquals("Class " + ACCOUNT + " has no identity table", refused.getMessage()); + } + } + + @Test + void anIdentityTableTheReaderMayNotViewIsRefusedWithoutBeingNamed() { + final OntologyMappingShapeModel model = model(COMPOSITE_KEY, POSTGRES).hide("crm_customers"); + + final AuthorizationException refused = + assertThrows(AuthorizationException.class, () -> open(model, "Account", List.of("eu", 42))); + + assertEquals( + "The identity table of class " + ACCOUNT + " is not visible to you", refused.getMessage()); + } + + @Test + void aPropertyTheVersionLacksOrTheReaderMayNotViewLeavesThePlan() { + final RecordStatement find = + find(model(UNFILTERED_IDENTITY, POSTGRES).omit("customerName"), "Customer", null); + + assertEquals( + "SELECT t0.id, t0.email\nFROM shop.customers t0\nWHERE t0.id IS NOT NULL\nLIMIT 25", + sql(find)); + assertEquals(List.of("0 key Customer part 0", "1 property Customer customerEmail"), plan(find)); + } + + @Test + void aBoundColumnThatLeftTheTableLeavesThePlanAndAKeyColumnThatLeftGivesNoStatement() { + final OntologyMappingShapeModel model = model(UNFILTERED_IDENTITY, POSTGRES); + model.table("customers").getColumns().removeIf(column -> column.getName().equals("email")); + + assertEquals( + "SELECT t0.id, t0.name\nFROM shop.customers t0\nWHERE t0.id IS NOT NULL\nLIMIT 25", + sql(find(model, "Customer", null))); + + model.table("customers").getColumns().removeIf(column -> column.getName().equals("id")); + final ClientErrorException refused = + assertThrows(ClientErrorException.class, () -> find(model, "Customer", null)); + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "Column id of warehouse.sales.shop.customers no longer exists", refused.getMessage()); + } + + @Test + void aRowFilterThatNoLongerAppliesIsRefusedOnlyByAStatementThatReadsItsTable() { + final OntologyMappingShapeModel model = + new OntologyMappingShapeModel( + COMPOSITE_KEY, + POSTGRES, + List.of( + COMPOSITE_KEY.bindings().getFirst(), + profile( + List.of("tenant", "customer"), + new FilterSpec("segment", OntologyRowFilterOperator.EQUALS, "retail")))); + + assertEquals(List.of("crm_customers"), read(find(model, "Account", null))); + assertEquals( + "The row filter of warehouse.sales.shop.crm_customer_profile no longer applies. A row" + + " filter column must exist in the bound table", + assertThrows(BadRequestException.class, () -> open(model, "Account", List.of("eu", 42))) + .getMessage()); + } + + @Test + void aStaleRowFilterOfAContributingTableThatAddsNoColumnChangesNothing() { + final OntologyMappingShapeModel model = + new OntologyMappingShapeModel( + COMPOSITE_KEY, + POSTGRES, + List.of( + COMPOSITE_KEY.bindings().getFirst(), + profile( + List.of("tenant", "customer"), + new FilterSpec("segment", OntologyRowFilterOperator.EQUALS, "retail")))); + + final RecordStatement open = open(model.omit("accountTier"), "Account", List.of("eu", 42)); + + assertEquals( + "SELECT t0.tenant_id, t0.customer_id, t0.name\nFROM shop.crm_customers t0\n" + + "WHERE t0.tenant_id = 'eu'\n AND t0.customer_id = 42\nLIMIT 101", + sql(open)); + assertEquals(List.of("crm_customers"), read(open)); + } + + @Test + void aContributingTableWhoseKeyHasAnotherLengthGivesNoStatement() { + final OntologyMappingShapeModel model = + new OntologyMappingShapeModel( + COMPOSITE_KEY, + POSTGRES, + List.of(COMPOSITE_KEY.bindings().getFirst(), profile(List.of("tenant"), null))); + + final ClientErrorException refused = + assertThrows(ClientErrorException.class, () -> open(model, "Account", List.of("eu", 42))); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "The subject key of warehouse.sales.shop.crm_customer_profile has 1 columns and the key of" + + " class " + + ACCOUNT + + " has 2", + refused.getMessage()); + } + + @Test + void aContributingTableInAnotherDatabaseGivesNoStatement() { + final OntologyMappingShapeModel model = model(COMPOSITE_KEY, POSTGRES); + model + .table("crm_customer_profile") + .setFullyQualifiedName("warehouse.marketing.shop.crm_customer_profile"); + + final ClientErrorException refused = + assertThrows(ClientErrorException.class, () -> open(model, "Account", List.of("eu", 42))); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals( + "Table warehouse.marketing.shop.crm_customer_profile is in another database than the" + + " identity table of class " + + ACCOUNT, + refused.getMessage()); + } + + @Test + void aServiceTypeOutsideEveryEngineFamilyIsRefusedByName() { + assertEquals( + "SQL generation does not support Oracle", + assertThrows( + BadRequestException.class, + () -> find(model(UNFILTERED_IDENTITY, "Oracle"), "Customer", null)) + .getMessage()); + } + + @Test + void thePlanNamesEveryEngineFamilyThatWritesAStatement() { + assertEquals( + Arrays.stream(SqlEngineFamily.values()) + .map(family -> family.name().toLowerCase(Locale.ROOT)) + .toList(), + Arrays.stream(OntologyStatementEngineFamily.values()) + .map(OntologyStatementEngineFamily::value) + .toList()); + } + + private static OntologyMappingShapeModel model(final Shape shape, final String serviceType) { + return new OntologyMappingShapeModel(shape, serviceType); + } + + private static RecordStatement find( + final OntologyMappingShapeModel model, final String type, final String matchText) { + return OntologyConceptSqlGenerator.find(model.mapped(type), matchText); + } + + private static RecordStatement open( + final OntologyMappingShapeModel model, final String type, final List key) { + return OntologyConceptSqlGenerator.open(model.mapped(type), model.contributing(type), key); + } + + /** The profile table of the composite key shape, bound with another key or row filter. */ + private static BindingSpec profile(final List key, final FilterSpec filter) { + return new BindingSpec( + "Account", + "crm_customer_profile", + OntologyBindingRole.CONTRIBUTING, + key, + filter, + List.of(new ColumnBindingSpec("accountTier", "tier", null))); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReferencesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReferencesTest.java index 6e22a85ef379..1a29c4935778 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReferencesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReferencesTest.java @@ -15,11 +15,13 @@ import org.openmetadata.schema.entity.data.OntologyAxiom; import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyExpression; import org.openmetadata.schema.type.OntologyExpressionKind; import org.openmetadata.schema.type.OntologyLiteral; import org.openmetadata.schema.type.OntologyReference; +import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.service.exception.BadRequestException; class OntologyReferencesTest { @@ -130,6 +132,38 @@ void nestedExpressionsAndAssertionsIncludeIndividualsPropertiesAndDatatypes() { keys(OntologyReferences.collect(axiom))); } + @Test + void aShapeIndexesTheClassesAndPropertiesItNamesAndNothingElse() { + OntologyShape shape = + new OntologyShape() + .withId(UUID.randomUUID()) + .withOntology(OWNER) + .withTargetConcept(iri("Person")) + .withConstraints( + List.of( + new OntologyShapeConstraint() + .withId("home") + .withPath(iri("livesAt")) + .withClassIri(iri("Address")) + .withDatatypeIri(iri("text")), + new OntologyShapeConstraint() + .withId("name") + .withPath(iri("name")) + .withMinCount(1))); + + List references = OntologyReferences.collect(shape); + + assertEquals( + Set.of( + "CLASS_EXPRESSION:Person", + "CLASS_EXPRESSION:Address", + "PROPERTY:livesAt", + "PROPERTY:name"), + keys(references)); + assertEquals("ontologyShape", references.getFirst().getSource().getType()); + assertEquals(List.of(), OntologyReferences.collect(shape.withDeleted(true))); + } + @Test void removedDefinitionsAndNamespacesHaveNoOutgoingReferences() { assertTrue(OntologyReferences.collect(new Ontology().withId(OWNER.getId())).isEmpty()); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseContentDigestTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseContentDigestTest.java new file mode 100644 index 000000000000..7cca6a3a8cd6 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseContentDigestTest.java @@ -0,0 +1,77 @@ +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; + +class OntologyReleaseContentDigestTest { + private static final UUID RELEASE = UUID.fromString("00000000-0000-0000-0000-0000000000a1"); + + /** + * The sealed content and digest of this property, computed on the commit before display-name + * intent existed. Both are literals, so a change to the generated classes or to the sealed fields + * that touches an unflagged property fails here. + */ + private static final String SEALED_BEFORE = + "{\"id\":\"00000000-0000-0000-0000-0000000000b1\",\"name\":\"name\"," + + "\"ontology\":{\"id\":\"00000000-0000-0000-0000-0000000000c1\",\"type\":\"ontology\"}," + + "\"iri\":\"https://example.org/name\",\"kind\":\"DATA\",\"domain\":[],\"range\":[]," + + "\"enumValues\":[],\"isIdentifier\":false,\"characteristics\":[],\"propertyChain\":[]," + + "\"disjointWith\":[],\"superProperties\":[],\"deprecated\":false}"; + + private static final String DIGEST_BEFORE = + "21498bea62f55ff6341537c8a8344d8f9b8628ce4fd5a3bbaf80485961fe2f3a"; + + @Test + void aPropertyWithoutTheFlagSealsTheDigestItAlwaysHad() { + final OntologyProperty property = property(); + + assertFalse(OntologyReleaseContent.project(property).has("isDisplayName")); + assertEquals(SEALED_BEFORE, OntologyReleaseContent.project(property).toString()); + assertEquals(DIGEST_BEFORE, digest(OntologyReleaseContent.project(property))); + assertEquals( + DIGEST_BEFORE, digest(OntologyReleaseContent.project(property.withIsDisplayName(null)))); + } + + @Test + void aPropertyWithTheFlagSealsItAndChangesTheDigest() { + final OntologyProperty property = property(); + final String without = digest(OntologyReleaseContent.project(property)); + final ObjectNode with = OntologyReleaseContent.project(property.withIsDisplayName(true)); + + assertTrue(with.path("isDisplayName").asBoolean()); + assertNotEquals(without, digest(with)); + } + + private static OntologyProperty property() { + return new OntologyProperty() + .withId(UUID.fromString("00000000-0000-0000-0000-0000000000b1")) + .withName("name") + .withIri(URI.create("https://example.org/name")) + .withKind(OntologyPropertyKind.DATA) + .withOntology( + new org.openmetadata.schema.type.EntityReference() + .withId(UUID.fromString("00000000-0000-0000-0000-0000000000c1")) + .withType("ontology")); + } + + private static String digest(final ObjectNode payload) { + return OntologyReleaseManifest.digest( + List.of( + OntologyReleaseManifest.member( + RELEASE, + MemberKind.PROPERTY, + UUID.fromString("00000000-0000-0000-0000-0000000000b1"), + payload))); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseManifestTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseManifestTest.java index 51029a31820f..68000c7c750a 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseManifestTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyReleaseManifestTest.java @@ -2,15 +2,19 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.net.URI; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.Ontology; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; import org.openmetadata.schema.utils.JsonUtils; @@ -29,6 +33,25 @@ void releaseHeadersAreNotCapturedDefinitionContent() { assertEquals("Unsupported ontology content: " + OntologyRelease.class, failure.getMessage()); } + @Test + void theMappingSourceOfAnOntologyIsNotCapturedDefinitionContent() { + final URI namespace = URI.create("https://example.org/sales/"); + final Ontology plain = new Ontology().withId(MEMBER).withName("sales").withNamespace(namespace); + final Ontology mapped = + new Ontology() + .withId(MEMBER) + .withName("sales") + .withNamespace(namespace) + .withMappingSource(new EntityReference().withId(RELEASE).withType("database")); + + final var content = OntologyReleaseContent.project(mapped); + + assertEquals("sales", content.get("name").asText()); + assertEquals("https://example.org/sales/", content.get("namespace").asText()); + assertFalse(content.has("mappingSource")); + assertEquals(OntologyReleaseContent.project(plain), content); + } + @Test void memberDigestsIgnoreJsonObjectOrderButPreserveIriSpelling() { OntologyReleaseMember first = diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java new file mode 100644 index 000000000000..e06010c6ea4c --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckAnswerTest.java @@ -0,0 +1,479 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.limit; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literals; + +import java.net.URI; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.api.data.OntologyCheckedConstraint; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.ontology.OntologyShapeCheckAnswer.Hidden; + +/** + * The answer as a caller reads it: one kind of entry for each outcome, every test as a request to + * create a test case takes it, and nothing about a constraint that rests on a table the caller + * may not view. + */ +class OntologyShapeCheckAnswerTest { + private static final String POSTGRES = "Postgres"; + private static final String CUSTOM_SQL = "tableCustomSQLQuery"; + private static final String CUSTOMERS_LINK = "<#E::table::warehouse.sales.shop.customers>"; + + /** The parameters after the statement, which say that the test passes at 0 violations. */ + private static final String PASSES_AT_NO_VIOLATION = + "[{\"name\":\"strategy\",\"value\":\"COUNT\"}," + + "{\"name\":\"operator\",\"value\":\"<=\"}," + + "{\"name\":\"threshold\",\"value\":\"0\"}]"; + + /** + * The reference of the customers table without its entity type. The type of a reference comes + * from the registry of entity types. This test does not load the registry and another test of + * the same run may, so {@link #withoutEntityType} takes the type out of what is compared. + */ + private static final String CUSTOMERS_TABLE = + "{\"id\":\"7cc39a8b-6fb0-313c-b68f-2dc9b46b50d5\",\"name\":\"customers\"," + + "\"fullyQualifiedName\":\"warehouse.sales.shop.customers\"," + + "\"displayName\":\"customers\",\"deleted\":false}"; + + private static final String CUSTOMER_BINDING = + "{\"conceptId\":\"25c48fe2-1541-3ad0-9724-3f720ced92d6\"," + + "\"assetId\":\"7cc39a8b-6fb0-313c-b68f-2dc9b46b50d5\",\"revision\":1}"; + + private static OntologyShapeCheckModel customers() { + return new OntologyShapeCheckModel(UNFILTERED_IDENTITY, POSTGRES); + } + + /** The parts of the one constraint, as the caller who may not view {@code hidden} reads them. */ + private static List parts( + final OntologyShapeCheckModel model, + final String type, + final OntologyShapeConstraint constraint, + final Set hidden) { + return shapes(model, type, hidden, constraint) + .getFirst() + .getConstraints() + .getFirst() + .getParts(); + } + + /** The parts with no entity type on the table reference of a check. */ + private static List withoutEntityType( + final List parts) { + parts.stream() + .filter(part -> part.getChecks() != null) + .flatMap(part -> part.getChecks().stream()) + .forEach(check -> check.getTable().setType(null)); + return parts; + } + + /** The answer for a caller who may not view the tables {@code hidden} and may view the rest. */ + private static List shapes( + final OntologyShapeCheckModel model, + final String type, + final Set hidden, + final OntologyShapeConstraint... constraints) { + return shapes(model, type, new Hidden(hidden, Set.of(), Set.of()), constraints); + } + + private static List shapes( + final OntologyShapeCheckModel model, + final String type, + final Hidden hidden, + final OntologyShapeConstraint... constraints) { + return OntologyShapeCheckAnswer.shapes( + model.facts(type), List.of(model.targeting(type, constraints)), hidden); + } + + private static OntologyShapeCheck check( + final OntologyShapeCheckModel model, + final String type, + final OntologyShapeConstraint constraint) { + return parts(model, type, constraint, Set.of()).getFirst().getChecks().getFirst(); + } + + private static String parameter(final OntologyShapeCheck check, final String name) { + return check.getParameterValues().stream() + .filter(parameter -> parameter.getName().equals(name)) + .map(TestCaseParameterValue::getValue) + .findFirst() + .orElseThrow(); + } + + private static String verdict(final OntologyShapeCheck check) { + return JsonUtils.pojoToJson(check.getParameterValues().subList(1, 4)); + } + + @Test + void minCountOneIsTheCustomQueryTestWhereTheRowsOfTheTableAreItsRecordsToo() { + final OntologyShapeCheckModel model = + customers().primaryKey("customers", "id").notNull("customers", "email"); + final OntologyShapeCheck check = + check(model, "Customer", model.on("customerEmail").withMinCount(1)); + assertEquals(CUSTOM_SQL, check.getTestDefinition()); + assertEquals(CUSTOMERS_LINK, check.getEntityLink()); + assertEquals( + """ + SELECT COUNT(*) AS violations + FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 + ) c""", + parameter(check, "sqlExpression")); + assertEquals(PASSES_AT_NO_VIOLATION, verdict(check)); + assertEquals(4, check.getParameterValues().size()); + } + + @Test + void inIsTheCustomQueryTestWhereTheColumnIsNeverNullAndTheRowsAreTheRecordsToo() { + final OntologyShapeCheckModel model = + customers().primaryKey("customers", "id").notNull("customers", "email"); + final OntologyShapeCheck check = + check(model, "Customer", model.on("customerEmail").withIn(literals("a", "b"))); + assertEquals(CUSTOM_SQL, check.getTestDefinition()); + assertEquals(CUSTOMERS_LINK, check.getEntityLink()); + assertEquals( + """ + SELECT COUNT(*) AS violations + FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email NOT IN ('a', 'b') + ) c""", + parameter(check, "sqlExpression")); + assertEquals(PASSES_AT_NO_VIOLATION, verdict(check)); + assertEquals(4, check.getParameterValues().size()); + } + + @Test + void rangeIsTheCustomQueryTestWhereTheRowsOfTheTableAreItsRecordsToo() { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel(COLUMN_RELATION, POSTGRES).primaryKey("orders", "id"); + final OntologyShapeCheck check = + check( + model, + "Order", + model.on("orderTotal").withMinInclusive(limit("0")).withMaxInclusive(limit("1000.5"))); + assertEquals(CUSTOM_SQL, check.getTestDefinition()); + assertEquals("<#E::table::warehouse.sales.shop.orders>", check.getEntityLink()); + assertEquals( + """ + SELECT COUNT(*) AS violations + FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND (t0.total < 0 OR t0.total > 1000.5) + ) c""", + parameter(check, "sqlExpression")); + assertEquals(PASSES_AT_NO_VIOLATION, verdict(check)); + assertEquals(4, check.getParameterValues().size()); + } + + @Test + void patternIsTheCustomQueryTestWithItsColonsEscapedInTheCountOnly() { + final OntologyShapeCheckModel model = customers(); + final OntologyShapeCheck check = + check(model, "Customer", model.on("customerEmail").withPattern("^[a-z]+:.$")); + assertEquals(CUSTOM_SQL, check.getTestDefinition()); + assertEquals(CUSTOMERS_LINK, check.getEntityLink()); + assertEquals(List.of(List.of("email")), check.getColumns()); + assertEquals( + """ + SELECT COUNT(*) AS violations + FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+\\:[^\\\\n\\\\r]$') + ) c""", + parameter(check, "sqlExpression")); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+:[^\\\\n\\\\r]$')""", + check.getInspectionQuery()); + assertEquals(PASSES_AT_NO_VIOLATION, verdict(check)); + assertEquals("[" + CUSTOMER_BINDING + "]", JsonUtils.pojoToJson(check.getReadBindings())); + } + + @Test + void aTestRunsItsCountWithColonsEscapedAndListsItsKeysAsAPersonReadsThem() { + final OntologyShapeCheckModel model = customers(); + assertEquals( + "[{\"part\":\"in\",\"outcome\":\"check\",\"checks\":[{" + + "\"identity\":\"5f601e0183676bea515c7d2a3fc65c264a4e6358b42df7a0382c8e9b80572854\"," + + "\"table\":" + + CUSTOMERS_TABLE + + ",\"columns\":[[\"email\"]]," + + "\"testDefinition\":\"tableCustomSQLQuery\"," + + "\"entityLink\":\"<#E::table::warehouse.sales.shop.customers>\"," + + "\"parameterValues\":[{\"name\":\"sqlExpression\",\"value\":\"" + + "SELECT COUNT(*) AS violations\\nFROM (\\n" + + " SELECT DISTINCT t0.id AS k0\\n FROM shop.customers t0\\n" + + " WHERE t0.id IS NOT NULL\\n AND t0.email NOT IN ('mailto\\\\:a', 'b')\\n) c\"}," + + "{\"name\":\"strategy\",\"value\":\"COUNT\"}," + + "{\"name\":\"operator\",\"value\":\"<=\"}," + + "{\"name\":\"threshold\",\"value\":\"0\"}]," + + "\"inspectionQuery\":\"SELECT DISTINCT t0.id AS k0\\nFROM shop.customers t0\\n" + + "WHERE t0.id IS NOT NULL\\n AND t0.email NOT IN ('mailto:a', 'b')\"," + + "\"readBindings\":[" + + CUSTOMER_BINDING + + "]}]}]", + JsonUtils.pojoToJson( + withoutEntityType( + parts( + model, + "Customer", + model.on("customerEmail").withIn(literals("mailto:a", "b")), + Set.of())))); + } + + @Test + void anAnswerWithoutATestSaysWhichKindItIsAndAReasonOnlyWhenItIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + assertEquals( + "[{\"part\":\"minCount\",\"outcome\":\"heldByMapping\"}," + + "{\"part\":\"pattern\",\"outcome\":\"notEnforceable\"," + + "\"reason\":\"patternNotPortable\"}]", + JsonUtils.pojoToJson( + parts( + model, + "Customer", + model.on("customerEmail").withMinCount(0).withPattern("^\\d+$"), + Set.of()))); + assertEquals( + "[{\"part\":\"maxCount\",\"outcome\":\"notMapped\"}]", + JsonUtils.pojoToJson( + parts( + model, + "Customer", + new OntologyShapeConstraint() + .withId("c2") + .withPath(URI.create("https://example.org/unfilteredIdentity#unbound")) + .withMaxCount(1), + Set.of()))); + } + + @Test + void aCheckIsNamedByWhatItChecksAndNotByAValueOfTheConstraint() { + final OntologyShapeCheckModel model = customers(); + final String listed = + check(model, "Customer", model.on("customerEmail").withIn(literals("a"))).getIdentity(); + assertEquals("5f601e0183676bea515c7d2a3fc65c264a4e6358b42df7a0382c8e9b80572854", listed); + assertEquals( + listed, + check(model, "Customer", model.on("customerEmail").withIn(literals("a", "b", "c"))) + .getIdentity()); + assertEquals( + "327d378c098bf5ae96b85be4b07fcc63093278a62dff2c38bb518f295604baf0", + check(model, "Customer", model.on("customerEmail").withMinCount(1)).getIdentity()); + } + + @Test + void aCheckOnALinkTableBelongsToItAndNamesTheRevisionOfEveryBindingItRead() { + final OntologyShapeCheckModel model = new OntologyShapeCheckModel(LINK_TABLE, POSTGRES); + final OntologyShapeCheck check = + check(model, "Order", model.on("contains").withClassIri(LINK_TABLE.iri("Product"))); + assertEquals( + "45a138d09a62daec111a6beb791f69f0d112a8e63be1f3e55fb9ef13500b145c", check.getIdentity()); + assertEquals("warehouse.sales.shop.order_items", check.getTable().getFullyQualifiedName()); + assertEquals("<#E::table::warehouse.sales.shop.order_items>", check.getEntityLink()); + assertEquals(List.of(List.of("product_sku")), check.getColumns()); + assertEquals( + "[{\"conceptId\":\"3709c2f7-5944-3e4d-b2da-78de8278487b\"," + + "\"assetId\":\"b5ad3863-fafc-3abc-8825-22d9088467a4\",\"revision\":1}," + + "{\"conceptId\":\"3709c2f7-5944-3e4d-b2da-78de8278487b\"," + + "\"assetId\":\"4a6b56cc-2fb6-31ef-8e8c-0cf153c56336\",\"revision\":1}," + + "{\"conceptId\":\"ad7613c7-65d8-3f2f-a0b6-17f1b0497611\"," + + "\"assetId\":\"9d471789-03f5-3b02-a136-5d5206dff661\",\"revision\":2}]", + JsonUtils.pojoToJson(check.getReadBindings())); + } + + @Test + void aConstraintOnAHiddenIdentityTableSaysOnlyHiddenForEachPart() { + final OntologyShapeCheckModel model = customers(); + final Set hidden = Set.of(model.mapping().id("customers")); + assertEquals( + "[{\"id\":\"c740db69-5948-3a3f-8958-af47e77417cb\",\"name\":\"shape\"," + + "\"severity\":\"Violation\",\"constraints\":[" + + "{\"id\":\"c1\",\"path\":\"https://example.org/unfilteredIdentity#customerEmail\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"hidden\"}," + + "{\"part\":\"in\",\"outcome\":\"hidden\"}]}," + + "{\"id\":\"c2\",\"path\":\"https://example.org/unfilteredIdentity#unbound\"," + + "\"parts\":[{\"part\":\"maxCount\",\"outcome\":\"hidden\"}]}]}]", + JsonUtils.pojoToJson( + shapes( + model, + "Customer", + hidden, + model.on("customerEmail").withMinCount(1).withIn(literals("a")), + new OntologyShapeConstraint() + .withId("c2") + .withPath(URI.create("https://example.org/unfilteredIdentity#unbound")) + .withMaxCount(1)))); + } + + @Test + void aConstraintAboutAHiddenPropertySaysOnlyHiddenForEachPartAndDoesNotNameTheProperty() { + final OntologyShapeCheckModel model = customers(); + final Hidden hidden = + new Hidden(Set.of(), Set.of(UNFILTERED_IDENTITY.iri("customerEmail")), Set.of()); + assertEquals( + "[{\"id\":\"c740db69-5948-3a3f-8958-af47e77417cb\",\"name\":\"shape\"," + + "\"severity\":\"Violation\",\"constraints\":[" + + "{\"id\":\"c1\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"hidden\"}," + + "{\"part\":\"in\",\"outcome\":\"hidden\"}]}," + + "{\"id\":\"c2\",\"path\":\"https://example.org/unfilteredIdentity#customerName\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"heldByMapping\"}]}]}]", + JsonUtils.pojoToJson( + shapes( + model, + "Customer", + hidden, + model.on("customerEmail").withMinCount(1).withIn(literals("a")), + model.on("customerName").withId("c2").withMinCount(0)))); + } + + @Test + void aHiddenPropertyOnAHiddenTableIsNotNamedEither() { + final OntologyShapeCheckModel model = customers(); + final Hidden hidden = + new Hidden( + Set.of(model.mapping().id("customers")), + Set.of(UNFILTERED_IDENTITY.iri("customerEmail")), + Set.of()); + assertEquals( + "[{\"id\":\"c1\",\"parts\":[{\"part\":\"maxCount\",\"outcome\":\"hidden\"}]}]", + JsonUtils.pojoToJson( + shapes(model, "Customer", hidden, model.on("customerEmail").withMaxCount(1)) + .getFirst() + .getConstraints())); + } + + @Test + void aHiddenTableThatHoldsOnePropertyHidesOnlyTheConstraintsOnThatProperty() { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel(REPEATED_CONTRIBUTION, POSTGRES); + final List shapes = + shapes( + model, + "Customer", + Set.of(model.mapping().id("customer_addresses")), + model.on("addressCity").withMaxCount(1).withIn(literals("London")), + model.on("customerName").withId("c2").withMinCount(0)); + assertEquals( + "[{\"id\":\"c1\",\"path\":\"https://example.org/repeatedContribution#addressCity\"," + + "\"parts\":[{\"part\":\"maxCount\",\"outcome\":\"hidden\"}," + + "{\"part\":\"in\",\"outcome\":\"hidden\"}]}," + + "{\"id\":\"c2\",\"path\":\"https://example.org/repeatedContribution#customerName\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"heldByMapping\"}]}]", + JsonUtils.pojoToJson(shapes.getFirst().getConstraints())); + } + + @Test + void aHiddenTableThatAJoinReachesHidesEveryPartOfTheRelation() { + final OntologyShapeCheckModel model = new OntologyShapeCheckModel(COLUMN_RELATION, POSTGRES); + final List shapes = + shapes( + model, + "Order", + Set.of(model.mapping().id("customers")), + model.on("placedBy").withMinCount(1).withClassIri(COLUMN_RELATION.iri("Customer")), + model.on("orderTotal").withId("c2").withMinCount(0)); + assertEquals( + "[{\"id\":\"c1\",\"path\":\"https://example.org/columnRelation#placedBy\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"hidden\"}," + + "{\"part\":\"class\",\"outcome\":\"hidden\"}]}," + + "{\"id\":\"c2\",\"path\":\"https://example.org/columnRelation#orderTotal\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"heldByMapping\"}]}]", + JsonUtils.pojoToJson(shapes.getFirst().getConstraints())); + } + + @Test + void aClassPartThatNamesAHiddenClassHidesEveryPartOfItsConstraintAndKeepsThePath() { + final OntologyShapeCheckModel model = new OntologyShapeCheckModel(LINK_TABLE, POSTGRES); + final Hidden hidden = new Hidden(Set.of(), Set.of(), Set.of(LINK_TABLE.iri("Product"))); + final List constraints = + shapes( + model, + "Order", + hidden, + model.on("contains").withMinCount(1).withClassIri(LINK_TABLE.iri("Product")), + model.on("orderChannel").withId("c2").withMinCount(0)) + .getFirst() + .getConstraints(); + assertEquals( + "[{\"id\":\"c1\",\"path\":\"https://example.org/linkTable#contains\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"hidden\"}," + + "{\"part\":\"class\",\"outcome\":\"hidden\"}]}," + + "{\"id\":\"c2\",\"path\":\"https://example.org/linkTable#orderChannel\"," + + "\"parts\":[{\"part\":\"minCount\",\"outcome\":\"heldByMapping\"}]}]", + JsonUtils.pojoToJson(constraints)); + } + + @Test + void aHiddenAnswerDoesNotTellHowManyAnswersTheTablesGave() { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel( + REPEATED_CONTRIBUTION, + POSTGRES, + List.of( + OntologyMappingShapes.identity( + "Customer", + "customers", + List.of("id"), + null, + OntologyMappingShapes.bound("customerName", "name")), + OntologyMappingShapes.contributing( + "Customer", + "customer_addresses", + List.of("customer_id"), + OntologyMappingShapes.bound("customerName", "city")))); + model.mapping().table("customer_addresses").getColumns().stream() + .filter(column -> column.getName().equals("city")) + .forEach(column -> column.setDataType(ColumnDataType.CHAR)); + final OntologyShapeConstraint pattern = model.on("customerName").withPattern("^[0-9]+$"); + assertEquals(2, parts(model, "Customer", pattern, Set.of()).size()); + assertEquals( + "[{\"part\":\"pattern\",\"outcome\":\"hidden\"}]", + JsonUtils.pojoToJson( + parts(model, "Customer", pattern, Set.of(model.mapping().id("customer_addresses"))))); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java new file mode 100644 index 000000000000..8bc2fb84813e --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckCompilerTest.java @@ -0,0 +1,1218 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.FILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.bound; +import static org.openmetadata.service.ontology.OntologyMappingShapes.contributing; +import static org.openmetadata.service.ontology.OntologyMappingShapes.data; +import static org.openmetadata.service.ontology.OntologyMappingShapes.identity; +import static org.openmetadata.service.ontology.OntologyMappingShapes.integer; +import static org.openmetadata.service.ontology.OntologyMappingShapes.table; +import static org.openmetadata.service.ontology.OntologyMappingShapes.text; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.FILTERED_TARGET; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.TWO_COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.limit; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literal; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literals; + +import java.net.URI; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyCheckProbe.FewerValues; +import org.openmetadata.service.ontology.OntologyCheckProbe.MoreValues; +import org.openmetadata.service.ontology.OntologyCheckProbe.NoRecord; +import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideList; +import org.openmetadata.service.ontology.OntologyCheckProbe.OutsideRange; +import org.openmetadata.service.ontology.OntologyCheckProbe.Unmatched; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyPartOutcome.Check; +import org.openmetadata.service.ontology.OntologyPartOutcome.HeldByMapping; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotEnforceable; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotMapped; +import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; +import org.openmetadata.service.ontology.OntologyRecordMapping.JoinPair; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.ontology.sql.TypedValue; + +/** + * Every row of the rule that compiles a shape constraint into data quality checks + * (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered), each with a literal mapping and + * the literal answer. + */ +class OntologyShapeCheckCompilerTest { + private static final String POSTGRES = "Postgres"; + private static final String XSD = "http://www.w3.org/2001/XMLSchema#"; + + private static OntologyShapeCheckModel customers() { + return new OntologyShapeCheckModel(UNFILTERED_IDENTITY, POSTGRES); + } + + /** The customers table with its key declared, so that its rows are its records. */ + private static OntologyShapeCheckModel simpleCustomers() { + return customers().primaryKey("customers", "id"); + } + + private static OntologyShapeCheckModel shape(final Shape shape) { + return new OntologyShapeCheckModel(shape, POSTGRES); + } + + private static OntologyShapeCheckModel customersWith(final BindingSpec... bindings) { + return new OntologyShapeCheckModel(UNFILTERED_IDENTITY, POSTGRES, List.of(bindings)); + } + + /** The customer class with its name bound in its identity table and in a contributing table. */ + private static OntologyShapeCheckModel nameInTwoTables() { + return new OntologyShapeCheckModel( + REPEATED_CONTRIBUTION, + POSTGRES, + List.of( + identity("Customer", "customers", List.of("id"), null, bound("customerName", "name")), + contributing( + "Customer", + "customer_addresses", + List.of("customer_id"), + bound("customerName", "city")))); + } + + private static OntologyShapeCheckModel customersOn(final String serviceType) { + return new OntologyShapeCheckModel(UNFILTERED_IDENTITY, serviceType); + } + + private static NotEnforceable refused(final OntologyShapeCheckReason reason) { + return new NotEnforceable(reason); + } + + private static T probe( + final Class kind, final TableCheck check) { + return assertInstanceOf(kind, check.probe()); + } + + private static Column column( + final OntologyShapeCheckModel model, final String table, final String name) { + return model.mapping().table(table).getColumns().stream() + .filter(column -> column.getName().equals(name)) + .findFirst() + .orElseThrow(); + } + + private static List tables(final List rows) { + return rows.stream().map(BindingRow::assetFqnHash).toList(); + } + + private static List sources(final List values) { + return values.stream().map(TypedValue::source).toList(); + } + + @Test + void minCountZeroIsHeldByAnyMapping() { + final OntologyShapeCheckModel simple = simpleCustomers(); + assertEquals( + new HeldByMapping(), simple.answer("Customer", simple.on("customerEmail").withMinCount(0))); + final OntologyShapeCheckModel filtered = shape(FILTERED_IDENTITY); + assertEquals( + new HeldByMapping(), filtered.answer("Person", filtered.on("personName").withMinCount(0))); + final OntologyShapeCheckModel linked = shape(LINK_TABLE); + assertEquals( + new HeldByMapping(), linked.answer("Order", linked.on("contains").withMinCount(0))); + } + + @Test + void minCountOneOnASubjectKeyColumnIsHeld() { + final BindingSpec nameIsTheKey = + identity("Customer", "customers", List.of("id"), null, bound("customerName", "id")); + final OntologyShapeCheckModel plain = customersWith(nameIsTheKey); + assertEquals( + new HeldByMapping(), plain.answer("Customer", plain.on("customerName").withMinCount(1))); + final OntologyShapeCheckModel simple = + customersWith(nameIsTheKey).primaryKey("customers", "id"); + assertEquals( + new HeldByMapping(), simple.answer("Customer", simple.on("customerName").withMinCount(1))); + } + + @Test + void minCountOneOnOneColumnCountsRecordsWithNoValueWhereTheRowsAreTheRecordsToo() { + final OntologyShapeCheckModel model = simpleCustomers().notNull("customers", "email"); + final TableCheck check = model.check("Customer", model.on("customerEmail").withMinCount(1)); + final FewerValues probe = probe(FewerValues.class, check); + assertEquals(1, probe.count()); + assertEquals(List.of(List.of("email")), probe.columns()); + assertNull(probe.reach().holder()); + assertEquals("customers", check.place().holder().table().getName()); + assertEquals(List.of(List.of("email")), check.columns()); + assertEquals(List.of("customers"), tables(check.read())); + } + + @Test + void minCountOneOffASimpleTableCountsRecordsWithNoValue() { + final OntologyShapeCheckModel undeclared = customers(); + final FewerValues noKey = + probe( + FewerValues.class, + undeclared.check("Customer", undeclared.on("customerEmail").withMinCount(1))); + assertEquals(1, noKey.count()); + assertEquals(List.of(List.of("email")), noKey.columns()); + assertNull(noKey.reach().holder()); + assertNull(noKey.reach().identity().filter()); + + final OntologyShapeCheckModel filtered = shape(FILTERED_IDENTITY).primaryKey("parties", "id"); + final FewerValues people = + probe( + FewerValues.class, filtered.check("Person", filtered.on("personName").withMinCount(1))); + assertEquals(OntologyRowFilterOperator.EQUALS, people.reach().identity().filter().operator()); + } + + @Test + void minCountOneOnAContributingColumnNamedLikeAKeyColumnOfTheIdentityTableIsNotHeld() { + final Shape keyNamedTwice = + new Shape( + "keyNamedTwice", + List.of( + table("customers", List.of(integer("customer_id"), text("name"))), + table("addresses", List.of(integer("customer_id"), text("city")))), + List.of("Customer"), + List.of( + data("customerName", true, "Customer"), data("addressOwner", false, "Customer")), + List.of( + identity( + "Customer", + "customers", + List.of("customer_id"), + null, + bound("customerName", "name")), + contributing( + "Customer", + "addresses", + List.of("customer_id"), + bound("addressOwner", "customer_id"))), + List.of()); + final OntologyShapeCheckModel model = shape(keyNamedTwice); + final TableCheck check = model.check("Customer", model.on("addressOwner").withMinCount(1)); + final FewerValues probe = probe(FewerValues.class, check); + assertEquals("addresses", check.place().holder().table().getName()); + assertEquals(List.of(List.of("customer_id")), probe.columns()); + assertEquals("addresses", probe.reach().holder().table().table().getName()); + assertEquals(1, probe.count()); + } + + @Test + void minCountOneOnAContributingTableJoinsItToTheRecords() { + final OntologyShapeCheckModel model = shape(COMPOSITE_KEY); + final TableCheck check = model.check("Account", model.on("accountTier").withMinCount(1)); + final FewerValues probe = probe(FewerValues.class, check); + assertEquals("crm_customer_profile", check.place().holder().table().getName()); + assertEquals("crm_customer_profile", probe.reach().holder().table().table().getName()); + assertEquals( + List.of( + new JoinPair(List.of("tenant_id"), List.of("tenant")), + new JoinPair(List.of("customer_id"), List.of("customer"))), + probe.reach().keyPairs()); + assertEquals(List.of("crm_customers", "crm_customer_profile"), tables(check.read())); + } + + @Test + void minCountOneOnARelationOfSeveralColumnsIsGeneratedEvenOnASimpleTable() { + final OntologyShapeCheckModel model = shape(TWO_COLUMN_RELATION).primaryKey("shipments", "id"); + final FewerValues probe = + probe(FewerValues.class, model.check("Shipment", model.on("shippedTo").withMinCount(1))); + assertEquals(1, probe.count()); + assertEquals(List.of(List.of("tenant"), List.of("customer")), probe.columns()); + } + + @Test + void minCountAboveOneCountsDistinctValuesEvenOnASimpleTable() { + final OntologyShapeCheckModel simple = simpleCustomers(); + assertEquals( + 2, + probe( + FewerValues.class, + simple.check("Customer", simple.on("customerEmail").withMinCount(2))) + .count()); + final OntologyShapeCheckModel repeated = shape(REPEATED_CONTRIBUTION); + assertEquals( + 3, + probe( + FewerValues.class, + repeated.check("Customer", repeated.on("addressCity").withMinCount(3))) + .count()); + } + + @Test + void maxCountOfAtLeastOneIsHeldOnASimpleTable() { + final OntologyShapeCheckModel model = simpleCustomers(); + assertEquals( + new HeldByMapping(), model.answer("Customer", model.on("customerEmail").withMaxCount(1))); + assertEquals( + new HeldByMapping(), model.answer("Customer", model.on("customerEmail").withMaxCount(3))); + } + + @Test + void maxCountOfAtLeastOneIsHeldWhereADeclaredKeyLiesInsideTheSubjectKey() { + final OntologyShapeCheckModel contributing = + shape(REPEATED_CONTRIBUTION).uniqueKey("customer_addresses", "customer_id"); + assertEquals( + new HeldByMapping(), + contributing.answer("Customer", contributing.on("addressCity").withMaxCount(1))); + final OntologyShapeCheckModel filtered = shape(FILTERED_IDENTITY).primaryKey("parties", "id"); + assertEquals( + new HeldByMapping(), filtered.answer("Person", filtered.on("personName").withMaxCount(1))); + } + + @Test + void maxCountWithoutSuchAKeyCountsDistinctValues() { + final OntologyShapeCheckModel undeclared = shape(REPEATED_CONTRIBUTION); + final TableCheck check = + undeclared.check("Customer", undeclared.on("addressCity").withMaxCount(1)); + final MoreValues probe = probe(MoreValues.class, check); + assertEquals(1, probe.count()); + assertEquals(List.of(List.of("city")), probe.columns()); + assertEquals("customer_addresses", check.place().holder().table().getName()); + + final OntologyShapeCheckModel widerKey = + shape(REPEATED_CONTRIBUTION).uniqueKey("customer_addresses", "customer_id", "city"); + assertEquals( + 1, + probe( + MoreValues.class, + widerKey.check("Customer", widerKey.on("addressCity").withMaxCount(1))) + .count()); + } + + @Test + void maxCountIsNotHeldByAPrimaryKeyThatReachesOutsideTheSubjectKey() { + final OntologyShapeCheckModel model = customers().primaryKey("customers", "id", "name"); + final TableCheck check = model.check("Customer", model.on("customerEmail").withMaxCount(1)); + final MoreValues probe = probe(MoreValues.class, check); + assertEquals(1, probe.count()); + assertEquals(List.of(List.of("email")), probe.columns()); + assertEquals("customers", check.place().holder().table().getName()); + } + + @Test + void maxCountZeroIsGeneratedEvenOnASimpleTable() { + final OntologyShapeCheckModel model = simpleCustomers(); + assertEquals( + 0, + probe(MoreValues.class, model.check("Customer", model.on("customerEmail").withMaxCount(0))) + .count()); + } + + @Test + void inOnAColumnThatIsNeverNullIsGeneratedWhereTheRowsAreTheRecordsToo() { + final OntologyShapeCheckModel text = simpleCustomers().notNull("customers", "email"); + final TableCheck check = + text.check( + "Customer", text.on("customerEmail").withIn(literals("ada@example.org", "it's \"x\""))); + final OutsideList listed = probe(OutsideList.class, check); + assertEquals(List.of("email"), listed.column()); + assertEquals(List.of("ada@example.org", "it's \"x\""), sources(listed.allowed())); + assertEquals(List.of("customers"), tables(check.read())); + + final OntologyShapeCheckModel key = + customersWith( + identity("Customer", "customers", List.of("id"), null, bound("customerName", "id"))) + .primaryKey("customers", "id") + .notNull("customers", "id"); + final OutsideList numbers = + probe( + OutsideList.class, + key.check("Customer", key.on("customerName").withIn(literals("1", "2")))); + assertEquals(List.of("id"), numbers.column()); + assertEquals(List.of("1", "2"), sources(numbers.allowed())); + } + + @Test + void inOnAColumnThatMayHoldNullIsGenerated() { + final OntologyShapeCheckModel model = simpleCustomers(); + final OutsideList probe = + probe( + OutsideList.class, + model.check("Customer", model.on("customerEmail").withIn(literals("a", "b")))); + assertEquals(List.of("email"), probe.column()); + assertEquals(List.of("a", "b"), sources(probe.allowed())); + } + + @Test + void inOffASimpleTableIsGenerated() { + final OntologyShapeCheckModel filtered = + shape(FILTERED_IDENTITY).primaryKey("parties", "id").notNull("parties", "name"); + final OutsideList people = + probe( + OutsideList.class, + filtered.check("Person", filtered.on("personName").withIn(literals("Ada")))); + assertEquals(List.of("name"), people.column()); + + final OntologyShapeCheckModel linked = shape(LINK_TABLE); + final TableCheck quantity = + linked.check("Order", linked.on("itemQuantity").withIn(literals("1", "2"))); + assertEquals("order_items", quantity.place().holder().table().getName()); + assertEquals( + "order_items", + probe(OutsideList.class, quantity).reach().holder().table().table().getName()); + } + + @Test + void inOnADecimalColumnIsGeneratedEvenOnASimpleTable() { + final OntologyShapeCheckModel model = + shape(COLUMN_RELATION).primaryKey("orders", "id").notNull("orders", "total"); + final OutsideList probe = + probe( + OutsideList.class, + model.check("Order", model.on("orderTotal").withIn(literals("9.99", "20")))); + assertEquals(List.of("9.99", "20"), sources(probe.allowed())); + } + + @Test + void rangeOnANumericColumnIsGeneratedWhereTheRowsAreTheRecordsToo() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION).primaryKey("orders", "id"); + final OutsideRange both = + probe( + OutsideRange.class, + model.check( + "Order", + model + .on("orderTotal") + .withMinInclusive(limit("0")) + .withMaxInclusive(limit("1000.5")))); + assertEquals(List.of("total"), both.column()); + assertEquals("0", both.min().orElseThrow().source()); + assertEquals("1000.5", both.max().orElseThrow().source()); + + final OutsideRange upper = + probe( + OutsideRange.class, + model.check("Order", model.on("orderTotal").withMaxInclusive(limit("250")))); + assertEquals(Optional.empty(), upper.min()); + assertEquals("250", upper.max().orElseThrow().source()); + } + + @Test + void rangeOffASimpleTableIsGenerated() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + final OutsideRange probe = + probe( + OutsideRange.class, + model.check( + "Order", + model.on("orderTotal").withMinInclusive(limit("0")).withMaxInclusive(limit("5")))); + assertEquals(List.of("total"), probe.column()); + assertEquals("0", probe.min().orElseThrow().source()); + assertEquals("5", probe.max().orElseThrow().source()); + } + + @Test + void rangeOnATextColumnIsNotEnforceable() { + final OntologyShapeCheckModel model = simpleCustomers(); + assertEquals( + refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED), + model.answer("Customer", model.on("customerEmail").withMinInclusive(limit("a")))); + } + + @Test + void patternOnATextColumnCountsRecordsWithAValueThatDoesNotMatch() { + final OntologyShapeCheckModel model = customers(); + final String pattern = "^[a-z]+@example\\.org$"; + final TableCheck check = + model.check("Customer", model.on("customerEmail").withPattern(pattern)); + final Unmatched probe = probe(Unmatched.class, check); + assertEquals(SqlEngineFamily.POSTGRES, probe.reach().family()); + assertEquals(List.of("email"), probe.column()); + assertEquals(pattern, probe.pattern().source()); + assertNull(probe.reach().holder()); + assertEquals("customers", check.place().holder().table().getName()); + assertEquals(List.of(List.of("email")), check.columns()); + assertEquals(List.of("customers"), tables(check.read())); + } + + @Test + void patternOnAContributingTableJoinsItToTheRecords() { + final OntologyShapeCheckModel model = shape(COMPOSITE_KEY); + final TableCheck check = model.check("Account", model.on("accountTier").withPattern("^a$")); + final Unmatched probe = probe(Unmatched.class, check); + assertEquals(List.of("tier"), probe.column()); + assertEquals("crm_customer_profile", probe.reach().holder().table().table().getName()); + assertEquals(List.of("crm_customers", "crm_customer_profile"), tables(check.read())); + } + + @Test + void patternWritesItsWildcardAsEveryCharacterButALineBreak() { + final OntologyShapeCheckModel model = customers(); + final Unmatched probe = + probe( + Unmatched.class, + model.check("Customer", model.on("customerEmail").withPattern("^1.2\\.3$"))); + assertEquals("^1[^\\n\\r]2\\.3$", probe.pattern().source()); + } + + @ParameterizedTest + @EnumSource(value = SqlEngineFamily.class, names = "POSTGRES", mode = EnumSource.Mode.EXCLUDE) + void patternOnAnyOtherEngineFamilyIsNotEnforceable(final SqlEngineFamily family) { + final OntologyShapeCheckModel model = + customersOn(OntologyStatementGoldens.SERVICE_TYPES.get(family)); + assertEquals( + refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED), + model.answer("Customer", model.on("customerEmail").withPattern("^a$"))); + } + + @ParameterizedTest + @ValueSource( + strings = { + "Timescale", + "Presto", + "Athena", + "MariaDB", + "SingleStore", + "Doris", + "StarRocks", + "UnityCatalog", + "Hive", + "Impala", + "Iomete", + "AzureSQL", + "Synapse", + "MicrosoftFabric", + "Oracle" + }) + void patternOnAnyOtherServiceTypeIsNotEnforceable(final String serviceType) { + final OntologyShapeCheckModel model = customersOn(serviceType).primaryKey("customers", "id"); + assertEquals( + refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED), + model.answer("Customer", model.on("customerEmail").withPattern("^a$"))); + } + + @Test + void patternOnMysqlIsNotEnforceableWhateverThePatternAndTheColumn() { + final OntologyShapeCheckModel model = customersOn("Mysql").primaryKey("customers", "id"); + final NotEnforceable unsupported = refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED); + assertEquals( + unsupported, model.answer("Customer", model.on("customerEmail").withPattern("^[0-9]+$"))); + assertEquals( + unsupported, model.answer("Customer", model.on("customerEmail").withPattern("^1.2$"))); + assertEquals( + unsupported, model.answer("Customer", model.on("customerEmail").withPattern("\\d+"))); + column(model, "customers", "email").withDataType(ColumnDataType.INT); + assertEquals( + unsupported, model.answer("Customer", model.on("customerEmail").withPattern("^[0-9]+$"))); + } + + @Test + void patternOutsideTheCommonCoreIsNotEnforceable() { + final OntologyShapeCheckModel model = simpleCustomers(); + assertEquals( + refused(OntologyShapeCheckReason.PATTERN_NOT_PORTABLE), + model.answer("Customer", model.on("customerEmail").withPattern("^\\d+$"))); + } + + @Test + void patternThatIsTooLongOnceWrittenIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + assertEquals( + 702, + probe( + Unmatched.class, + model.check( + "Customer", model.on("customerEmail").withPattern("^" + ".".repeat(100) + "$"))) + .pattern() + .source() + .length()); + assertEquals( + refused(OntologyShapeCheckReason.PATTERN_NOT_PORTABLE), + model.answer( + "Customer", model.on("customerEmail").withPattern("^" + ".".repeat(147) + "$"))); + } + + @Test + void patternOnAColumnThatIsNotTextIsNotEnforceable() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION).primaryKey("orders", "id"); + assertEquals( + refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED), + model.answer("Order", model.on("orderTotal").withPattern("^[0-9]+$"))); + } + + @Test + void patternOnAColumnThatPadsItsValuesIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + column(model, "customers", "email").withDataType(ColumnDataType.CHAR); + assertEquals( + refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED), + model.answer("Customer", model.on("customerEmail").withPattern("^[a-z]+$"))); + } + + @ParameterizedTest + @CsvSource({"VARCHAR", "TEXT", "STRING", "MEDIUMTEXT", "ENUM"}) + void patternIsMatchedOnEveryOtherTextType(final ColumnDataType type) { + final OntologyShapeCheckModel model = customers(); + column(model, "customers", "email").withDataType(type); + assertEquals( + "^[a-z]+$", + probe( + Unmatched.class, + model.check("Customer", model.on("customerEmail").withPattern("^[a-z]+$"))) + .pattern() + .source()); + } + + @Test + void classCountsValuesThatAreNoRecordOfTheNamedClass() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION).primaryKey("orders", "id"); + final TableCheck check = + model.check("Order", model.on("placedBy").withClassIri(COLUMN_RELATION.iri("Customer"))); + final NoRecord probe = probe(NoRecord.class, check); + assertEquals(List.of(new JoinPair(List.of("customer_id"), List.of("id"))), probe.on()); + assertEquals("customers", probe.target().table().table().getName()); + assertNull(probe.target().filter()); + assertEquals(List.of(List.of("customer_id")), check.columns()); + assertEquals(List.of("orders", "customers"), tables(check.read())); + } + + @Test + void classOnALinkTableBelongsToTheLinkTableAndNamesEveryBindingItRead() { + final OntologyShapeCheckModel model = shape(LINK_TABLE); + final TableCheck check = + model.check("Order", model.on("contains").withClassIri(LINK_TABLE.iri("Product"))); + final NoRecord probe = probe(NoRecord.class, check); + assertEquals("order_items", check.place().holder().table().getName()); + assertEquals(List.of(new JoinPair(List.of("product_sku"), List.of("sku"))), probe.on()); + assertEquals(List.of("orders", "order_items", "products"), tables(check.read())); + assertEquals( + List.of( + model.mapping().id("Order"), + model.mapping().id("Order"), + model.mapping().id("Product")), + check.read().stream().map(BindingRow::conceptId).toList()); + } + + @Test + void classCarriesTheFilterOfTheTargetBinding() { + final OntologyShapeCheckModel model = shape(FILTERED_TARGET); + final NoRecord probe = + probe( + NoRecord.class, + model.check( + "Membership", model.on("heldBy").withClassIri(FILTERED_TARGET.iri("Person")))); + assertEquals(List.of("kind"), probe.target().filter().column()); + assertEquals("person", probe.target().filter().values().getFirst().source()); + } + + @Test + void classIsNotEnforceableWhenASubclassSharesAFilteredTargetTable() { + final OntologyShapeCheckModel filtered = + shape(FILTERED_TARGET).shareTableWithSubclass("Person"); + assertEquals( + refused(OntologyShapeCheckReason.SUBCLASS_ON_JOIN_TABLE), + filtered.answer( + "Membership", filtered.on("heldBy").withClassIri(FILTERED_TARGET.iri("Person")))); + + final OntologyShapeCheckModel unfiltered = + shape(COLUMN_RELATION).shareTableWithSubclass("Customer"); + assertInstanceOf( + Check.class, + unfiltered.answer( + "Order", unfiltered.on("placedBy").withClassIri(COLUMN_RELATION.iri("Customer")))); + } + + @Test + void classOnADataPropertyIsNotEnforceable() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + assertEquals( + refused(OntologyShapeCheckReason.NOT_A_RELATION), + model.answer( + "Order", model.on("orderTotal").withClassIri(COLUMN_RELATION.iri("Customer")))); + } + + @Test + void classWhoseIdentityTableIsNotWhereTheJoinArrivesIsNotEnforceable() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + assertEquals( + refused(OntologyShapeCheckReason.TARGET_CLASS_NOT_ON_JOIN), + model.answer("Order", model.on("placedBy").withClassIri(COLUMN_RELATION.iri("Order")))); + assertEquals( + refused(OntologyShapeCheckReason.TARGET_CLASS_NOT_ON_JOIN), + model.answer("Order", model.on("placedBy").withClassIri(COLUMN_RELATION.iri("Unknown")))); + } + + @ParameterizedTest + @CsvSource({"INFERRED,JOIN_NOT_CONFIRMED", ",NO_JOIN"}) + void relationWithoutAConfirmedJoinIsNotEnforceable( + final OntologyJoinStatus status, final OntologyShapeCheckReason reason) { + final JoinSpec join = + status == null + ? null + : new JoinSpec("customers", status, List.of("customer_id"), List.of("id")); + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel( + COLUMN_RELATION, + POSTGRES, + List.of( + COLUMN_RELATION.binding("Customer", "customers"), + identity( + "Order", + "orders", + List.of("id"), + null, + new ColumnBindingSpec("placedBy", "customer_id", join)))); + final OntologyShapeConstraint constraint = + model + .on("placedBy") + .withMinCount(1) + .withMaxCount(1) + .withClassIri(COLUMN_RELATION.iri("Customer")); + assertEquals( + List.of(refused(reason), refused(reason), refused(reason)), + model.answers("Order", constraint)); + assertEquals(new HeldByMapping(), model.answer("Order", model.on("placedBy").withMinCount(0))); + } + + @Test + void relationTheClassDoesNotBindIsBoundOnItsInverseOrNotMapped() { + final OntologyShapeCheckModel inverse = shape(COLUMN_RELATION).bindOnInverse("placedBy"); + assertEquals( + List.of( + refused(OntologyShapeCheckReason.BOUND_ON_INVERSE), + refused(OntologyShapeCheckReason.BOUND_ON_INVERSE)), + inverse.answers("Customer", inverse.on("placedBy").withMinCount(1).withMaxCount(5))); + final OntologyShapeCheckModel unbound = shape(COLUMN_RELATION); + assertEquals( + new NotMapped(), unbound.answer("Customer", unbound.on("placedBy").withMinCount(1))); + } + + @Test + void valuePartsOnARelationAreNotEnforceable() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + final OntologyShapeConstraint constraint = + model + .on("placedBy") + .withDatatypeIri(URI.create(XSD + "integer")) + .withMinInclusive(limit("1")) + .withIn(literals("1")) + .withPattern("^1$"); + final NotEnforceable notData = refused(OntologyShapeCheckReason.NOT_A_DATA_PROPERTY); + assertEquals(List.of(notData, notData, notData, notData), model.answers("Order", constraint)); + } + + @ParameterizedTest + @CsvSource({ + "Postgres,BOOLEAN,,boolean", + "Redshift,BOOLEAN,,boolean", + "Trino,BOOLEAN,,boolean", + "Clickhouse,BOOLEAN,,boolean", + "BigQuery,BOOLEAN,,boolean", + "Snowflake,BOOLEAN,,boolean", + "Databricks,BOOLEAN,,boolean", + "Postgres,TINYINT,,integer", + "Postgres,SMALLINT,,integer", + "Postgres,INT,,integer", + "Mysql,INT,,integer", + "Mssql,BIGINT,,integer", + "Databricks,BIGINT,,integer", + "Snowflake,BYTEINT,,integer", + "StarRocks,LARGEINT,,integer", + "Mysql,DECIMAL,0,integer", + "Snowflake,NUMERIC,0,integer", + "Databricks,DECIMAL,0,integer", + "Postgres,BIGINT,,decimal", + "Databricks,INT,,decimal", + "Mysql,DECIMAL,2,decimal", + "Mssql,NUMERIC,,decimal", + "BigQuery,NUMERIC,2,decimal", + "Postgres,FLOAT,,double", + "Mysql,FLOAT,,double", + "Mssql,FLOAT,,double", + "Databricks,FLOAT,,double", + "BigQuery,DATE,,date", + "Mssql,DATE,,date", + "BigQuery,TIME,,time", + "Mssql,TIME,,time", + "BigQuery,TIMESTAMP,,dateTime", + "BigQuery,DATETIME,,dateTime", + "Mssql,DATETIME,,dateTime", + "Synapse,DATETIME,,dateTime" + }) + void datatypeIsHeldWhereTheEngineStoresNothingElseInTheColumnType( + final String serviceType, + final ColumnDataType type, + final Integer scale, + final String datatype) { + final OntologyShapeCheckModel model = customersOn(serviceType); + column(model, "customers", "email").withDataType(type).withScale(scale); + assertEquals( + new HeldByMapping(), + model.answer( + "Customer", model.on("customerEmail").withDatatypeIri(URI.create(XSD + datatype)))); + } + + /** A 64-bit column is named FLOAT on some engines, so no column holds only 32-bit numbers. */ + @ParameterizedTest + @CsvSource({"Postgres,FLOAT", "Mysql,FLOAT", "Mssql,FLOAT", "Snowflake,FLOAT", "Postgres,DOUBLE"}) + void floatIsHeldOnNoColumn(final String serviceType, final ColumnDataType type) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), datatype(serviceType, type, "float")); + } + + /** DOUBLE also names a decimal floating-point type. */ + @ParameterizedTest + @ValueSource(strings = {"Postgres", "Mysql", "Snowflake", "BigQuery", "Mssql"}) + void doubleIsNotHeldOnADoubleColumn(final String serviceType) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), + datatype(serviceType, ColumnDataType.DOUBLE, "double")); + } + + /** The MySQL family stores a time of 25:00:00 and a negative one. */ + @ParameterizedTest + @ValueSource(strings = {"Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"}) + void timeIsNotHeldOnTheMysqlFamily(final String serviceType) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), + datatype(serviceType, ColumnDataType.TIME, "time")); + } + + /** Postgres stores NaN in a fixed-point column. */ + @ParameterizedTest + @CsvSource({ + "Postgres,DECIMAL,2,decimal", + "Postgres,NUMERIC,2,decimal", + "Postgres,NUMERIC,,decimal", + "Postgres,DECIMAL,0,integer", + "Postgres,NUMERIC,0,integer", + "Timescale,NUMERIC,0,integer", + "Timescale,DECIMAL,2,decimal" + }) + void fixedPointIsNotHeldOnThePostgresFamily( + final String serviceType, + final ColumnDataType type, + final Integer scale, + final String datatype) { + final OntologyShapeCheckModel model = customersOn(serviceType); + column(model, "customers", "email").withDataType(type).withScale(scale); + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), + model.answer( + "Customer", model.on("customerEmail").withDatatypeIri(URI.create(XSD + datatype)))); + } + + /** Postgres stores infinity in a date and a timestamp, and its time can carry an offset. */ + @ParameterizedTest + @CsvSource({ + "Postgres,DATE,date", + "Postgres,TIMESTAMP,dateTime", + "Postgres,TIMESTAMPZ,dateTime", + "Postgres,DATETIME,dateTime", + "Postgres,TIME,time", + "Timescale,DATE,date", + "Timescale,TIMESTAMP,dateTime" + }) + void datesAndTimesAreNotHeldOnThePostgresFamily( + final String serviceType, final ColumnDataType type, final String datatype) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), datatype(serviceType, type, datatype)); + } + + /** The MySQL family stores the zero date. */ + @ParameterizedTest + @CsvSource({ + "Mysql,DATE,date", + "Mysql,DATETIME,dateTime", + "Mysql,TIMESTAMP,dateTime", + "MariaDB,DATE,date", + "MariaDB,DATETIME,dateTime", + "MariaDB,TIMESTAMP,dateTime" + }) + void datesAreNotHeldOnTheMysqlFamily( + final String serviceType, final ColumnDataType type, final String datatype) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), datatype(serviceType, type, datatype)); + } + + /** A boolean of the MySQL family is a number from -128 to 127, and T-SQL has no boolean. */ + @ParameterizedTest + @ValueSource(strings = {"Mysql", "MariaDB", "SingleStore", "Mssql", "AzureSQL"}) + void booleanIsNotHeldWhereTheEngineHasNoBooleanType(final String serviceType) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), + datatype(serviceType, ColumnDataType.BOOLEAN, "boolean")); + } + + /** Every text type stores control characters, which are no characters of xsd:string. */ + @ParameterizedTest + @CsvSource({ + "Postgres,VARCHAR", + "Postgres,CHAR", + "Postgres,TEXT", + "Postgres,ENUM", + "Mysql,MEDIUMTEXT", + "Snowflake,STRING", + "Mssql,VARCHAR" + }) + void stringIsHeldOnNoColumn(final String serviceType, final ColumnDataType type) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), datatype(serviceType, type, "string")); + } + + /** + * The lines the table leaves out for a reason of their own: a decimal that the catalog names + * INT, a row version that it names TIMESTAMP or NUMBER, and the engines whose dates and times + * were not read. + */ + @ParameterizedTest + @CsvSource({ + "Databricks,INT,integer", + "Hive,INT,integer", + "Mssql,TIMESTAMP,dateTime", + "Mssql,NUMBER,decimal", + "Postgres,NUMBER,decimal", + "Snowflake,NUMBER,integer", + "Snowflake,DATE,date", + "Trino,TIMESTAMP,dateTime", + "Databricks,DATE,date", + "Redshift,TIME,time", + "Clickhouse,DATETIME,dateTime", + "Mssql,TIMESTAMPZ,dateTime" + }) + void datatypeIsNotHeldWhereTheCatalogTypeNamesSomethingElseOrWasNotRead( + final String serviceType, final ColumnDataType type, final String datatype) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), datatype(serviceType, type, datatype)); + } + + @ParameterizedTest + @CsvSource({ + "Oracle,INT,integer", + "Oracle,DATE,date", + "Db2,DOUBLE,double", + "Db2,BOOLEAN,boolean", + "Teradata,FLOAT,double" + }) + void datatypeIsHeldOnNoServiceTypeWithoutAnEngineFamily( + final String serviceType, final ColumnDataType type, final String datatype) { + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), datatype(serviceType, type, datatype)); + } + + @ParameterizedTest + @CsvSource({ + "Postgres,VARCHAR,,integer", + "Postgres,INT,,boolean", + "Mysql,DECIMAL,2,integer", + "Mysql,DECIMAL,,integer", + "Postgres,BIT,,boolean", + "BigQuery,TIMESTAMP,,date", + "BigQuery,DATE,,dateTime", + "Mssql,FLOAT,,decimal" + }) + void datatypeThatTheColumnTypeCanBreakIsNotEnforceable( + final String serviceType, + final ColumnDataType type, + final Integer scale, + final String datatype) { + final OntologyShapeCheckModel model = customersOn(serviceType); + column(model, "customers", "email").withDataType(type).withScale(scale); + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_MISMATCH), + model.answer( + "Customer", model.on("customerEmail").withDatatypeIri(URI.create(XSD + datatype)))); + } + + /** The answer for a datatype on a column of the type, with no scale, on a service type. */ + private static OntologyPartOutcome datatype( + final String serviceType, final ColumnDataType type, final String datatype) { + final OntologyShapeCheckModel model = customersOn(serviceType); + column(model, "customers", "email").withDataType(type); + return model.answer( + "Customer", model.on("customerEmail").withDatatypeIri(URI.create(XSD + datatype))); + } + + @Test + void datatypeOutsideTheSupportedOnesIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + assertEquals( + refused(OntologyShapeCheckReason.DATATYPE_NOT_SUPPORTED), + model.answer( + "Customer", model.on("customerEmail").withDatatypeIri(URI.create(XSD + "anyURI")))); + } + + @Test + void propertyBoundInSeveralTablesIsCheckedOncePerTable() { + final OntologyShapeCheckModel model = nameInTwoTables(); + final Check check = + assertInstanceOf( + Check.class, model.answer("Customer", model.on("customerName").withIn(literals("a")))); + assertEquals( + List.of("customers", "customer_addresses"), + check.checks().stream().map(one -> one.place().holder().table().getName()).toList()); + assertEquals( + List.of(List.of(List.of("name")), List.of(List.of("city"))), + check.checks().stream().map(TableCheck::columns).toList()); + } + + @Test + void countsOverSeveralTablesAreNotEnforceable() { + final OntologyShapeCheckModel model = nameInTwoTables(); + final NotEnforceable several = refused(OntologyShapeCheckReason.SEVERAL_TABLES); + assertEquals( + List.of(several, several), + model.answers("Customer", model.on("customerName").withMinCount(1).withMaxCount(1))); + assertEquals( + new HeldByMapping(), model.answer("Customer", model.on("customerName").withMinCount(0))); + } + + @Test + void tablesThatDoNotAgreeGetOneAnswerEach() { + final OntologyShapeCheckModel model = nameInTwoTables(); + column(model, "customer_addresses", "city").withDataType(ColumnDataType.CHAR); + final List answers = + model.answers("Customer", model.on("customerName").withPattern("^[0-9]+$")); + assertEquals(2, answers.size()); + final Check check = assertInstanceOf(Check.class, answers.getFirst()); + assertEquals( + List.of("customers"), + check.checks().stream().map(one -> one.place().holder().table().getName()).toList()); + assertEquals(refused(OntologyShapeCheckReason.COLUMN_TYPE_NOT_SUPPORTED), answers.getLast()); + } + + @Test + void literalThatDoesNotParseAsTheColumnTypeIsNotEnforceable() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + final NotEnforceable misfit = refused(OntologyShapeCheckReason.VALUE_DOES_NOT_FIT_COLUMN); + assertEquals( + misfit, model.answer("Order", model.on("orderTotal").withIn(literals("1", "many")))); + assertEquals( + misfit, model.answer("Order", model.on("orderTotal").withMaxInclusive(limit("1e3")))); + } + + @Test + void literalWithALanguageTagIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + final OntologyShapeValue tagged = + new OntologyShapeValue() + .withLiteral( + new OntologyLiteral() + .withValue("hello") + .withDatatypeIri( + URI.create("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"))); + assertEquals( + refused(OntologyShapeCheckReason.VALUE_DOES_NOT_FIT_COLUMN), + model.answer("Customer", model.on("customerEmail").withIn(List.of(tagged)))); + } + + @Test + void listThatNamesARecordIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + final OntologyShapeValue named = + new OntologyShapeValue().withIri(URI.create("https://example.org/records/1")); + assertEquals( + refused(OntologyShapeCheckReason.VALUES_ARE_RECORDS), + model.answer("Customer", model.on("customerEmail").withIn(List.of(literal("a"), named)))); + } + + @Test + void listOfMoreThanAThousandValuesIsNotEnforceable() { + final OntologyShapeCheckModel model = customers(); + final List thousand = + IntStream.range(0, 1000).mapToObj(index -> literal("v" + index)).toList(); + assertEquals( + 1000, + probe( + OutsideList.class, + model.check("Customer", model.on("customerEmail").withIn(thousand))) + .allowed() + .size()); + final List oneMore = + IntStream.range(0, 1001).mapToObj(index -> literal("v" + index)).toList(); + assertEquals( + refused(OntologyShapeCheckReason.TOO_MANY_VALUES), + model.answer("Customer", model.on("customerEmail").withIn(oneMore))); + } + + @Test + void columnThatLeftTheTableIsNotEnforceable() { + final OntologyShapeCheckModel value = simpleCustomers(); + value.mapping().table("customers").getColumns().removeIf(c -> c.getName().equals("email")); + final NotEnforceable missing = refused(OntologyShapeCheckReason.COLUMN_MISSING); + assertEquals( + List.of(missing, missing, missing), + value.answers( + "Customer", + value + .on("customerEmail") + .withMinCount(1) + .withDatatypeIri(URI.create(XSD + "string")) + .withIn(literals("a")))); + + final OntologyShapeCheckModel key = customers(); + key.mapping().table("customers").getColumns().removeIf(c -> c.getName().equals("id")); + assertEquals(missing, key.answer("Customer", key.on("customerEmail").withMinCount(1))); + } + + @Test + void tableInAnotherDatabaseIsNotEnforceable() { + final OntologyShapeCheckModel model = shape(COMPOSITE_KEY); + model + .mapping() + .table("crm_customer_profile") + .setFullyQualifiedName("warehouse.archive.shop.crm_customer_profile"); + assertEquals( + refused(OntologyShapeCheckReason.OTHER_DATABASE), + model.answer("Account", model.on("accountTier").withIn(literals("gold")))); + } + + @Test + void everyCheckNeedsAnEngineThatStatementsAreWrittenFor() { + final NotEnforceable unsupported = refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED); + final OntologyShapeCheckModel undeclared = customersOn("Oracle"); + assertEquals( + unsupported, undeclared.answer("Customer", undeclared.on("customerEmail").withMinCount(1))); + final OntologyShapeCheckModel simple = + customersOn("Oracle").primaryKey("customers", "id").notNull("customers", "email"); + assertEquals( + List.of(unsupported, unsupported, unsupported), + simple.answers( + "Customer", + simple.on("customerEmail").withMinCount(1).withIn(literals("a")).withPattern("^a$"))); + final OntologyShapeCheckModel orders = + new OntologyShapeCheckModel(COLUMN_RELATION, "Oracle").primaryKey("orders", "id"); + assertEquals( + unsupported, orders.answer("Order", orders.on("orderTotal").withMaxInclusive(limit("5")))); + assertEquals( + new HeldByMapping(), simple.answer("Customer", simple.on("customerEmail").withMaxCount(1))); + } + + @Test + void clickHouseGetsNoStatementThatKeepsUnmatchedRows() { + final OntologyShapeCheckModel contributing = + new OntologyShapeCheckModel(COMPOSITE_KEY, "Clickhouse"); + assertEquals( + List.of(refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED)), + contributing.answers("Account", contributing.on("accountTier").withMinCount(1))); + assertInstanceOf( + MoreValues.class, + contributing.check("Account", contributing.on("accountTier").withMaxCount(1)).probe()); + assertInstanceOf( + FewerValues.class, + contributing.check("Account", contributing.on("accountName").withMinCount(1)).probe()); + final OntologyShapeCheckModel related = + new OntologyShapeCheckModel(COLUMN_RELATION, "Clickhouse"); + assertEquals( + refused(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED), + related.answer( + "Order", related.on("placedBy").withClassIri(COLUMN_RELATION.iri("Customer")))); + } + + @Test + void propertyTheClassBindsInNoColumnIsNotMapped() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + assertEquals( + List.of(new NotMapped(), new NotMapped()), + model.answers("Customer", model.on("orderTotal").withMinCount(0).withIn(literals("1")))); + } + + @Test + void propertyTheVersionLacksIsNotMapped() { + final OntologyShapeCheckModel model = simpleCustomers(); + model.mapping().omit("customerEmail"); + assertEquals( + new NotMapped(), model.answer("Customer", model.on("customerEmail").withMinCount(1))); + } + + @Test + void classWithoutAnIdentityTableHasNoRecordsToCheck() { + final OntologyShapeCheckModel contributingOnly = + customersWith( + contributing("Customer", "customers", List.of("id"), bound("customerEmail", "email"))); + final NotEnforceable none = refused(OntologyShapeCheckReason.NO_IDENTITY_TABLE); + assertEquals( + List.of(none, none), + contributingOnly.answers( + "Customer", + contributingOnly.on("customerEmail").withMinCount(1).withIn(literals("a")))); + assertEquals( + new HeldByMapping(), + contributingOnly.answer("Customer", contributingOnly.on("customerEmail").withMinCount(0))); + + final OntologyShapeCheckModel noRole = + customersWith( + new BindingSpec( + "Customer", + "customers", + null, + List.of(), + null, + List.of(bound("customerEmail", "email")))); + assertEquals(none, noRole.answer("Customer", noRole.on("customerEmail").withMinCount(1))); + } + + @Test + void constraintRestsOnTheIdentityTableTheHolderAndTheTableItsJoinReaches() { + final OntologyShapeCheckModel model = shape(LINK_TABLE); + assertEquals( + Set.of( + model.mapping().id("orders"), + model.mapping().id("order_items"), + model.mapping().id("products")), + model.compile("Order", model.on("contains").withMinCount(1)).rests()); + assertEquals( + Set.of(model.mapping().id("orders")), + model.compile("Order", model.on("productTitle").withMinCount(1)).rests()); + } + + @Test + void constraintAlsoRestsOnATableWithNoRoleThatBindsItsProperty() { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel( + REPEATED_CONTRIBUTION, + POSTGRES, + List.of( + identity( + "Customer", "customers", List.of("id"), null, bound("customerName", "name")), + new BindingSpec( + "Customer", + "customer_addresses", + null, + List.of(), + null, + List.of(bound("addressCity", "city"))))); + final OntologyShapeConstraint constraint = model.on("addressCity").withMinCount(1); + assertEquals(new NotMapped(), model.answer("Customer", constraint)); + assertEquals( + Set.of(model.mapping().id("customers"), model.mapping().id("customer_addresses")), + model.compile("Customer", constraint).rests()); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java new file mode 100644 index 000000000000..43a38b991795 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenTest.java @@ -0,0 +1,172 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.service.ontology.OntologyPartOutcome.NotEnforceable; +import org.openmetadata.service.ontology.OntologyShapeCheckGoldens.Golden; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; + +/** + * Holds every generated shape check to the SQL text that a person read and committed: nine engine + * families, the six mapping shapes and each part that compiles to a query. A pattern compiles to + * one for Postgres alone. The test reads the files and never writes one. + */ +class OntologyShapeCheckGoldenTest { + private static final int FAMILIES = 9; + private static final int PARTS_OF_THE_SHAPES = 25; + private static final List NOT_WRITTEN_FOR_CLICKHOUSE = + List.of( + "columnRelation-placedBy-class", + "compositeKey-accountTier-minCount", + "linkTable-contains-class", + "linkTable-contains-minCount", + "repeatedContribution-addressCity-minCount"); + private static final List PATTERNS = + List.of( + "compositeKey-accountTier-pattern", + "filteredIdentity-personName-pattern", + "repeatedContribution-addressCity-pattern", + "unfilteredIdentity-customerEmail-pattern"); + + /** Text that ends a string, starts a statement, opens a comment and names a parameter. */ + private static final String INJECTION = "ZQX'; DROP TABLE t; -- :p \\ %_"; + + private static final String MARKER = "ZQX"; + + static List goldens() { + return OntologyShapeCheckGoldens.all(); + } + + private static String file(final Golden golden) throws IOException { + try (InputStream file = + OntologyShapeCheckGoldenTest.class.getResourceAsStream("/" + golden.resource())) { + assertNotNull(file, "No golden file " + golden.resource()); + return new String(file.readAllBytes(), StandardCharsets.UTF_8); + } + } + + @ParameterizedTest + @MethodSource("goldens") + void aCountQueryIsTheTextOfItsGoldenFile(final Golden golden) throws IOException { + assertEquals(file(golden), golden.text()); + } + + /** + * A person names and describes a shape, a property, a table and a column, and none of that text + * is part of a statement. With an injection as each of them, the answer names the shape with + * the text, the count that a test runs is still the golden file with its colons escaped, the + * list of keys is still the one the count is made from, and no parameter holds the injection. + */ + @ParameterizedTest + @MethodSource("goldens") + void injectionTextInEveryTermReachesNoStatement(final Golden golden) throws IOException { + final OntologyCheckedShape shape = golden.checkedWhereEveryTermHolds(INJECTION); + final List checks = + shape.getConstraints().getFirst().getParts().getFirst().getChecks(); + final OntologyShapeCheck first = checks.getFirst(); + assertEquals(INJECTION, shape.getName()); + assertEquals( + file(golden).stripTrailing().replace(":", "\\:"), + first.getParameterValues().getFirst().getValue()); + assertEquals(golden.keys(), first.getInspectionQuery()); + for (final OntologyShapeCheck check : checks) { + assertFalse(check.getInspectionQuery().contains(MARKER), check.getInspectionQuery()); + check + .getParameterValues() + .forEach( + parameter -> + assertFalse(parameter.getValue().contains(MARKER), parameter.getValue())); + } + } + + @ParameterizedTest + @MethodSource("goldens") + void aCountQueryCountsTheRowsOfTheKeyList(final Golden golden) { + assertEquals( + "SELECT COUNT(*) AS violations\nFROM (\n " + + golden.keys().replace("\n", "\n ") + + "\n) c\n", + golden.text()); + } + + @Test + void everyGoldenFileBelongsToACheck() throws IOException, URISyntaxException { + final Path directory = + Path.of( + OntologyShapeCheckGoldenTest.class + .getResource("/" + OntologyShapeCheckGoldens.DIRECTORY) + .toURI()); + try (Stream files = Files.walk(directory)) { + assertEquals( + goldens().stream().map(Golden::resource).sorted().toList(), + files + .filter(Files::isRegularFile) + .map(file -> OntologyShapeCheckGoldens.DIRECTORY + "/" + directory.relativize(file)) + .map(path -> path.replace('\\', '/')) + .sorted() + .toList()); + } + assertEquals( + FAMILIES * PARTS_OF_THE_SHAPES + - NOT_WRITTEN_FOR_CLICKHOUSE.size() + - (FAMILIES - 1) * PATTERNS.size(), + goldens().size()); + } + + @Test + void aPartWithNoQueryIsAPatternOffPostgresOrOneThatKeepsUnmatchedRowsOnClickHouse() { + final List refused = + OntologyShapeCheckGoldens.asked().stream().filter(golden -> !golden.isGenerated()).toList(); + final List expected = new ArrayList<>(); + NOT_WRITTEN_FOR_CLICKHOUSE.forEach(name -> expected.add(resource("clickhouse", name))); + for (final SqlEngineFamily family : SqlEngineFamily.values()) { + if (family != SqlEngineFamily.POSTGRES) { + final String directory = family.name().toLowerCase(Locale.ROOT); + PATTERNS.forEach(name -> expected.add(resource(directory, name))); + } + } + assertEquals( + expected.stream().sorted().toList(), + refused.stream().map(Golden::resource).sorted().toList()); + refused.forEach( + golden -> + assertEquals( + new NotEnforceable(OntologyShapeCheckReason.ENGINE_NOT_SUPPORTED), + golden.answer(), + golden.resource())); + } + + private static String resource(final String family, final String name) { + return OntologyShapeCheckGoldens.DIRECTORY + "/" + family + "/" + name + ".sql"; + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenWriter.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenWriter.java new file mode 100644 index 000000000000..76bf6a042fae --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldenWriter.java @@ -0,0 +1,45 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.openmetadata.service.ontology.OntologyShapeCheckGoldens.Golden; + +/** + * Writes the golden SQL files of the generated shape checks that do not exist yet. It never + * replaces a file: to write one again, delete it, run this class with the system property below, + * and read the new text before committing it. No test run starts this class, because its name + * matches no test pattern and it needs the property. + */ +class OntologyShapeCheckGoldenWriter { + @Test + @EnabledIfSystemProperty(named = "ontology.shapeCheck.goldens", matches = "write") + void writesTheGoldensThatDoNotExist() throws IOException { + final Path resources = Path.of(System.getProperty("basedir", "."), "src", "test", "resources"); + assertTrue(Files.isDirectory(resources), "Run it from the openmetadata-service module"); + for (final Golden golden : OntologyShapeCheckGoldens.all()) { + final Path file = resources.resolve(golden.resource()); + if (Files.notExists(file)) { + Files.createDirectories(file.getParent()); + Files.writeString(file, golden.text(), StandardOpenOption.CREATE_NEW); + } + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java new file mode 100644 index 000000000000..38a32940e92e --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckGoldens.java @@ -0,0 +1,225 @@ +/* + * 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.ontology; + +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.FILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.LINK_TABLE; +import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.limit; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.function.UnaryOperator; +import org.openmetadata.schema.api.data.OntologyCheckedShape; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyShapeCheckAnswer.Hidden; +import org.openmetadata.service.ontology.OntologyShapeCheckSql.Statements; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; + +/** + * The golden SQL of the generated shape checks: one file for each engine family, mapping shape + * and part that compiles to a query there. {@link OntologyShapeCheckGoldenWriter} writes a file + * that does not exist yet, and {@link OntologyShapeCheckGoldenTest} only reads them. + */ +final class OntologyShapeCheckGoldens { + static final String DIRECTORY = "ontology/shape-checks"; + + /** A wildcard, an escaped dot that is no wildcard, an escaped backslash, and a colon and a quote that a string writes. */ + private static final String PATTERN = "^[A-Z][a-z0-9]+.(:|\\.|'|\\\\)*[^ ]{2,}$"; + + private OntologyShapeCheckGoldens() {} + + /** + * One part of a constraint on one property of a class of a shape. + * + * @param part the name of the part, as the file name holds it + * @param states what the constraint states for that part + */ + record Asked( + Shape shape, + String type, + String property, + String part, + UnaryOperator states) { + String name() { + return shape.name() + "-" + property + "-" + part; + } + } + + /** One part as one engine family checks it. */ + record Golden(SqlEngineFamily family, Asked asked) { + /** The path of the file under the test resources. */ + String resource() { + return String.format( + "%s/%s/%s.sql", DIRECTORY, family.name().toLowerCase(Locale.ROOT), asked.name()); + } + + private OntologyShapeCheckModel model() { + return new OntologyShapeCheckModel( + asked.shape(), OntologyStatementGoldens.SERVICE_TYPES.get(family)); + } + + OntologyPartOutcome answer() { + final OntologyShapeCheckModel model = model(); + return model.answer(asked.type(), asked.states().apply(model.on(asked.property()))); + } + + /** + * The answer for the shape of this part, when {@code text} is every name and description that + * a person gives the shape and each property, and the display name and the description of each + * table and column. The names of a table and of a column stay, because a statement is written + * with them. + */ + OntologyCheckedShape checkedWhereEveryTermHolds(final String text) { + final OntologyShapeCheckModel model = model(); + asked.shape().tables().forEach(spec -> describe(model.mapping().table(spec.name()), text)); + final OntologyShapeCheckFacts facts = model.facts(asked.type()); + facts.properties().values().forEach(property -> describe(property, text)); + final OntologyShape shape = + model + .targeting(asked.type(), asked.states().apply(model.on(asked.property()))) + .withName(text) + .withDisplayName(text) + .withDescription(text) + .withFullyQualifiedName(text); + return OntologyShapeCheckAnswer.shapes( + facts, List.of(shape), new Hidden(Set.of(), Set.of(), Set.of())) + .getFirst(); + } + + boolean isGenerated() { + return answer() instanceof OntologyPartOutcome.Check; + } + + /** The text of the file: the count query for a person to read, and a line break. */ + String text() { + return family.finish(statements().count()).sql() + "\n"; + } + + /** The query that lists the keys of the records in violation. */ + String keys() { + return family.finish(statements().keys()).sql(); + } + + private Statements statements() { + final OntologyPartOutcome.Check check = (OntologyPartOutcome.Check) answer(); + return OntologyShapeCheckSql.write(check.checks().getFirst().probe()); + } + + @Override + public String toString() { + return resource(); + } + } + + /** Every part of every shape on every family, whether or not it compiles to a query there. */ + static List asked() { + final List goldens = new ArrayList<>(); + for (final SqlEngineFamily family : OntologyStatementGoldens.SERVICE_TYPES.keySet()) { + parts().forEach(asked -> goldens.add(new Golden(family, asked))); + } + return goldens; + } + + /** The parts that compile to a query, each of which has a golden file. */ + static List all() { + return asked().stream().filter(Golden::isGenerated).toList(); + } + + /** The parts that a query checks, for each of the six mapping shapes. */ + static List parts() { + final List parts = new ArrayList<>(); + parts.addAll(valueParts(UNFILTERED_IDENTITY, "Customer", "customerEmail", 1)); + parts.addAll(valueParts(FILTERED_IDENTITY, "Person", "personName", 1)); + parts.addAll(valueParts(COMPOSITE_KEY, "Account", "accountTier", 1)); + parts.addAll(valueParts(REPEATED_CONTRIBUTION, "Customer", "addressCity", 2)); + parts.addAll(relationParts(COLUMN_RELATION, "placedBy", "Customer")); + parts.add( + new Asked( + COLUMN_RELATION, + "Order", + "orderTotal", + "range", + constraint -> + constraint.withMinInclusive(limit("0")).withMaxInclusive(limit("100.50")))); + parts.addAll(relationParts(LINK_TABLE, "contains", "Product")); + parts.add( + new Asked( + LINK_TABLE, + "Order", + "itemQuantity", + "range", + constraint -> constraint.withMinInclusive(limit("1")))); + parts.add( + new Asked( + LINK_TABLE, + "Order", + "orderChannel", + "in", + constraint -> constraint.withIn(literals("web", "store")))); + return List.copyOf(parts); + } + + private static void describe(final Table table, final String text) { + table.withDisplayName(text).withDescription(text); + table.getColumns().forEach(column -> column.withDisplayName(text).withDescription(text)); + } + + private static void describe(final OntologyProperty property, final String text) { + property + .withName(text) + .withDisplayName(text) + .withDescription(text) + .withFullyQualifiedName(text) + .withUnit(text); + } + + /** + * The counts, the list and the pattern of a text property. The pattern holds each construct + * that is written in another way than it is given: a wildcard, and a backslash before a colon, + * a dot and a quote. + */ + private static List valueParts( + final Shape shape, final String type, final String property, final int count) { + return List.of( + new Asked(shape, type, property, "minCount", constraint -> constraint.withMinCount(count)), + new Asked(shape, type, property, "maxCount", constraint -> constraint.withMaxCount(count)), + new Asked(shape, type, property, "in", constraint -> constraint.withIn(literals("a", "b"))), + new Asked(shape, type, property, "pattern", constraint -> constraint.withPattern(PATTERN))); + } + + /** The counts of a relation of the order class, and the class its values must be records of. */ + private static List relationParts( + final Shape shape, final String relation, final String target) { + final String type = "Order"; + return List.of( + new Asked(shape, type, relation, "minCount", constraint -> constraint.withMinCount(1)), + new Asked(shape, type, relation, "maxCount", constraint -> constraint.withMaxCount(1)), + new Asked( + shape, + type, + relation, + "class", + constraint -> constraint.withClassIri(shape.iri(target)))); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java new file mode 100644 index 000000000000..07acd5367446 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckModel.java @@ -0,0 +1,284 @@ +/* + * 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.ontology; + +import static org.openmetadata.service.ontology.OntologyMappingShapes.identity; +import static org.openmetadata.service.ontology.OntologyMappingShapes.integer; +import static org.openmetadata.service.ontology.OntologyMappingShapes.joined; +import static org.openmetadata.service.ontology.OntologyMappingShapes.relation; +import static org.openmetadata.service.ontology.OntologyMappingShapes.table; +import static org.openmetadata.service.ontology.OntologyMappingShapes.text; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.ColumnConstraint; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TableConstraint.ConstraintType; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyMappingReader.Bindings; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyPartOutcome.Check; +import org.openmetadata.service.ontology.OntologyPartOutcome.TableCheck; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledConstraint; +import org.openmetadata.service.ontology.OntologyShapeCheckCompiler.CompiledPart; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Subject; +import org.openmetadata.service.ontology.OntologyShapeCheckFacts.Target; + +/** + * One mapping shape as the shape check compile reads it. A test declares a key, binds a relation + * on its inverse or shares a table with a subclass, then asks what one constraint compiles to. + */ +final class OntologyShapeCheckModel { + static final String CONSTRAINT_ID = "c1"; + + /** A shipment names its account with two columns, the two-column key of the account table. */ + static final Shape TWO_COLUMN_RELATION = + new Shape( + "twoColumnRelation", + List.of( + table("shipments", List.of(integer("id"), text("tenant"), integer("customer"))), + table( + "crm_customers", + List.of(text("tenant_id"), integer("customer_id"), text("name")))), + List.of("Shipment", "Account"), + List.of(relation("shippedTo", "Shipment", "Account")), + List.of( + identity( + "Shipment", + "shipments", + List.of("id"), + null, + new ColumnBindingSpec( + "shippedTo", + "tenant", + new JoinSpec( + "crm_customers", + OntologyJoinStatus.CONFIRMED, + List.of("tenant", "customer"), + List.of("tenant_id", "customer_id")))), + identity("Account", "crm_customers", List.of("tenant_id", "customer_id"), null)), + List.of()); + + /** A membership is held by a person, and people share a filtered table with other parties. */ + static final Shape FILTERED_TARGET = + new Shape( + "filteredTarget", + List.of( + table("parties", List.of(integer("id"), text("kind"), text("name"))), + table("memberships", List.of(integer("id"), integer("party_id")))), + List.of("Membership", "Person"), + List.of(relation("heldBy", "Membership", "Person")), + List.of( + identity( + "Person", + "parties", + List.of("id"), + new FilterSpec("kind", OntologyRowFilterOperator.EQUALS, "person")), + identity( + "Membership", + "memberships", + List.of("id"), + null, + joined("heldBy", "party_id", "parties", "id"))), + List.of()); + + private final Shape shape; + private final OntologyMappingShapeModel mapping; + private final Set boundOnInverse = new HashSet<>(); + private final Set sharedWithSubclass = new HashSet<>(); + + OntologyShapeCheckModel(final Shape shape, final String serviceType) { + this(shape, serviceType, shape.bindings()); + } + + OntologyShapeCheckModel( + final Shape shape, final String serviceType, final List bindings) { + this.shape = shape; + this.mapping = new OntologyMappingShapeModel(shape, serviceType, bindings); + } + + static OntologyShapeValue literal(final String value) { + return new OntologyShapeValue().withLiteral(limit(value)); + } + + static List literals(final String... values) { + return List.of(values).stream().map(OntologyShapeCheckModel::literal).toList(); + } + + /** A literal with no datatype, as a bound of a range or a member of a list. */ + static OntologyLiteral limit(final String value) { + return new OntologyLiteral().withValue(value); + } + + /** The tables and binding rows under the facts. A test changes a table through it. */ + OntologyMappingShapeModel mapping() { + return mapping; + } + + /** The catalog declares a primary key of the table on these columns. */ + OntologyShapeCheckModel primaryKey(final String table, final String... columns) { + return declare(table, ConstraintType.PRIMARY_KEY, columns); + } + + /** The catalog declares a unique key of the table on these columns. */ + OntologyShapeCheckModel uniqueKey(final String table, final String... columns) { + return declare(table, ConstraintType.UNIQUE, columns); + } + + private OntologyShapeCheckModel declare( + final String table, final ConstraintType type, final String... columns) { + mapping + .table(table) + .setTableConstraints( + List.of(new TableConstraint().withConstraintType(type).withColumns(List.of(columns)))); + return this; + } + + /** The catalog says the column never holds a null. */ + OntologyShapeCheckModel notNull(final String table, final String column) { + mapping.table(table).getColumns().stream() + .filter(candidate -> candidate.getName().equals(column)) + .forEach(candidate -> candidate.setConstraint(ColumnConstraint.NOT_NULL)); + return this; + } + + /** Another class binds the inverse of the relation. */ + OntologyShapeCheckModel bindOnInverse(final String relation) { + boundOnInverse.add(relation); + return this; + } + + /** A subclass of the class has its identity table on the identity table of the class. */ + OntologyShapeCheckModel shareTableWithSubclass(final String type) { + sharedWithSubclass.add(type); + return this; + } + + /** A constraint on one property of the shape, ready for the parts a test states. */ + OntologyShapeConstraint on(final String property) { + return new OntologyShapeConstraint().withId(CONSTRAINT_ID).withPath(shape.iri(property)); + } + + OntologyShapeCheckFacts facts(final String type) { + final Bindings bindings = mapping.bindings(); + return new OntologyShapeCheckFacts( + new Subject(mapping.id(type), mapping.iri(type), tables(type, bindings)), + mapping.properties().values().stream() + .collect(Collectors.toMap(OntologyProperty::getIri, Function.identity())), + targets(bindings), + boundOnInverse.stream().map(mapping::id).collect(Collectors.toSet()), + revisions()); + } + + /** The binding revision of each class: its position in the shape, from 1. */ + private Map revisions() { + final Map revisions = new HashMap<>(); + for (int index = 0; index < shape.classes().size(); index++) { + revisions.put(mapping.id(shape.classes().get(index)), index + 1L); + } + return revisions; + } + + /** The tables of a class that exist: its identity table, then the others in binding order. */ + private List tables(final String type, final Bindings bindings) { + final List rows = new ArrayList<>(); + final BindingRow identity = bindings.identity().get(mapping.id(type)); + if (identity != null) { + rows.add(identity); + } + rows.addAll(bindings.contributing().getOrDefault(mapping.id(type), List.of())); + final Set live = mapping.catalog().live(); + return rows.stream().filter(row -> live.contains(row.assetId())).map(this::mapped).toList(); + } + + /** The model names each binding row after its table, so the row says which table it binds. */ + private MappedTable mapped(final BindingRow row) { + return new MappedTable(mapping.table(row.assetFqnHash()), row); + } + + private Map targets(final Bindings bindings) { + final Set live = mapping.catalog().live(); + final Map targets = new HashMap<>(); + for (final String type : shape.classes()) { + final BindingRow identity = bindings.identity().get(mapping.id(type)); + final boolean held = identity != null && live.contains(identity.assetId()); + targets.put( + mapping.iri(type), + new Target( + mapping.id(type), held ? mapped(identity) : null, sharedWithSubclass.contains(type))); + } + return targets; + } + + /** The shape named {@code shape} that targets the class and holds these constraints. */ + OntologyShape targeting(final String type, final OntologyShapeConstraint... constraints) { + return new OntologyShape() + .withId(mapping.id("shape")) + .withName("shape") + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withTargetConcept(mapping.iri(type)) + .withConstraints(List.of(constraints)); + } + + /** The shape that holds only {@code constraint}, compiled for the class. */ + CompiledConstraint compile(final String type, final OntologyShapeConstraint constraint) { + return OntologyShapeCheckCompiler.compile(facts(type), List.of(targeting(type, constraint))) + .getFirst() + .constraints() + .getFirst(); + } + + /** The answers of the parts of one constraint, in part order. */ + List answers(final String type, final OntologyShapeConstraint constraint) { + return compile(type, constraint).parts().stream().map(CompiledPart::outcome).toList(); + } + + /** The answer of a constraint that states one part and gets one answer. */ + OntologyPartOutcome answer(final String type, final OntologyShapeConstraint constraint) { + final List answers = answers(type, constraint); + if (answers.size() != 1) { + throw new AssertionError("Expected one answer and got " + answers); + } + return answers.getFirst(); + } + + /** The one test of a constraint that states one part and is checked on one table. */ + TableCheck check(final String type, final OntologyShapeConstraint constraint) { + if (answer(type, constraint) instanceof Check found && found.checks().size() == 1) { + return found.checks().getFirst(); + } + throw new AssertionError("Expected one check and got " + answer(type, constraint)); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java new file mode 100644 index 000000000000..975066bdaa25 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckReaderTest.java @@ -0,0 +1,509 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import jakarta.ws.rs.ClientErrorException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyReleaseMember; +import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.jdbi3.OntologyConceptBindingStore; +import org.openmetadata.service.jdbi3.OntologyReleaseDAO; +import org.openmetadata.service.ontology.OntologyBindingAccess.TableViews; +import org.openmetadata.service.ontology.OntologyRecordMapping.MappedTable; +import org.openmetadata.service.ontology.OntologyShapeCheckAnswer.Hidden; +import org.openmetadata.service.ontology.OntologyShapeCheckReader.Asked; +import org.openmetadata.service.ontology.OntologyShapeCheckReader.Read; + +/** + * What an answer is read from: the binding revision its rows were read under, the shapes that + * target the class and that the caller may view, the properties the caller may not view, and the + * classes that get no answer because one read cannot hold all of theirs. + */ +class OntologyShapeCheckReaderTest { + private static final UUID ORDER = UUID.fromString("00000000-0000-0000-0000-00000000000a"); + private static final UUID PERSON = UUID.fromString("00000000-0000-0000-0000-00000000000b"); + private static final UUID ONTOLOGY = UUID.fromString("00000000-0000-0000-0000-0000000000f0"); + private static final UUID RELEASE = UUID.fromString("00000000-0000-0000-0000-0000000000e0"); + private static final URI ORDER_IRI = URI.create("https://example.org/shop#Order"); + private static final URI PERSON_IRI = URI.create("https://example.org/shop#Person"); + private static final URI PRODUCT_IRI = URI.create("https://example.org/shop#Product"); + private static final URI CHANNEL_IRI = URI.create("https://example.org/shop#orderChannel"); + private static final URI PLACED_BY_IRI = URI.create("https://example.org/shop#placedBy"); + private static final int MOST_SHAPES_OF_A_DRAFT = 1001; + private static final Asked DRAFT_ORDER = + new Asked(ORDER, ORDER_IRI, ONTOLOGY, new OntologyVersion.Draft(7L)); + + private final OntologyConceptBindingStore store = mock(OntologyConceptBindingStore.class); + private final OntologyBindingAccess catalog = mock(OntologyBindingAccess.class); + private final OntologyShapeCheckReader reader = new OntologyShapeCheckReader(store, catalog); + + /** Every table that is asked for exists, and the caller may view it and every definition. */ + @BeforeEach + void everythingExistsAndIsViewable() { + when(catalog.tableViews(any(), anyCollection())) + .thenAnswer( + call -> { + final Map live = + call.>getArgument(1).stream() + .distinct() + .collect(Collectors.toMap(id -> id, id -> new Table().withId(id))); + return new TableViews(live, live.keySet()); + }); + when(catalog.viewable(any(), anyString(), ArgumentMatchers.anyList())) + .thenAnswer( + call -> + call.>getArgument(2).stream() + .collect( + Collectors.>toMap( + OntologyDefinition::getId, definition -> new OntologyShape()))); + } + + @Test + void anAnswerNamesTheRevisionItsRowsWereReadUnder() { + final BindingRow orders = row(1, OntologyBindingRole.IDENTITY); + final BindingRow items = row(2, OntologyBindingRole.CONTRIBUTING); + when(store.revisions(anyCollection())).thenReturn(Map.of(ORDER, 4L)); + when(store.identityFirstTables(List.of(ORDER), 101)).thenReturn(List.of(orders, items)); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(Map.of(ORDER, 4L), read.facts().revisions()); + assertEquals(List.of(orders, items), rows(read)); + assertEquals(new Hidden(Set.of(), Set.of(), Set.of()), read.hidden()); + } + + @Test + void aBindingWriteThatLandsWhileTheRowsAreReadMakesTheReaderReadThemAgain() { + final BindingRow before = row(1, OntologyBindingRole.IDENTITY); + final BindingRow after = row(2, OntologyBindingRole.IDENTITY); + when(store.revisions(anyCollection())) + .thenReturn(Map.of(ORDER, 4L), Map.of(ORDER, 5L), Map.of(ORDER, 5L)); + when(store.identityFirstTables(List.of(ORDER), 101)) + .thenReturn(List.of(before), List.of(after)); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(Map.of(ORDER, 5L), read.facts().revisions()); + assertEquals(List.of(after), rows(read)); + } + + @Test + void aBindingWriteOfAClassThatAPartNamesMakesTheReaderReadTheRowsAgain() { + final BindingRow orders = row(1, OntologyBindingRole.IDENTITY); + final BindingRow before = row(PERSON, 2, OntologyBindingRole.IDENTITY); + final BindingRow after = row(PERSON, 3, OntologyBindingRole.IDENTITY); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) + .thenReturn(List.of(shape(1, "a", ORDER_IRI, on(PLACED_BY_IRI).withClassIri(PERSON_IRI)))); + when(store.liveConcepts(ONTOLOGY, Set.of(PERSON_IRI))) + .thenReturn(List.of(new OntologyConcept().withId(PERSON).withIri(PERSON_IRI))); + when(store.revisions(anyCollection())) + .thenReturn( + Map.of(ORDER, 4L, PERSON, 7L), + Map.of(ORDER, 4L, PERSON, 8L), + Map.of(ORDER, 4L, PERSON, 8L)); + when(store.identityFirstTables(List.of(ORDER), 101)).thenReturn(List.of(orders)); + when(store.identityRows(List.of(PERSON))).thenReturn(List.of(before), List.of(after)); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(Map.of(ORDER, 4L, PERSON, 8L), read.facts().revisions()); + assertEquals(after, read.facts().targets().get(PERSON_IRI).identity().row()); + verify(store, times(2)).identityFirstTables(List.of(ORDER), 101); + verify(store, times(2)).identityRows(List.of(PERSON)); + } + + @Test + void filteredClassesAreReadForTheirSubclassesInOneReadOfTheRowsAndOneQuestion() { + final UUID placer = new UUID(5, 1); + final UUID buyer = new UUID(5, 2); + final URI placerIri = URI.create("https://example.org/shop#Placer"); + final URI buyerIri = URI.create("https://example.org/shop#Buyer"); + final OntologyConcept subOfPerson = + new OntologyConcept() + .withId(placer) + .withIri(placerIri) + .withOntology(new EntityReference().withId(ONTOLOGY)); + final OntologyConcept unrelated = + new OntologyConcept() + .withId(buyer) + .withIri(buyerIri) + .withOntology(new EntityReference().withId(ONTOLOGY)); + final BindingRow person = filtered(PERSON, 2, OntologyBindingRole.IDENTITY); + final BindingRow product = filtered(new UUID(4, 1), 3, OntologyBindingRole.IDENTITY); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) + .thenReturn( + List.of( + shape( + 1, + "a", + ORDER_IRI, + on(PLACED_BY_IRI).withClassIri(PERSON_IRI), + on(CHANNEL_IRI).withId("c2").withClassIri(PRODUCT_IRI)))); + when(store.liveConcepts(ONTOLOGY, Set.of(PERSON_IRI, PRODUCT_IRI))) + .thenReturn( + List.of( + new OntologyConcept().withId(PERSON).withIri(PERSON_IRI), + new OntologyConcept().withId(product.conceptId()).withIri(PRODUCT_IRI))); + when(store.identityFirstTables(List.of(ORDER), 101)) + .thenReturn(List.of(row(1, OntologyBindingRole.IDENTITY))); + when(store.identityRows(anyCollection())).thenReturn(List.of(person, product)); + when(store.firstForAssets(anyCollection(), eq(101))) + .thenReturn( + List.of( + person, + row(placer, 2, OntologyBindingRole.IDENTITY), + product, + row(buyer, 3, OntologyBindingRole.IDENTITY))); + when(store.liveConcepts(ArgumentMatchers.>any())) + .thenReturn(List.of(subOfPerson, unrelated)); + when(store.namedParentsAbove(ONTOLOGY, Set.of(placerIri.toString(), buyerIri.toString()))) + .thenReturn(Map.of(placerIri.toString(), Set.of(PERSON_IRI.toString()))); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(true, read.facts().targets().get(PERSON_IRI).subclassSharesTable()); + assertEquals(false, read.facts().targets().get(PRODUCT_IRI).subclassSharesTable()); + verify(store, times(1)).firstForAssets(anyCollection(), eq(101)); + verify(store, times(1)).liveConcepts(ArgumentMatchers.>any()); + verify(store, times(1)).namedParentsAbove(eq(ONTOLOGY), anyCollection()); + } + + @Test + void bindingsThatChangeOnEveryReadGiveNoAnswer() { + when(store.revisions(anyCollection())) + .thenReturn( + Map.of(ORDER, 1L), + Map.of(ORDER, 2L), + Map.of(ORDER, 3L), + Map.of(ORDER, 4L), + Map.of(ORDER, 5L), + Map.of(ORDER, 6L)); + + assertRefused( + "The table bindings changed while the answer was built. Ask again", + () -> reader.read(null, DRAFT_ORDER)); + } + + @Test + void aClassThatBindsMoreTablesThanAnAnswerReadsGivesNoAnswer() { + final List rows = new ArrayList<>(); + rows.add(row(1, OntologyBindingRole.IDENTITY)); + IntStream.rangeClosed(2, 101) + .forEach(table -> rows.add(row(table, OntologyBindingRole.CONTRIBUTING))); + when(store.identityFirstTables(List.of(ORDER), 101)).thenReturn(rows, rows.subList(0, 100)); + + assertRefused( + "Class https://example.org/shop#Order binds more than 100 tables", + () -> reader.read(null, DRAFT_ORDER)); + assertEquals(rows.subList(0, 100), rows(reader.read(null, DRAFT_ORDER))); + } + + @Test + void aDraftClassThatMoreShapesNameThanOneStatementReadsGivesNoAnswer() { + final List naming = + IntStream.rangeClosed(1, 1001) + .mapToObj(shape -> shape(shape, "s" + shape, PRODUCT_IRI)) + .toList(); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, 1001)) + .thenReturn(naming, naming.subList(0, 1000)); + + assertRefused( + "More than 1000 shapes name class https://example.org/shop#Order", + () -> reader.read(null, DRAFT_ORDER)); + assertEquals(List.of(), reader.read(null, DRAFT_ORDER).shapes()); + } + + @Test + void theShapesOfAnAnswerAreTheOnesThatTargetTheClassInNameOrder() { + final OntologyShape second = shape(1, "b", ORDER_IRI); + final OntologyShape first = shape(2, "a", ORDER_IRI); + final OntologyShape namesItInAConstraint = shape(3, "c", PRODUCT_IRI); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, 1001)) + .thenReturn(List.of(second, namesItInAConstraint, first)); + + assertEquals(List.of(first, second), reader.read(null, DRAFT_ORDER).shapes()); + } + + @Test + void aShapeTheCallerMayNotViewIsLeftOutAndNothingIsReadForIt() { + final OntologyShape viewable = shape(1, "b", ORDER_IRI, on(CHANNEL_IRI).withMinCount(1)); + final OntologyShape denied = + shape(2, "a", ORDER_IRI, on(PLACED_BY_IRI).withClassIri(PERSON_IRI)); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) + .thenReturn(List.of(denied, viewable)); + when(catalog.viewable(null, Entity.ONTOLOGY_SHAPE, List.of(denied, viewable))) + .thenReturn(Map.of(viewable.getId(), viewable)); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(List.of(viewable), read.shapes()); + verify(store).liveProperties(ONTOLOGY, Set.of(CHANNEL_IRI)); + verify(store).liveConcepts(ONTOLOGY, Set.of()); + } + + @Test + void aPropertyTheCallerMayNotViewIsReadForTheCompileAndNamedAsHidden() { + final OntologyProperty channel = property(1, CHANNEL_IRI); + final OntologyProperty placedBy = property(2, PLACED_BY_IRI); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) + .thenReturn( + List.of( + shape( + 1, + "a", + ORDER_IRI, + on(CHANNEL_IRI).withMinCount(1), + on(PLACED_BY_IRI).withMinCount(1)))); + when(store.liveProperties(ONTOLOGY, Set.of(CHANNEL_IRI, PLACED_BY_IRI))) + .thenReturn(List.of(channel, placedBy)); + when(catalog.viewable(null, Entity.ONTOLOGY_PROPERTY, List.of(channel, placedBy))) + .thenReturn(Map.of(channel.getId(), channel)); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(new Hidden(Set.of(), Set.of(PLACED_BY_IRI), Set.of()), read.hidden()); + assertEquals(Map.of(CHANNEL_IRI, channel, PLACED_BY_IRI, placedBy), read.facts().properties()); + } + + @Test + void aClassThatAPartNamesAndTheCallerMayNotViewIsNamedAsHidden() { + final OntologyConcept product = + new OntologyConcept().withId(new UUID(4, 1)).withIri(PRODUCT_IRI); + final OntologyConcept person = new OntologyConcept().withId(new UUID(4, 2)).withIri(PERSON_IRI); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) + .thenReturn( + List.of( + shape( + 1, + "a", + ORDER_IRI, + on(PLACED_BY_IRI).withClassIri(PERSON_IRI), + on(CHANNEL_IRI).withId("c2").withClassIri(PRODUCT_IRI)))); + when(store.liveConcepts(ONTOLOGY, Set.of(PERSON_IRI, PRODUCT_IRI))) + .thenReturn(List.of(person, product)); + when(catalog.viewable(null, Entity.ONTOLOGY_CONCEPT, List.of(person, product))) + .thenReturn(Map.of(person.getId(), person)); + + final Read read = reader.read(null, DRAFT_ORDER); + + assertEquals(new Hidden(Set.of(), Set.of(), Set.of(PRODUCT_IRI)), read.hidden()); + } + + @Test + void theDraftAuthorizesTheRowsItReadAndReadsNoneAgain() { + final OntologyShape order = shape(1, "a", ORDER_IRI, on(CHANNEL_IRI).withMinCount(1)); + final OntologyProperty channel = property(1, CHANNEL_IRI); + when(store.shapesNamingClass(ONTOLOGY, ORDER_IRI, MOST_SHAPES_OF_A_DRAFT)) + .thenReturn(List.of(order)); + when(store.liveProperties(ONTOLOGY, Set.of(CHANNEL_IRI))).thenReturn(List.of(channel)); + + reader.read(null, DRAFT_ORDER); + + verify(catalog).viewable(null, Entity.ONTOLOGY_SHAPE, List.of(order)); + verify(catalog).viewable(null, Entity.ONTOLOGY_PROPERTY, List.of(channel)); + verify(catalog, never()).viewable(any(), anyString(), anyCollection()); + } + + @Test + void theShapesOfAReleaseAreReadFromEveryPageOfItsMembers() { + final List members = new ArrayList<>(); + IntStream.rangeClosed(1, OntologyVersion.SHAPE_MEMBERS_READ) + .forEach(shape -> members.add(released(shape, PRODUCT_IRI))); + final OntologyShape onTheFirstPage = released(7, ORDER_IRI); + members.set(6, onTheFirstPage); + final OntologyShape onTheSecondPage = + released(OntologyVersion.SHAPE_MEMBERS_READ + 2, ORDER_IRI); + members.add(released(OntologyVersion.SHAPE_MEMBERS_READ + 1, PRODUCT_IRI)); + members.add(onTheSecondPage); + final OntologyVersion release = release(members); + + assertEquals( + List.of(onTheFirstPage.getId(), onTheSecondPage.getId()), + release.shapesTargeting(store, ONTOLOGY, ORDER_IRI).stream() + .map(OntologyShape::getId) + .toList()); + } + + @Test + void aReleaseAuthorizesTheClassRowsItWasGivenAndNotTheirIds() { + final OntologyConcept released = + new OntologyConcept().withId(new UUID(4, 1)).withIri(PRODUCT_IRI); + when(catalog.viewable(null, Entity.ONTOLOGY_CONCEPT, List.of(released))) + .thenReturn(Map.of(released.getId(), released)); + + final Set viewable = + release(List.of()).viewable(catalog, null, Entity.ONTOLOGY_CONCEPT, List.of(released)); + + assertEquals(Set.of(released.getId()), viewable); + verify(catalog).viewable(null, Entity.ONTOLOGY_CONCEPT, List.of(released)); + verifyNoMoreInteractions(catalog); + } + + /** A sealed release whose shape members are {@code shapes}, listed a page at a time by id. */ + private static OntologyVersion release(final List shapes) { + final OntologyReleaseDAO releases = mock(OntologyReleaseDAO.class); + final CollectionDAO dao = mock(CollectionDAO.class); + when(dao.ontologyReleaseDAO()).thenReturn(releases); + final List members = + shapes.stream() + .map( + shape -> + new OntologyReleaseMember() + .withReleaseId(RELEASE) + .withMemberKind(MemberKind.SHAPE) + .withMemberId(shape.getId()) + .withPayload(JsonUtils.valueToTree(shape))) + .toList(); + final int[] listed = {0}; + when(releases.listMembers(eq(RELEASE), eq(MemberKind.SHAPE.value()), anyString(), anyInt())) + .thenAnswer( + call -> { + // A cursor that never moves would list the first page for ever. + assertTrue(++listed[0] <= members.size(), "the cursor does not move"); + final String after = call.getArgument(2); + return members.stream() + .filter(member -> member.getMemberId().toString().compareTo(after) > 0) + .limit(call.getArgument(3)) + .toList(); + }); + return new OntologyVersion.Release( + dao, + new OntologyRelease() + .withId(RELEASE) + .withEncodingVersion(OntologyRelease.EncodingVersion.ONTOLOGY_RELEASE_V_1) + .withOntology(new EntityReference().withId(ONTOLOGY)), + "shop"); + } + + /** A shape as a release holds it, with an id that sorts in the order of {@code number}. */ + private static OntologyShape released(final int number, final URI target) { + return new OntologyShape() + .withId(new UUID(2, number)) + .withName("s" + number) + .withTargetConcept(target) + .withOntology(new EntityReference().withId(ONTOLOGY)); + } + + private static void assertRefused(final String message, final Runnable read) { + final ClientErrorException refused = assertThrows(ClientErrorException.class, read::run); + + assertEquals(409, refused.getResponse().getStatus()); + assertEquals(message, refused.getMessage()); + } + + /** The binding rows of the tables of the class that an answer was read from, in its order. */ + private static List rows(final Read read) { + return read.facts().subject().tables().stream().map(MappedTable::row).toList(); + } + + private static BindingRow row(final int table, final OntologyBindingRole role) { + return row(ORDER, table, role); + } + + private static BindingRow filtered( + final UUID type, final int table, final OntologyBindingRole role) { + final BindingRow plain = row(type, table, role); + return new BindingRow( + plain.conceptId(), + plain.assetId(), + plain.assetType(), + plain.assetFqnHash(), + plain.columns(), + plain.role(), + plain.subjectKey(), + new OntologyRowFilter() + .withColumn(List.of("title")) + .withOperator(OntologyRowFilterOperator.NOT_EQUALS) + .withValue("x")); + } + + private static BindingRow row(final UUID type, final int table, final OntologyBindingRole role) { + return new BindingRow( + type, + new UUID(0, table), + OntologyBindingAssetType.TABLE, + "hash" + table, + List.of(), + role, + List.of(List.of("id")), + null); + } + + private static OntologyShape shape( + final int id, + final String name, + final URI target, + final OntologyShapeConstraint... constraints) { + return new OntologyShape() + .withId(new UUID(1, id)) + .withName(name) + .withTargetConcept(target) + .withConstraints(List.of(constraints)); + } + + private static OntologyShapeConstraint on(final URI path) { + return new OntologyShapeConstraint().withId(path.getFragment()).withPath(path); + } + + private static OntologyProperty property(final int id, final URI iri) { + return new OntologyProperty() + .withId(new UUID(3, id)) + .withIri(iri) + .withKind(OntologyPropertyKind.DATA); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java new file mode 100644 index 000000000000..3e1ffb592a7e --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckSqlTest.java @@ -0,0 +1,291 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.COMPOSITE_KEY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.REPEATED_CONTRIBUTION; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyMappingShapes.bound; +import static org.openmetadata.service.ontology.OntologyMappingShapes.identity; +import static org.openmetadata.service.ontology.OntologyMappingShapes.integer; +import static org.openmetadata.service.ontology.OntologyMappingShapes.relation; +import static org.openmetadata.service.ontology.OntologyMappingShapes.table; +import static org.openmetadata.service.ontology.OntologyMappingShapes.text; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.FILTERED_TARGET; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.TWO_COLUMN_RELATION; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.limit; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literals; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.ontology.OntologyMappingShapes.BindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.ColumnBindingSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.FilterSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.JoinSpec; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.OntologyShapeCheckSql.Statements; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; + +/** + * The text of the generated shape checks that the golden files of the six mapping shapes do not + * hold: a join of several columns, a filtered table on the far side of a join, a bound on one side, + * a list with no member and a pattern with a backslash. + */ +class OntologyShapeCheckSqlTest { + private static final String POSTGRES = "Postgres"; + + /** An order names its customer by email, which is not the key of the customer table. */ + private static final Shape JOIN_OFF_THE_KEY = + new Shape( + "joinOffTheKey", + List.of( + table("customers", List.of(integer("id"), text("email"))), + table("orders", List.of(integer("id"), text("customer_email")))), + List.of("Order", "Customer"), + List.of(relation("placedBy", "Order", "Customer")), + List.of( + identity("Customer", "customers", List.of("id"), null), + identity( + "Order", + "orders", + List.of("id"), + null, + new ColumnBindingSpec( + "placedBy", + "customer_email", + new JoinSpec( + "customers", + OntologyJoinStatus.CONFIRMED, + List.of("customer_email"), + List.of("email"))))), + List.of()); + + private static String keys( + final OntologyShapeCheckModel model, final String type, final OntologyShapeConstraint part) { + return SqlEngineFamily.POSTGRES.finish(statements(model, type, part).keys()).sql(); + } + + private static Statements statements( + final OntologyShapeCheckModel model, final String type, final OntologyShapeConstraint part) { + return OntologyShapeCheckSql.write(model.check(type, part).probe()); + } + + private static OntologyShapeCheckModel shape(final Shape shape) { + return new OntologyShapeCheckModel(shape, POSTGRES); + } + + /** The addresses of the customers with a row filter on the table that holds them. */ + private static OntologyShapeCheckModel filteredAddresses() { + return new OntologyShapeCheckModel( + REPEATED_CONTRIBUTION, + POSTGRES, + List.of( + identity("Customer", "customers", List.of("id"), null, bound("customerName", "name")), + new BindingSpec( + "Customer", + "customer_addresses", + OntologyBindingRole.CONTRIBUTING, + List.of("customer_id"), + new FilterSpec("country", OntologyRowFilterOperator.NOT_EQUALS, "XX"), + List.of(bound("addressCity", "city"))))); + } + + @Test + void classOverAJoinOfTwoColumnsComparesBothAndAsksBothForAValue() { + final OntologyShapeCheckModel model = shape(TWO_COLUMN_RELATION); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.shipments t0 + LEFT JOIN shop.crm_customers t1 ON t1.tenant_id = t0.tenant AND t1.customer_id = t0.customer + WHERE t0.id IS NOT NULL + AND t0.tenant IS NOT NULL + AND t0.customer IS NOT NULL + AND t1.tenant_id IS NULL""", + keys( + model, + "Shipment", + model.on("shippedTo").withClassIri(TWO_COLUMN_RELATION.iri("Account")))); + } + + @Test + void minCountOfARelationOfTwoColumnsCountsTheRowsWhereBothHoldAValue() { + final OntologyShapeCheckModel model = shape(TWO_COLUMN_RELATION); + assertEquals( + """ + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.tenant AS v0, t0.customer AS v1 + FROM shop.shipments t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL AND k.v1 IS NOT NULL THEN 1 ELSE 0 END) < 1""", + keys(model, "Shipment", model.on("shippedTo").withMinCount(1))); + } + + @Test + void classCarriesTheRowFilterOfTheClassItsValuesMustBeRecordsOf() { + final OntologyShapeCheckModel model = shape(FILTERED_TARGET); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.memberships t0 + LEFT JOIN shop.parties t1 ON t1.id = t0.party_id AND t1.kind = 'person' + WHERE t0.id IS NOT NULL + AND t0.party_id IS NOT NULL + AND t1.id IS NULL""", + keys(model, "Membership", model.on("heldBy").withClassIri(FILTERED_TARGET.iri("Person")))); + } + + @Test + void classOverAJoinOffTheKeyAsksTheKeyOfTheFoundRowForAValue() { + final OntologyShapeCheckModel model = shape(JOIN_OFF_THE_KEY); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + LEFT JOIN shop.customers t1 ON t1.email = t0.customer_email AND t1.id IS NOT NULL + WHERE t0.id IS NOT NULL + AND t0.customer_email IS NOT NULL + AND t1.email IS NULL""", + keys(model, "Order", model.on("placedBy").withClassIri(JOIN_OFF_THE_KEY.iri("Customer")))); + } + + @Test + void rangeWithOnlyAnUpperBoundComparesOnce() { + final OntologyShapeCheckModel model = shape(COLUMN_RELATION); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.total > 100""", + keys(model, "Order", model.on("orderTotal").withMaxInclusive(limit("100")))); + } + + @Test + void listWithNoMemberIsBrokenByEveryValue() { + final OntologyShapeCheckModel model = shape(UNFILTERED_IDENTITY); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email IS NOT NULL""", + keys(model, "Customer", model.on("customerEmail").withIn(List.of()))); + } + + @Test + void maxCountZeroFindsEveryRecordWithAValue() { + final OntologyShapeCheckModel model = shape(UNFILTERED_IDENTITY); + assertEquals( + """ + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 0""", + keys(model, "Customer", model.on("customerEmail").withMaxCount(0))); + } + + @Test + void rowFilterOfATableThatHoldsThePropertyIsPartOfItsJoin() { + final OntologyShapeCheckModel model = filteredAddresses(); + assertEquals( + """ + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + LEFT JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id AND t1.country <> 'XX' + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1""", + keys(model, "Customer", model.on("addressCity").withMinCount(1))); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id AND t1.country <> 'XX' + WHERE t0.id IS NOT NULL + AND t1.city NOT IN ('London')""", + keys(model, "Customer", model.on("addressCity").withIn(literals("London")))); + } + + @Test + void patternIsMatchedAgainstTheValueAsTextUnderTheCodePointCollation() { + final OntologyShapeCheckModel model = shape(UNFILTERED_IDENTITY); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ '^[a-z]+$')""", + keys(model, "Customer", model.on("customerEmail").withPattern("^[a-z]+$"))); + } + + @Test + void patternWithABackslashIsWrittenAsAStringThatReadsItsEscapes() { + final OntologyShapeCheckModel model = shape(UNFILTERED_IDENTITY); + assertEquals( + """ + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[a-z]+[^\\\\n\\\\r]@example\\\\.org$')""", + keys(model, "Customer", model.on("customerEmail").withPattern("^[a-z]+.@example\\.org$"))); + } + + @Test + void patternOnATableThatAddsToTheRecordsJoinsItByTheKey() { + final OntologyShapeCheckModel model = shape(COMPOSITE_KEY); + assertEquals( + """ + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND NOT (CAST(t1.tier AS text) COLLATE "C" ~ '^(gold|silver)$')""", + keys(model, "Account", model.on("accountTier").withPattern("^(gold|silver)$"))); + } + + @Test + void countQueryHoldsTheKeyListAndNothingThatOrdersOrLimitsIt() { + final OntologyShapeCheckModel model = new OntologyShapeCheckModel(COLUMN_RELATION, "Mssql"); + final Statements statements = + statements(model, "Order", model.on("orderTotal").withMinInclusive(limit("0"))); + assertEquals( + """ + SELECT COUNT(*) AS violations + FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[total] < 0 + ) c""", + SqlEngineFamily.TSQL.finish(statements.count()).sql()); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java new file mode 100644 index 000000000000..b23428cb5e83 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeCheckValueCasesTest.java @@ -0,0 +1,146 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.openmetadata.service.ontology.OntologyMappingShapes.UNFILTERED_IDENTITY; +import static org.openmetadata.service.ontology.OntologyShapeCheckModel.literals; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.schema.api.data.OntologyCheckedPart; +import org.openmetadata.schema.api.data.OntologyShapeCheck; +import org.openmetadata.schema.api.data.OntologyShapeCheckOutcome; +import org.openmetadata.schema.api.data.OntologyShapeCheckReason; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.service.ontology.OntologyShapeCheckAnswer.Hidden; + +/** + * Sends each key value case of {@code ontology/sql-value-cases.json} that is for one text column + * through an {@code in} list on a text column, once for each service type the case names. A case + * says how its engine family writes the value, or that the value is refused. A check holds the + * written value in the statement it runs, and a refused value leaves the part with no exact test. + * + *

    The expected text of a case is the oracle. A case is never edited to make this test pass. + */ +class OntologyShapeCheckValueCasesTest { + private static final String CASES = "/ontology/sql-value-cases.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String KEY_VALUE = "keyValue"; + private static final String ONE_TEXT_COLUMN = "VARCHAR"; + private static final String RENDERED = "rendered"; + private static final String REFUSED = "refusedAtRequest"; + + /** One case on one service type of the engine family the case is for. */ + private record Run(JsonNode json, String serviceType) { + String outcome() { + return json.at("/expectedOutcome/kind").asText(); + } + + String input() { + return json.get("input").asText(); + } + + @Override + public String toString() { + return json.get("id").asText() + " " + serviceType; + } + } + + static Stream runs() throws IOException { + try (InputStream cases = OntologyShapeCheckValueCasesTest.class.getResourceAsStream(CASES)) { + final List runs = new ArrayList<>(); + for (final JsonNode json : JSON.readTree(cases)) { + if (KEY_VALUE.equals(json.get("path").asText()) + && ONE_TEXT_COLUMN.equals(json.get("columnType").asText())) { + json.get("serviceTypes").forEach(type -> runs.add(new Run(json, type.asText()))); + } + } + return runs.stream(); + } + } + + /** The {@code in} part of a constraint that lists the value of the case, on a text column. */ + private static OntologyCheckedPart listed(final Run run) { + final OntologyShapeCheckModel model = + new OntologyShapeCheckModel(UNFILTERED_IDENTITY, run.serviceType()); + return OntologyShapeCheckAnswer.shapes( + model.facts("Customer"), + List.of( + model.targeting( + "Customer", model.on("customerEmail").withIn(literals(run.input())))), + new Hidden(Set.of(), Set.of(), Set.of())) + .getFirst() + .getConstraints() + .getFirst() + .getParts() + .getFirst(); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("runs") + void aListedValueIsWrittenAsItsCaseSaysOrLeavesNoTest(final Run run) { + final OntologyCheckedPart part = listed(run); + switch (run.outcome()) { + case RENDERED -> assertTheCountHoldsTheWrittenValue(run, part); + case REFUSED -> assertNoTest(part); + default -> fail("No test covers " + run.outcome()); + } + } + + private static void assertTheCountHoldsTheWrittenValue( + final Run run, final OntologyCheckedPart part) { + assertEquals(OntologyShapeCheckOutcome.CHECK, part.getOutcome()); + final OntologyShapeCheck check = part.getChecks().getFirst(); + final String count = + check.getParameterValues().stream() + .filter(parameter -> parameter.getName().equals("sqlExpression")) + .map(TestCaseParameterValue::getValue) + .findFirst() + .orElseThrow(); + + assertEquals("tableCustomSQLQuery", check.getTestDefinition()); + assertTrue( + count.endsWith(" NOT IN (" + run.json().at("/expectedOutcome/text").asText() + ")\n) c"), + count); + } + + private static void assertNoTest(final OntologyCheckedPart part) { + assertEquals(OntologyShapeCheckOutcome.NOT_ENFORCEABLE, part.getOutcome()); + assertEquals(OntologyShapeCheckReason.VALUE_DOES_NOT_FIT_COLUMN, part.getReason()); + assertNull(part.getChecks()); + } + + @Test + void theCaseFileHoldsThirtyEightKeyValuesForOneTextColumn() throws IOException { + final List runs = runs().toList(); + + assertEquals(138, runs.size()); + assertEquals(38, runs.stream().map(run -> run.json().get("id").asText()).distinct().count()); + assertEquals(92, runs.stream().filter(run -> RENDERED.equals(run.outcome())).count()); + assertEquals(46, runs.stream().filter(run -> REFUSED.equals(run.outcome())).count()); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeRulesTest.java new file mode 100644 index 000000000000..8b331bfc7349 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeRulesTest.java @@ -0,0 +1,208 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyProfileViolation; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.service.exception.BadRequestException; + +class OntologyShapeRulesTest { + private static final URI NAME = URI.create("urn:property:name"); + + @Test + void aShapeWithSatisfiableConstraintsHasNoFindings() { + final OntologyShape shape = + shape( + constraint("name-required").withMinCount(1).withMaxCount(1), + constraint("name-pattern").withPattern("^[A-Z][a-z]+$"), + constraint("name-values") + .withIn( + List.of( + new OntologyShapeValue().withLiteral(new OntologyLiteral().withValue("A")), + new OntologyShapeValue().withIri(URI.create("urn:value:b"))))); + + assertEquals(List.of(), validate(shape)); + } + + @Test + void aMinimumAboveTheMaximumCanNeverBeSatisfied() { + final var findings = validate(shape(constraint("c1").withMinCount(3).withMaxCount(2))); + + assertEquals( + List.of( + "SHAPE_CARDINALITY_CONFLICT /constraints/0: minCount 3 is above maxCount 2, so no value count satisfies the constraint"), + findings); + } + + @Test + void anEmptyInListCanNeverBeSatisfied() { + final var findings = validate(shape(constraint("c1").withIn(List.of()))); + + assertEquals( + List.of( + "SHAPE_EMPTY_VALUE_LIST /constraints/0/in: An in list names at least one value, or no value satisfies the constraint"), + findings); + } + + @Test + void aShapeWithMoreConstraintsThanTheCapIsRefusedAtSave() { + final OntologyShapeConstraint[] constraints = + java.util.stream.IntStream.rangeClosed(0, OntologyShapeRules.MAX_CONSTRAINTS) + .mapToObj(index -> constraint("c" + index).withMinCount(1)) + .toArray(OntologyShapeConstraint[]::new); + + final BadRequestException refused = + assertThrows( + BadRequestException.class, () -> OntologyShapeRules.requireValid(shape(constraints))); + + assertEquals("/constraints: A shape holds at most 200 constraints: 201", refused.getMessage()); + assertEquals( + List.of(), + validate( + shape( + java.util.stream.IntStream.range(0, OntologyShapeRules.MAX_CONSTRAINTS) + .mapToObj(index -> constraint("c" + index).withMinCount(1)) + .toArray(OntologyShapeConstraint[]::new)))); + } + + @Test + void aShapeOverTheMemberSizeLimitIsRefusedAtSave() { + final OntologyShape shape = shape(constraint("c1").withMinCount(1)); + shape.setDescription("x".repeat(OntologyReleaseManifest.MAX_MEMBER_BYTES)); + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> OntologyShapeRules.requireValid(shape)); + + assertEquals("An ontology definition exceeds the 1 MiB member limit", refused.getMessage()); + shape.setDescription("x".repeat(1000)); + OntologyShapeRules.requireValid(shape); + } + + @Test + void aRepeatedConstraintIdIsRefused() { + final var findings = + validate(shape(constraint("c1").withMinCount(1), constraint("c1").withMaxCount(2))); + + assertEquals( + List.of( + "SHAPE_INVALID_CONSTRAINT /constraints/1/id: A constraint id is unique within its shape: c1"), + findings); + } + + @Test + void aConstraintThatStatesNothingIsRefused() { + final var findings = validate(shape(constraint("c1"))); + + assertEquals(1, findings.size()); + assertTrue(findings.getFirst().startsWith("SHAPE_INVALID_CONSTRAINT /constraints/0: ")); + } + + @Test + void anIdOutsideTheAllowedAlphabetIsRefused() { + assertEquals( + 1, validate(shape(constraint("has space").withMinCount(1))).size(), "space in the id"); + assertEquals(1, validate(shape(constraint("-leading").withMinCount(1))).size(), "leading dash"); + assertEquals( + 1, validate(shape(constraint("x".repeat(65)).withMinCount(1))).size(), "65 characters"); + } + + @Test + void aRelativeIriIsRefused() { + final OntologyShape shape = + shape(constraint("c1").withMinCount(1).withPath(URI.create("relative"))); + shape.setTargetConcept(URI.create("AlsoRelative")); + + assertEquals( + List.of( + "SHAPE_INVALID_CONSTRAINT /targetConcept: An IRI must be absolute: AlsoRelative", + "SHAPE_INVALID_CONSTRAINT /constraints/0/path: An IRI must be absolute: relative"), + validate(shape)); + } + + @Test + void aPatternThatDoesNotCompileIsRefused() { + final var findings = validate(shape(constraint("c1").withPattern("[unclosed"))); + + assertEquals(1, findings.size()); + assertTrue( + findings.getFirst().startsWith("SHAPE_INVALID_CONSTRAINT /constraints/0/pattern: "), + findings.getFirst()); + } + + @Test + void anInValueNeedsExactlyOneOfAnIriOrALiteral() { + final var both = + new OntologyShapeValue() + .withIri(URI.create("urn:v")) + .withLiteral(new OntologyLiteral().withValue("v")); + final var findings = + validate(shape(constraint("c1").withIn(List.of(both, new OntologyShapeValue())))); + + assertEquals( + List.of( + "SHAPE_INVALID_CONSTRAINT /constraints/0/in/0: An in value is exactly one of an iri or a literal", + "SHAPE_INVALID_CONSTRAINT /constraints/0/in/1: An in value is exactly one of an iri or a literal"), + findings); + } + + @Test + void savingASatisfiableShapeThrowsNothingAndAnInvalidOneNamesTheFirstProblem() { + OntologyShapeRules.requireValid(shape(constraint("c1").withMinCount(1))); + + final var refused = + assertThrows( + BadRequestException.class, + () -> + OntologyShapeRules.requireValid( + shape(constraint("c1").withMinCount(2).withMaxCount(1)))); + assertEquals( + "/constraints/0: minCount 2 is above maxCount 1, so no value count satisfies the constraint", + refused.getMessage()); + } + + private static List validate(final OntologyShape shape) { + return OntologyShapeRules.validate(shape).stream() + .map(OntologyShapeRulesTest::describe) + .toList(); + } + + private static String describe(final OntologyProfileViolation violation) { + return violation.getCode() + " " + violation.getPath() + ": " + violation.getMessage(); + } + + private static OntologyShape shape(final OntologyShapeConstraint... constraints) { + return new OntologyShape() + .withId(UUID.randomUUID()) + .withName("PersonShape") + .withTargetConcept(URI.create("urn:class:Person")) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints(List.of(constraints)); + } + + private static OntologyShapeConstraint constraint(final String id) { + return new OntologyShapeConstraint().withId(id).withPath(NAME); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeValidationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeValidationTest.java new file mode 100644 index 000000000000..ae541b244376 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyShapeValidationTest.java @@ -0,0 +1,213 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.OntologyConceptType; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyReleaseMember; +import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; + +/** What release validation says about the shapes a release holds. */ +class OntologyShapeValidationTest { + private static final OntologyRelease RELEASE = + new OntologyRelease().withId(UUID.randomUUID()).withContentDigest("a".repeat(64)); + private static final URI PERSON = URI.create("urn:class:Person"); + private static final URI ADDRESS = URI.create("urn:class:Address"); + private static final URI NAME = URI.create("urn:property:name"); + private static final URI LIVES_AT = URI.create("urn:property:livesAt"); + + @Test + void aShapeOverDeclaredClassesAndPropertiesIsValid() { + final var report = + validate( + shape( + PERSON, + new OntologyShapeConstraint().withId("name").withPath(NAME).withMinCount(1), + new OntologyShapeConstraint() + .withId("address") + .withPath(LIVES_AT) + .withClassIri(ADDRESS))); + + assertTrue(report.getValid(), report.getViolations().toString()); + } + + @Test + void aTargetClassThatTheReleaseDoesNotDeclareFails() { + assertEquals( + List.of("UNDECLARED_CLASS /targetConcept"), + violations( + shape( + URI.create("urn:class:Missing"), + new OntologyShapeConstraint().withId("name").withPath(NAME).withMinCount(1)))); + } + + @Test + void aPathThatTheReleaseDoesNotDeclareFails() { + assertEquals( + List.of("UNDECLARED_PROPERTY /constraints/0/path"), + violations( + shape( + PERSON, + new OntologyShapeConstraint() + .withId("age") + .withPath(URI.create("urn:property:age")) + .withMinCount(1)))); + } + + @Test + void aClassConstraintThatNamesAMissingClassFails() { + assertEquals( + List.of("UNDECLARED_CLASS /constraints/0/classIri"), + violations( + shape( + PERSON, + new OntologyShapeConstraint() + .withId("address") + .withPath(LIVES_AT) + .withClassIri(URI.create("urn:class:Missing"))))); + } + + @Test + void aMinimumCountAboveTheMaximumFails() { + assertEquals( + List.of("SHAPE_CARDINALITY_CONFLICT /constraints/0"), + violations( + shape( + PERSON, + new OntologyShapeConstraint() + .withId("name") + .withPath(NAME) + .withMinCount(2) + .withMaxCount(1)))); + } + + @Test + void anEmptyInListFails() { + assertEquals( + List.of("SHAPE_EMPTY_VALUE_LIST /constraints/0/in"), + violations( + shape( + PERSON, + new OntologyShapeConstraint() + .withId("name") + .withPath(NAME) + .withIn(List.of())))); + } + + @Test + void aRepeatedConstraintIdFails() { + assertEquals( + List.of("SHAPE_INVALID_CONSTRAINT /constraints/1/id"), + violations( + shape( + PERSON, + new OntologyShapeConstraint().withId("c").withPath(NAME).withMinCount(1), + new OntologyShapeConstraint().withId("c").withPath(NAME).withMaxCount(2)))); + } + + @Test + void aValidShapeOverValidDefinitionsLeavesTheReportValid() { + final var without = validate(null); + final var with = + validate( + shape( + PERSON, + new OntologyShapeConstraint().withId("has-name").withPath(NAME).withMinCount(1), + new OntologyShapeConstraint() + .withId("lives-at") + .withPath(LIVES_AT) + .withClassIri(ADDRESS))); + + assertTrue(without.getValid()); + assertTrue(with.getValid()); + assertEquals(0, without.getViolationCount()); + assertEquals(0, with.getViolationCount()); + assertEquals(List.of(), with.getViolations()); + } + + private static List violations(final OntologyShape shape) { + final var report = validate(shape); + assertEquals(false, report.getValid()); + return report.getViolations().stream() + .map(issue -> issue.getViolation().getCode() + " " + issue.getViolation().getPath()) + .toList(); + } + + private static org.openmetadata.schema.api.data.OntologyReleaseStructureReport validate( + final OntologyShape shape) { + final List members = new ArrayList<>(); + members.add(member(MemberKind.CONCEPT, concept(PERSON))); + members.add(member(MemberKind.CONCEPT, concept(ADDRESS))); + members.add(member(MemberKind.PROPERTY, property(NAME, OntologyPropertyKind.DATA))); + members.add(member(MemberKind.PROPERTY, property(LIVES_AT, OntologyPropertyKind.OBJECT))); + if (shape != null) { + members.add(member(MemberKind.SHAPE, shape)); + } + return OntologyStructureValidator.validate(RELEASE, members); + } + + private static OntologyShape shape( + final URI target, final OntologyShapeConstraint... constraints) { + return new OntologyShape() + .withId(UUID.randomUUID()) + .withName("PersonShape") + .withTargetConcept(target) + .withSeverity(OntologyShapeSeverity.VIOLATION) + .withConstraints(List.of(constraints)) + .withOntology(ontology()); + } + + private static OntologyConcept concept(final URI iri) { + return new OntologyConcept() + .withId(UUID.randomUUID()) + .withIri(iri) + .withConceptType(OntologyConceptType.OWL_CLASS) + .withOntology(ontology()); + } + + private static OntologyProperty property(final URI iri, final OntologyPropertyKind kind) { + return new OntologyProperty() + .withId(UUID.randomUUID()) + .withIri(iri) + .withKind(kind) + .withOntology(ontology()); + } + + private static EntityReference ontology() { + return new EntityReference().withId(RELEASE.getId()).withType("ontology"); + } + + private static OntologyReleaseMember member( + final MemberKind kind, final OntologyDefinition definition) { + return OntologyReleaseManifest.member( + RELEASE.getId(), kind, definition.getId(), OntologyReleaseContent.project(definition)); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologySqlValueCasesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologySqlValueCasesTest.java new file mode 100644 index 000000000000..72b9b9260d92 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologySqlValueCasesTest.java @@ -0,0 +1,424 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.abort; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyAssetBinding; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.BoundConcept; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.BoundTable; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.Hop; +import org.openmetadata.service.ontology.sql.BoundStatement; +import org.openmetadata.service.ontology.sql.ParsedValue; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; +import org.openmetadata.service.ontology.sql.TypedRowFilter; +import org.openmetadata.service.ontology.sql.TypedStatement; +import org.openmetadata.service.ontology.sql.TypedValue; +import org.openmetadata.service.ontology.sql.TypedValues; + +/** + * Runs the cases of {@code ontology/sql-value-cases.json}. A case gives a value, a name or a label + * as it can arrive, the data type of the column it is for, and what must happen to it on one + * engine family: the exact text it is written as, the parameters a driver binds, or the refusal. A + * case for every family runs once per family when its outcome depends on the family. + * + *

    The expected text of a case is the oracle. A case is never edited to make this test pass. + */ +class OntologySqlValueCasesTest { + private static final String CASES = "/ontology/sql-value-cases.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String EVERY_FAMILY = "any"; + private static final int FORBIDDEN = 403; + + /** How each family writes a lowercase name that is no reserved word, such as a case's column. */ + private static final Map PLAIN_NAME = + Map.of( + SqlEngineFamily.POSTGRES, "%s", + SqlEngineFamily.REDSHIFT, "%s", + SqlEngineFamily.TRINO, "%s", + SqlEngineFamily.MYSQL, "`%s`", + SqlEngineFamily.CLICKHOUSE, "`%s`", + SqlEngineFamily.BIGQUERY, "`%s`", + SqlEngineFamily.SNOWFLAKE, "\"%s\"", + SqlEngineFamily.SPARK, "`%s`", + SqlEngineFamily.TSQL, "[%s]"); + + private static final Map A_SERVICE_TYPE = + Map.of( + SqlEngineFamily.POSTGRES, "Postgres", + SqlEngineFamily.REDSHIFT, "Redshift", + SqlEngineFamily.TRINO, "Trino", + SqlEngineFamily.MYSQL, "Mysql", + SqlEngineFamily.CLICKHOUSE, "Clickhouse", + SqlEngineFamily.BIGQUERY, "BigQuery", + SqlEngineFamily.SNOWFLAKE, "Snowflake", + SqlEngineFamily.SPARK, "Databricks", + SqlEngineFamily.TSQL, "Mssql"); + + private static final Map OPERATORS = Map.of("equals", " = ", "in", " IN "); + + /** One case on one engine family, or on none when its outcome is the same on every family. */ + private record Run(JsonNode json, SqlEngineFamily family) { + String kind() { + return json.get("path").asText() + " " + json.at("/expectedOutcome/kind").asText(); + } + + Object input() { + return JSON.convertValue(json.get("input"), Object.class); + } + + String expectedText() { + return json.at("/expectedOutcome/text").asText(); + } + + List expected(final String field) { + final List texts = new ArrayList<>(); + json.at("/expectedOutcome/" + field).forEach(text -> texts.add(text.asText())); + return texts; + } + + @Override + public String toString() { + final String id = json.get("id").asText(); + return family == null ? id : id + " " + family.name().toLowerCase(Locale.ROOT); + } + } + + static Stream runs() throws IOException { + try (InputStream cases = OntologySqlValueCasesTest.class.getResourceAsStream(CASES)) { + final List runs = new ArrayList<>(); + JSON.readTree(cases).forEach(json -> runs.addAll(runsOf(json))); + return runs.stream(); + } + } + + private static List runsOf(final JsonNode json) { + final String family = json.get("engineFamily").asText(); + if (!EVERY_FAMILY.equals(family)) { + return List.of(new Run(json, SqlEngineFamily.valueOf(family.toUpperCase(Locale.ROOT)))); + } + final String outcome = json.at("/expectedOutcome/kind").asText(); + final boolean writesSql = List.of("rendered", "bound").contains(outcome); + return writesSql + ? Arrays.stream(SqlEngineFamily.values()).map(each -> new Run(json, each)).toList() + : List.of(new Run(json, null)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("runs") + void eachCaseIsWrittenBoundOrRefusedAsItSays(final Run run) { + skipWhatAnotherTestOwns(run); + switch (run.kind()) { + case "rowFilterValue rendered" -> assertEquals( + plainName(run) + operator(run) + run.expectedText(), + written(run, sql -> saved(run).appendTo(sql, null))); + case "rowFilterValue refusedAtSave" -> assertRefused(run, () -> saved(run)); + case "rowFilterValue refusedAtBuild" -> assertRefused(run, () -> builtFromStored(run)); + case "rowFilterValue bound" -> assertRowFilterValueIsBound(run); + case "keyValue rendered" -> assertEquals( + run.expectedText(), + key(run).stream() + .map(part -> written(run, sql -> sql.value(part))) + .collect(Collectors.joining(" | "))); + case "keyValue refusedAtRequest" -> assertRefused(run, () -> key(run)); + case "keyValue bound" -> assertKeyValueIsBound(run); + case "searchText rendered" -> assertEquals( + run.expectedText(), written(run, sql -> sql.contains(searchText(run)))); + case "searchText refusedAtRequest" -> assertRefused(run, () -> searchText(run)); + case "identifier rendered" -> assertEquals( + run.expectedText(), written(run, sql -> sql.name((String) run.input()))); + case "identifier refusedAtBuild" -> assertRefused( + run, () -> TypedStatement.builder().name((String) run.input())); + case "identifier bound" -> assertANameThatLooksLikeAParameterIsNotOne(run); + case "commentText rendered" -> assertTheLabelStaysOutOfTheStatement(run); + default -> fail("No test covers " + run.kind()); + } + } + + @Test + void everyServiceTypeACaseNamesBelongsToTheFamilyOfThatCase() throws IOException { + final List ofOneFamily = + runs() + .filter(run -> !EVERY_FAMILY.equals(run.json().get("engineFamily").asText())) + .toList(); + + assertEquals(599, ofOneFamily.size()); + for (final Run run : ofOneFamily) { + for (final JsonNode type : run.json().get("serviceTypes")) { + assertEquals(run.family(), SqlEngineFamily.ofServiceType(type.asText()), run::toString); + } + } + } + + /** + * Constraint values belong to the tests generated from shapes and stored counts to the job that + * stores them. Neither exists in this code. A write the authorizer refuses needs a server and a + * caller without the right, so OntologyRowFilterValueIT runs those cases. One of them writes + * through a change set, and OntologyChangeSetBindingIT applies that change set. + */ + private static void skipWhatAnotherTestOwns(final Run run) { + if (run.kind().startsWith("constraintValue ")) { + abort("Constraint values belong to the tests generated from shapes"); + } + if (run.kind().endsWith(" countWithheld")) { + abort("Stored counts are no part of SQL generation"); + } + if (run.json().at("/expectedOutcome/status").asInt() == FORBIDDEN) { + abort( + run.json().at("/input/via").isMissingNode() + ? "OntologyRowFilterValueIT sends this write as a caller without the right" + : "OntologyChangeSetBindingIT applies this change set as a caller without the right"); + } + } + + private static String written(final Run run, final Consumer parts) { + return run.family().inline(statement(parts)); + } + + private static TypedStatement statement(final Consumer parts) { + final TypedStatement.Builder sql = TypedStatement.builder(); + parts.accept(sql); + return sql.build(); + } + + private static String plainName(final Run run) { + return String.format(PLAIN_NAME.get(run.family()), run.json().at("/column/0").asText()); + } + + private static String operator(final Run run) { + return OPERATORS.get(run.json().get("operator").asText()); + } + + /** What a write of a binding runs on its row filter: the shape rules, then the typed check. */ + private static TypedRowFilter saved(final Run run) { + final OntologyRowFilter filter = filter(run); + OntologyBindingRules.validate( + new OntologyAssetBinding() + .withAssetType(OntologyBindingAssetType.TABLE) + .withAssetId(UUID.randomUUID()) + .withRowFilter(filter)); + return OntologyTableBindingChecks.typedRowFilter(table(run), filter); + } + + /** + * What a statement runs on a stored binding when it reads the table: the filter is parsed again, + * with no shape rule. + */ + private static TypedRowFilter builtFromStored(final Run run) { + final BindingRow stored = + new BindingRow( + UUID.randomUUID(), + UUID.randomUUID(), + OntologyBindingAssetType.TABLE, + "hash", + List.of(), + null, + null, + filter(run)); + return OntologyBoundTables.of(table(run), stored, Map.of()).rowFilter().get(); + } + + private static OntologyRowFilter filter(final Run run) { + return new OntologyRowFilter() + .withColumn(List.of(run.json().at("/column/0").asText())) + .withOperator(OntologyRowFilterOperator.fromValue(run.json().get("operator").asText())) + .withValue(run.input()); + } + + private static Table table(final Run run) { + return new Table().withFullyQualifiedName("svc.db.sales.orders").withColumns(columns(run)); + } + + /** The case names one column path and type, or a list of paths and as many types. */ + private static List columns(final Run run) { + final JsonNode column = run.json().get("column"); + final String[] types = run.json().get("columnType").asText().split(","); + final List paths = new ArrayList<>(); + if (column.get(0).isArray()) { + column.forEach(paths::add); + } else { + paths.add(column); + } + return IntStream.range(0, paths.size()) + .mapToObj(index -> column(paths.get(index).get(0).asText(), types[index])) + .toList(); + } + + private static Column column(final String name, final String type) { + return new Column().withName(name).withDataType(ColumnDataType.fromValue(type)); + } + + private static List key(final Run run) { + final Object input = run.input(); + return TypedValues.key( + columns(run), input instanceof List parts ? parts : Collections.singletonList(input)); + } + + private static TypedValue searchText(final Run run) { + return TypedValues.searchText(columns(run).getFirst(), (String) run.input()); + } + + private static void assertRefused(final Run run, final Executable call) { + final BadRequestException refusal = assertThrows(BadRequestException.class, call); + + assertEquals(400, refusal.getResponse().getStatus()); + for (final String words : run.expected("messageContains")) { + assertTrue(refusal.getMessage().contains(words), refusal::getMessage); + } + } + + private static void assertRowFilterValueIsBound(final Run run) { + final BoundStatement bound = + run.family().bind(statement(sql -> saved(run).appendTo(sql, null))); + + assertEquals(plainName(run) + " = :p0", bound.text()); + assertEquals(parsed(run.json().at("/expectedOutcome/parameters")), parameters(bound)); + for (final String value : run.expected("textMustNotContain")) { + assertFalse(bound.text().contains(value), bound::text); + } + } + + /** The case gives no catalog type, so the key column is character data. */ + private static void assertKeyValueIsBound(final Run run) { + final Column id = column("id", "VARCHAR"); + final TypedValue part = TypedValues.key(List.of(id), List.of(run.input())).getFirst(); + + final BoundStatement bound = + run.family() + .bind( + statement( + sql -> + sql.sql("SELECT COUNT(*) FROM t WHERE ") + .name("id") + .sql(" = ") + .value(part))); + + assertEquals(List.of(new ParsedValue.Text((String) run.input())), parameters(bound)); + assertFalse(bound.text().contains((String) run.input()), bound::text); + for (final String value : run.expected("textMustNotContain")) { + assertFalse(bound.text().contains(value), bound::text); + } + } + + private static void assertANameThatLooksLikeAParameterIsNotOne(final Run run) { + final String name = (String) run.input(); + final JsonNode parameters = run.json().at("/expectedOutcome/parameters"); + final TypedValue value = TypedValues.value(column(name, "VARCHAR"), parameters.get(0).asText()); + + final BoundStatement bound = + run.family() + .bind( + statement( + sql -> + sql.sql("SELECT COUNT(*) FROM t WHERE ") + .name(name) + .sql(" = ") + .value(value))); + + assertEquals(run.expectedText(), bound.text()); + assertEquals( + run.json().at("/expectedOutcome/bindParameterCount").asInt(), bound.parameters().size()); + assertEquals(parsed(parameters), parameters(bound)); + } + + private static void assertTheLabelStaysOutOfTheStatement(final Run run) { + final String sql = statementOverAHopLabelled((String) run.input(), run.family()); + + assertTrue(sql.contains("\nJOIN "), sql); + for (final String forbidden : run.expected("statementMustNotContain")) { + assertFalse(sql.contains(forbidden), sql); + } + } + + private static String statementOverAHopLabelled( + final String label, final SqlEngineFamily family) { + final String serviceType = A_SERVICE_TYPE.get(family); + final BoundTable customers = + new BoundTable( + "svc.db.sales.customers", + serviceType, + List.of(List.of("name")), + Map.of(), + List.of(), + List.of()); + final TableConstraint toCustomers = + new TableConstraint() + .withConstraintType(TableConstraint.ConstraintType.FOREIGN_KEY) + .withColumns(List.of("customer_id")) + .withReferredColumns(List.of("svc.db.sales.customers.customer_id")); + final BoundTable orders = + new BoundTable( + "svc.db.sales.orders", + serviceType, + List.of(List.of("order_id")), + Map.of(), + List.of(), + List.of(toCustomers)); + final Hop hop = + new Hop(UUID.randomUUID(), null, label, new BoundConcept("Customer", List.of(customers))); + return OntologyConceptSqlGenerator.generate( + new BoundConcept("Order", List.of(orders)), List.of(hop)) + .sql(); + } + + private static List parameters(final BoundStatement bound) { + return bound.parameters().stream().map(TypedValue::parsed).toList(); + } + + /** The parsed form of each expected parameter: a JSON string is text, a JSON integer a number. */ + private static List parsed(final JsonNode parameters) { + final List parsed = new ArrayList<>(); + parameters.forEach( + parameter -> + parsed.add( + parameter.isTextual() + ? new ParsedValue.Text(parameter.asText()) + : new ParsedValue.WholeNumber(BigInteger.valueOf(parameter.asLong())))); + return parsed; + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java new file mode 100644 index 000000000000..dac39c361095 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenTest.java @@ -0,0 +1,81 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.service.ontology.OntologyStatementGoldens.Golden; + +/** + * Holds every statement about records to the SQL text that a person read and committed: nine + * engine families, fourteen mapping shapes (seven that hold the other statements and seven that + * hold the link counts of a relation) and each statement that applies to a shape. The test reads + * the files and never writes one. + */ +class OntologyStatementGoldenTest { + private static final int FAMILIES = 9; + private static final int STATEMENTS_OF_THE_SHAPES = 55; + + static List goldens() { + return OntologyStatementGoldens.all(); + } + + @ParameterizedTest + @MethodSource("goldens") + void aStatementIsTheTextOfItsGoldenFile(final Golden golden) throws IOException { + try (InputStream file = + OntologyStatementGoldenTest.class.getResourceAsStream("/" + golden.resource())) { + assertNotNull(file, "No golden file " + golden.resource()); + assertEquals(new String(file.readAllBytes(), StandardCharsets.UTF_8), golden.text()); + } + } + + @ParameterizedTest + @MethodSource("goldens") + void aStatementPlansTheColumnsThatItsShapeNames(final Golden golden) { + assertEquals(golden.ask().columns(), golden.columns()); + } + + @Test + void everyGoldenFileBelongsToAStatement() throws IOException, URISyntaxException { + final Path directory = + Path.of( + OntologyStatementGoldenTest.class + .getResource("/" + OntologyStatementGoldens.DIRECTORY) + .toURI()); + try (Stream files = Files.walk(directory)) { + assertEquals( + goldens().stream().map(Golden::resource).sorted().toList(), + files + .filter(Files::isRegularFile) + .map(file -> OntologyStatementGoldens.DIRECTORY + "/" + directory.relativize(file)) + .map(path -> path.replace('\\', '/')) + .sorted() + .toList()); + } + assertEquals(FAMILIES * STATEMENTS_OF_THE_SHAPES, goldens().size()); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenWriter.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenWriter.java new file mode 100644 index 000000000000..adb15c91936d --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldenWriter.java @@ -0,0 +1,46 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.openmetadata.service.ontology.OntologyStatementGoldens.Golden; + +/** + * Writes the golden SQL files that do not exist yet. It never replaces a file: to write one again, + * delete it, run {@code scripts/write-ontology-statement-goldens.sh}, and read the new text before + * committing it. No test run starts this class, because its name matches no test pattern and it + * needs the system property below. + */ +class OntologyStatementGoldenWriter { + @Test + @EnabledIfSystemProperty(named = "ontology.statement.goldens", matches = "write") + void writesTheGoldensThatDoNotExist() throws IOException { + final Path resources = Path.of(System.getProperty("basedir", "."), "src", "test", "resources"); + assertTrue(Files.isDirectory(resources), "Run it from the openmetadata-service module"); + for (final Golden golden : OntologyStatementGoldens.all()) { + final Path file = resources.resolve(golden.resource()); + if (Files.notExists(file)) { + Files.createDirectories(file.getParent()); + Files.writeString(file, golden.text(), StandardOpenOption.CREATE_NEW); + } + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java new file mode 100644 index 000000000000..5b177fcb4936 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStatementGoldens.java @@ -0,0 +1,97 @@ +/* + * 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.ontology; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Stream; +import org.openmetadata.service.ontology.OntologyConceptSqlGenerator.RecordStatement; +import org.openmetadata.service.ontology.OntologyMappingShapes.Ask; +import org.openmetadata.service.ontology.OntologyMappingShapes.Shape; +import org.openmetadata.service.ontology.sql.SqlEngineFamily; + +/** + * The golden SQL of the statements about records: one file for each engine family, mapping shape + * and statement. {@link OntologyStatementGoldenWriter} writes a file that does not exist yet, and + * {@link OntologyStatementGoldenTest} only reads them. + */ +final class OntologyStatementGoldens { + static final String DIRECTORY = OntologyMappingShapes.GOLDEN_STATEMENTS; + + /** The service type whose statements stand for its engine family. */ + static final Map SERVICE_TYPES = serviceTypes(); + + private OntologyStatementGoldens() {} + + /** One statement of one shape as one engine family writes it. */ + record Golden(SqlEngineFamily family, Shape shape, Ask ask) { + /** The path of the file under the test resources. */ + String resource() { + return shape.golden(family.name().toLowerCase(Locale.ROOT), ask); + } + + /** The text of the file: the statement for a person to read, and a line break. */ + String text() { + final RecordStatement statement = statement(); + return statement.family().finish(statement.text()).sql() + "\n"; + } + + /** What each result column of the statement holds, one line for each. */ + List columns() { + return OntologyMappingShapeModel.plan(statement()); + } + + private RecordStatement statement() { + return new OntologyMappingShapeModel(shape, SERVICE_TYPES.get(family)).statement(ask); + } + + @Override + public String toString() { + return resource(); + } + } + + static List all() { + final List goldens = new ArrayList<>(); + for (final SqlEngineFamily family : SERVICE_TYPES.keySet()) { + for (final Shape shape : shapes()) { + shape.asks().forEach(ask -> goldens.add(new Golden(family, shape, ask))); + } + } + return goldens; + } + + /** The seven mapping shapes, then the seven that hold the link counts of a relation. */ + static List shapes() { + return Stream.concat(OntologyMappingShapes.all().stream(), OntologyLinkShapes.all().stream()) + .toList(); + } + + private static Map serviceTypes() { + final Map types = new LinkedHashMap<>(); + types.put(SqlEngineFamily.POSTGRES, "Postgres"); + types.put(SqlEngineFamily.REDSHIFT, "Redshift"); + types.put(SqlEngineFamily.TRINO, "Trino"); + types.put(SqlEngineFamily.MYSQL, "Mysql"); + types.put(SqlEngineFamily.CLICKHOUSE, "Clickhouse"); + types.put(SqlEngineFamily.BIGQUERY, "BigQuery"); + types.put(SqlEngineFamily.SNOWFLAKE, "Snowflake"); + types.put(SqlEngineFamily.SPARK, "Databricks"); + types.put(SqlEngineFamily.TSQL, "Mssql"); + return types; + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStructureValidatorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStructureValidatorTest.java index 10f151b7129f..dde690b60c5e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStructureValidatorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyStructureValidatorTest.java @@ -26,6 +26,7 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.OntologyAxiomType; import org.openmetadata.schema.type.OntologyConceptType; @@ -37,6 +38,7 @@ import org.openmetadata.schema.type.OntologyReleaseMember; import org.openmetadata.schema.type.OntologyReleaseMember.MemberKind; import org.openmetadata.schema.type.OntologyRestrictionKind; +import org.openmetadata.schema.type.OntologyShapeConstraint; import org.openmetadata.schema.type.RelationshipCharacteristic; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.exception.OntologyValidationException; @@ -587,6 +589,37 @@ void deletionImpactListsChildrenRelationshipsRulesAndBlockers() { assertEquals(List.of("eats"), names(impact.getBlockers())); } + @Test + void aLiveShapeThatNamesTheConceptBlocksItsDeletion() { + final var person = named(concept("Person"), "Person"); + final var address = named(concept("Address"), "Address"); + final var names = named(shape(person.getIri(), address.getIri()), "names-person"); + final var elsewhere = + named(shape(address.getIri(), URI.create("urn:other")), "names-address-only"); + final var gone = named(shape(person.getIri(), address.getIri()), "deleted").withDeleted(true); + + final var impact = + OntologyStructureValidator.deletionImpact( + person, List.of(person, address, names, elsewhere, gone)); + + assertEquals(List.of("names-person"), names(impact.getBlockers())); + assertEquals(List.of(), impact.getRules()); + assertEquals(List.of(), impact.getRelationships()); + } + + private static OntologyShape shape(URI target, URI required) { + return new OntologyShape() + .withId(UUID.randomUUID()) + .withOntology(new EntityReference().withId(UUID.randomUUID()).withType("ontology")) + .withTargetConcept(target) + .withConstraints( + List.of( + new OntologyShapeConstraint() + .withId("c1") + .withPath(URI.create("urn:p")) + .withClassIri(required))); + } + @Test void deletionImpactIgnoresDefinitionsThatDoNotNameTheConcept() { final var animal = named(concept("Animal"), "Animal"); @@ -793,6 +826,33 @@ void draftValidationReportsEveryClashAsAnErrorThatASingleSaveCouldNotSee() { .getValid()); } + @Test + void aClassHasAtMostOneDisplayNameProperty() { + final var customer = concept("Customer"); + final var order = concept("Order"); + final var name = displayName("name", customer); + final var label = displayName("label", customer); + final var orderName = displayName("orderName", order); + final var both = displayName("both", customer, order); + + assertEquals(List.of(), violations(customer, order, name, orderName)); + assertEquals( + List.of("DUPLICATE_DISPLAY_NAME /isDisplayName", "DUPLICATE_DISPLAY_NAME /isDisplayName"), + violations(customer, name, label)); + assertEquals( + List.of("DUPLICATE_DISPLAY_NAME /isDisplayName", "DUPLICATE_DISPLAY_NAME /isDisplayName"), + violations(customer, order, orderName, both)); + final String pair = + "A class has at most one display-name property, but %s and %s both name the same class"; + assertEquals( + List.of( + pair.formatted(label.getIri(), name.getIri()), + pair.formatted(name.getIri(), label.getIri())), + messages(customer, name, label)); + assertEquals(List.of(), violations(customer, name, label.withIsDisplayName(null))); + assertEquals(List.of(), violations(customer, name, label.withIsDisplayName(false))); + } + private static OntologyReleaseStructureReport validate(OntologyDefinition... definitions) { return OntologyStructureValidator.validate( RELEASE, Arrays.stream(definitions).map(value -> member(RELEASE.getId(), value)).toList()); @@ -833,6 +893,12 @@ private static OntologyProperty property(URI iri, OntologyPropertyKind kind) { return new OntologyProperty().withId(UUID.randomUUID()).withIri(iri).withKind(kind); } + private static OntologyProperty displayName(String name, OntologyConcept... classes) { + return property(URI.create("urn:property:" + name), OntologyPropertyKind.DATA) + .withDomain(Arrays.stream(classes).map(OntologyConcept::getIri).toList()) + .withIsDisplayName(true); + } + private static OntologyConcept concept(String name) { return new OntologyConcept() .withId(UUID.randomUUID()) diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableBindingChecksTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableBindingChecksTest.java new file mode 100644 index 000000000000..e0859640e56d --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableBindingChecksTest.java @@ -0,0 +1,126 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigInteger; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.ontology.sql.ParsedValue; +import org.openmetadata.service.ontology.sql.TypedRowFilter; +import org.openmetadata.service.ontology.sql.TypedValue; + +class OntologyTableBindingChecksTest { + private static final Table ORDERS = + new Table() + .withFullyQualifiedName("svc.db.sales.orders") + .withColumns( + List.of( + column("status", ColumnDataType.VARCHAR), + column("qty", ColumnDataType.INT), + column("address", ColumnDataType.STRUCT) + .withChildren(List.of(column("city", ColumnDataType.VARCHAR))))); + + @Test + void aRowFilterValueIsParsedAsTheDataTypeOfTheFilterColumn() { + final TypedRowFilter typed = + OntologyTableBindingChecks.typedRowFilter( + ORDERS, filter(List.of("qty"), OntologyRowFilterOperator.IN, List.of(5, "6"))); + + assertEquals(List.of("qty"), typed.column()); + assertEquals(OntologyRowFilterOperator.IN, typed.operator()); + assertEquals( + List.of( + new ParsedValue.WholeNumber(BigInteger.valueOf(5)), + new ParsedValue.WholeNumber(BigInteger.valueOf(6))), + typed.values().stream().map(TypedValue::parsed).toList()); + } + + @Test + void aRowFilterValueOfAnotherTypeIsRefusedWithTheColumnTheTypeAndWhatTheTypeExpects() { + assertRefused( + "The value for column qty does not parse as INT: a whole number is written in ASCII" + + " digits, with a leading minus sign when negative and no leading zeros", + filter(List.of("qty"), OntologyRowFilterOperator.EQUALS, "5 OR 1=1")); + assertRefused( + "The value for column status does not parse as VARCHAR: a string or a number is expected", + filter(List.of("status"), OntologyRowFilterOperator.NOT_EQUALS, true)); + assertRefused( + "The value for column status must not hold a control character", + filter(List.of("status"), OntologyRowFilterOperator.EQUALS, "open\n-- ")); + } + + @Test + void aRowFilterOnANestedColumnIsParsedAsTheDataTypeOfThatColumn() { + final List city = List.of("address", "city"); + + final TypedRowFilter typed = + OntologyTableBindingChecks.typedRowFilter( + ORDERS, filter(city, OntologyRowFilterOperator.EQUALS, "Paris")); + + assertEquals(city, typed.column()); + assertEquals( + List.of(new ParsedValue.Text("Paris")), + typed.values().stream().map(TypedValue::parsed).toList()); + } + + @Test + void aColumnWhoseDataTypeHasNoWrittenFormTakesANullTestOnly() { + assertRefused( + "SQL generation does not support column type STRUCT of column address", + filter(List.of("address"), OntologyRowFilterOperator.EQUALS, "x")); + assertEquals( + List.of(), + OntologyTableBindingChecks.typedRowFilter( + ORDERS, filter(List.of("address"), OntologyRowFilterOperator.IS_NOT_NULL, null)) + .values()); + } + + @Test + void aRowFilterOnAColumnTheTableLacksIsRefused() { + assertRefused( + "A row filter column must exist in the bound table", + filter(List.of("state"), OntologyRowFilterOperator.EQUALS, "open")); + assertRefused( + "A row filter column must exist in the bound table", + filter(List.of("address", "zip"), OntologyRowFilterOperator.IS_NULL, null)); + } + + private static void assertRefused(final String message, final OntologyRowFilter filter) { + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> OntologyTableBindingChecks.typedRowFilter(ORDERS, filter)); + + assertEquals(message, refusal.getMessage()); + assertEquals(400, refusal.getResponse().getStatus()); + } + + private static OntologyRowFilter filter( + final List column, final OntologyRowFilterOperator operator, final Object value) { + return new OntologyRowFilter().withColumn(column).withOperator(operator).withValue(value); + } + + private static Column column(final String name, final ColumnDataType type) { + return new Column().withName(name).withDataType(type); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java new file mode 100644 index 000000000000..da0cb51b3e13 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/OntologyTableMappingRulesTest.java @@ -0,0 +1,781 @@ +/* + * 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.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.api.data.OntologyStatementVersion; +import org.openmetadata.schema.api.data.OntologyStatementVersionRead; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.entity.data.OntologyProperty; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyBindingAssetType; +import org.openmetadata.schema.type.OntologyBindingRole; +import org.openmetadata.schema.type.OntologyColumnBinding; +import org.openmetadata.schema.type.OntologyColumnJoin; +import org.openmetadata.schema.type.OntologyJoinColumnPair; +import org.openmetadata.schema.type.OntologyJoinStatus; +import org.openmetadata.schema.type.OntologyPropertyKind; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.jdbi3.OntologyConceptBindingDAO.BindingRow; +import org.openmetadata.service.ontology.OntologyTableMapping.Applies; +import org.openmetadata.service.ontology.OntologyTableMapping.Broken; +import org.openmetadata.service.ontology.OntologyTableMapping.ClassMapping; +import org.openmetadata.service.ontology.OntologyTableMapping.TableBinding; +import org.openmetadata.service.ontology.OntologyTableMappingRules.Facts; + +class OntologyTableMappingRulesTest { + private static final String NS = "https://example.org/"; + private static final OntologyStatementVersionRead VERSION = + new OntologyStatementVersionRead().withKind(OntologyStatementVersion.DRAFT); + + /** A small world that each test fills in and reads through {@link #build}. */ + private static final class World { + private long next = 1; + private final List rows = new ArrayList<>(); + private final Map tables = new HashMap<>(); + private final Set viewableTables = new HashSet<>(); + private final Map classes = new HashMap<>(); + private final Set viewableClasses = new HashSet<>(); + private final Map properties = new HashMap<>(); + private final Set viewableProperties = new HashSet<>(); + private final Map> parents = new HashMap<>(); + + UUID id() { + return new UUID(0, next++); + } + + OntologyConcept type(final String name) { + final OntologyConcept type = + new OntologyConcept().withId(id()).withName(name).withIri(URI.create(NS + name)); + classes.put(type.getId(), type); + viewableClasses.add(type.getId()); + return type; + } + + OntologyConcept hiddenType(final String name) { + final OntologyConcept type = type(name); + viewableClasses.remove(type.getId()); + return type; + } + + Table table(final String name, final String... columns) { + final List list = new ArrayList<>(); + for (final String column : columns) { + list.add(new Column().withName(column).withDataType(ColumnDataType.INT)); + } + final Table table = + new Table() + .withId(id()) + .withName(name) + .withFullyQualifiedName("svc.db.public." + name) + .withColumns(list); + tables.put(table.getId(), table); + viewableTables.add(table.getId()); + return table; + } + + Table hiddenTable(final String name, final String... columns) { + final Table table = table(name, columns); + viewableTables.remove(table.getId()); + return table; + } + + OntologyProperty data(final String name) { + return property(name, OntologyPropertyKind.DATA, List.of()); + } + + OntologyProperty relation(final String name, final String... range) { + return property( + name, + OntologyPropertyKind.OBJECT, + List.of(range).stream().map(iri -> URI.create(NS + iri)).toList()); + } + + private OntologyProperty property( + final String name, final OntologyPropertyKind kind, final List range) { + final OntologyProperty property = + new OntologyProperty() + .withId(id()) + .withName(name) + .withIri(URI.create(NS + name)) + .withKind(kind) + .withRange(range); + properties.put(property.getId(), property); + viewableProperties.add(property.getId()); + return property; + } + + OntologyProperty hiddenProperty(final String name) { + final OntologyProperty property = data(name); + viewableProperties.remove(property.getId()); + return property; + } + + void bind( + final OntologyConcept type, + final Table table, + final OntologyBindingRole role, + final String key, + final OntologyColumnBinding... columns) { + bind(type, table, role, key, null, columns); + } + + void bind( + final OntologyConcept type, + final Table table, + final OntologyBindingRole role, + final String key, + final OntologyRowFilter filter, + final OntologyColumnBinding... columns) { + rows.add( + new BindingRow( + type.getId(), + table.getId(), + OntologyBindingAssetType.TABLE, + "hash", + List.of(columns), + role, + key == null ? null : List.of(List.of(key)), + filter)); + } + + OntologyTableMapping build() { + return OntologyTableMappingRules.build( + new Facts( + VERSION, + rows, + tables, + viewableTables, + classes, + viewableClasses, + properties, + viewableProperties, + parents)); + } + } + + private static OntologyColumnBinding column(final OntologyProperty property, final String path) { + return new OntologyColumnBinding() + .withPropertyId(property.getId()) + .withColumnPath(List.of(path)); + } + + private static OntologyColumnBinding link( + final OntologyProperty relation, + final String path, + final Table target, + final OntologyJoinStatus status) { + return column(relation, path) + .withJoin( + new OntologyColumnJoin() + .withTargetAssetId(target.getId()) + .withStatus(status) + .withOn( + List.of( + new OntologyJoinColumnPair() + .withChild(List.of(path)) + .withParent(List.of("id"))))); + } + + private static List names(final ClassMapping mapping) { + return mapping.tables().stream().map(bound -> bound.table().fullyQualifiedName()).toList(); + } + + @Test + void aClassListsItsIdentityTableThenContributingTablesByNameThenUnassignedTablesByName() { + final World world = new World(); + final OntologyConcept customer = world.type("Customer"); + world.bind(customer, world.table("zeta", "id"), OntologyBindingRole.IDENTITY, "id"); + world.bind(customer, world.table("mid", "id"), OntologyBindingRole.CONTRIBUTING, "id"); + world.bind(customer, world.table("beta", "id"), null, null); + world.bind(customer, world.table("alpha", "id"), OntologyBindingRole.CONTRIBUTING, "id"); + world.bind(customer, world.table("aaa", "id"), null, null); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(1, mapping.classes().size()); + assertEquals(NS + "Customer", mapping.classes().getFirst().iri().toString()); + assertEquals( + List.of( + "svc.db.public.zeta", + "svc.db.public.alpha", + "svc.db.public.mid", + "svc.db.public.aaa", + "svc.db.public.beta"), + names(mapping.classes().getFirst())); + assertEquals( + Arrays.asList( + OntologyBindingRole.IDENTITY, + OntologyBindingRole.CONTRIBUTING, + OntologyBindingRole.CONTRIBUTING, + null, + null), + mapping.classes().getFirst().tables().stream().map(TableBinding::role).toList()); + assertEquals(0, mapping.hiddenTables()); + assertEquals(0, mapping.hiddenClasses()); + assertEquals(0, mapping.hiddenProperties()); + } + + @Test + void classesComeInIriOrderAndColumnsInBindingOrder() { + final World world = new World(); + final OntologyProperty name = world.data("name"); + final OntologyProperty age = world.data("age"); + final Table people = world.table("people", "id", "age", "name"); + world.bind( + world.type("Zebra"), + people, + OntologyBindingRole.IDENTITY, + "id", + column(name, "name"), + column(age, "age")); + world.bind(world.type("Ant"), world.table("ants", "id"), OntologyBindingRole.IDENTITY, "id"); + + final OntologyTableMapping mapping = world.build(); + + assertEquals( + List.of(NS + "Ant", NS + "Zebra"), + mapping.classes().stream().map(type -> type.iri().toString()).toList()); + assertEquals( + List.of(NS + "name", NS + "age"), + mapping.classes().get(1).tables().getFirst().dataColumns().stream() + .map(data -> data.propertyIri().toString()) + .toList()); + assertEquals( + List.of(List.of("name"), List.of("age")), + mapping.classes().get(1).tables().getFirst().dataColumns().stream() + .map(data -> data.columnPath()) + .toList()); + assertEquals(List.of(List.of("id")), mapping.classes().get(1).tables().getFirst().subjectKey()); + } + + @Test + void aHiddenIdentityTableIsCountedAndTheContributingTableStaysListed() { + final World world = new World(); + final OntologyConcept customer = world.type("Customer"); + world.bind(customer, world.hiddenTable("hidden_id", "id"), OntologyBindingRole.IDENTITY, "id"); + world.bind(customer, world.table("notes", "id"), OntologyBindingRole.CONTRIBUTING, "id"); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(List.of("svc.db.public.notes"), names(mapping.classes().getFirst())); + assertEquals(1, mapping.hiddenTables()); + assertEquals(0, mapping.hiddenClasses()); + assertEquals(0, mapping.hiddenProperties()); + } + + @Test + void aHiddenContributingTableIsCountedAndTheIdentityTableStaysListed() { + final World world = new World(); + final OntologyConcept customer = world.type("Customer"); + world.bind(customer, world.table("customers", "id"), OntologyBindingRole.IDENTITY, "id"); + world.bind(customer, world.hiddenTable("secret", "id"), OntologyBindingRole.CONTRIBUTING, "id"); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(List.of("svc.db.public.customers"), names(mapping.classes().getFirst())); + assertEquals(1, mapping.hiddenTables()); + } + + @Test + void aClassWhoseTablesAreAllHiddenIsListedWithNoTables() { + final World world = new World(); + world.bind( + world.type("Customer"), + world.hiddenTable("secret", "id"), + OntologyBindingRole.IDENTITY, + "id"); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(1, mapping.classes().size()); + assertEquals(List.of(), mapping.classes().getFirst().tables()); + assertEquals(1, mapping.hiddenTables()); + } + + @Test + void aHiddenClassIsCountedLeftOutAndItsTablesAreCountedWhenHidden() { + final World world = new World(); + world.bind( + world.type("Customer"), world.table("customers", "id"), OntologyBindingRole.IDENTITY, "id"); + final OntologyConcept secret = world.hiddenType("Secret"); + world.bind(secret, world.table("secrets", "id"), OntologyBindingRole.IDENTITY, "id"); + world.bind(secret, world.hiddenTable("vault", "id"), OntologyBindingRole.CONTRIBUTING, "id"); + + final OntologyTableMapping mapping = world.build(); + + assertEquals( + List.of(NS + "Customer"), + mapping.classes().stream().map(type -> type.iri().toString()).toList()); + assertEquals(1, mapping.hiddenClasses()); + assertEquals(1, mapping.hiddenTables()); + assertEquals(0, mapping.hiddenProperties()); + } + + @Test + void aHiddenPropertyIsCountedOnceWhateverNumberOfColumnsBindItAndLeftOutOfTheColumns() { + final World world = new World(); + final OntologyProperty visible = world.data("name"); + final OntologyProperty secret = world.hiddenProperty("salary"); + final OntologyConcept customer = world.type("Customer"); + world.bind( + customer, + world.table("customers", "id", "name", "pay", "bonus"), + OntologyBindingRole.IDENTITY, + "id", + column(visible, "name"), + column(secret, "pay"), + column(secret, "bonus")); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding bound = mapping.classes().getFirst().tables().getFirst(); + assertEquals(List.of(NS + "name"), iris(bound)); + assertEquals(List.of(), bound.absentFromVersion()); + assertEquals(1, mapping.hiddenProperties()); + assertEquals(0, mapping.hiddenTables()); + assertEquals(0, mapping.hiddenClasses()); + } + + private static List iris(final TableBinding bound) { + return bound.dataColumns().stream().map(data -> data.propertyIri().toString()).toList(); + } + + @Test + void aHiddenPropertyBoundOnAViewableTableOfAHiddenClassIsCounted() { + final World world = new World(); + final OntologyProperty secret = world.hiddenProperty("secretValue"); + world.bind( + world.hiddenType("SecretKind"), + world.table("secret_rows", "id", "secret_val"), + OntologyBindingRole.IDENTITY, + "id", + column(secret, "secret_val")); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(List.of(), mapping.classes()); + assertEquals(0, mapping.hiddenTables()); + assertEquals(1, mapping.hiddenClasses()); + assertEquals(1, mapping.hiddenProperties()); + } + + @Test + void aPropertyOfAHiddenTableIsNotCounted() { + final World world = new World(); + final OntologyProperty secret = world.hiddenProperty("salary"); + world.bind( + world.type("Customer"), + world.hiddenTable("customers", "id", "pay"), + OntologyBindingRole.IDENTITY, + "id", + column(secret, "pay")); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(0, mapping.hiddenProperties()); + assertEquals(1, mapping.hiddenTables()); + } + + @Test + void nothingHiddenAppearsInTheValueItsTextOrItsJson() { + final World world = new World(); + final OntologyProperty secretProperty = world.hiddenProperty("salary"); + final OntologyConcept secretClass = world.hiddenType("Classified"); + final OntologyConcept customer = world.type("Customer"); + final Table secretTable = world.hiddenTable("vault_ledger", "id", "pay"); + world.bind( + customer, + world.table("customers", "id", "pay"), + OntologyBindingRole.IDENTITY, + "id", + column(secretProperty, "pay")); + world.bind(customer, secretTable, OntologyBindingRole.CONTRIBUTING, "id"); + world.bind( + secretClass, world.table("classified_rows", "id"), OntologyBindingRole.IDENTITY, "id"); + + final OntologyTableMapping mapping = world.build(); + final String text = mapping.toString(); + final String json = JsonUtils.pojoToJson(mapping); + + assertEquals(1, mapping.hiddenTables()); + assertEquals(1, mapping.hiddenClasses()); + assertEquals(1, mapping.hiddenProperties()); + for (final String shown : List.of(text, json)) { + assertFalse(shown.contains("vault_ledger")); + assertFalse(shown.contains(secretTable.getId().toString())); + assertFalse(shown.contains("Classified")); + assertFalse(shown.contains(secretClass.getId().toString())); + assertFalse(shown.contains("salary")); + assertFalse(shown.contains(secretProperty.getId().toString())); + assertFalse(shown.contains("classified_rows")); + } + } + + @Test + void aFilterWhoseColumnWasDroppedGivesTheReasonAndNoValue() { + final World world = new World(); + world.bind( + world.type("Customer"), + world.table("customers", "id"), + OntologyBindingRole.IDENTITY, + "id", + new OntologyRowFilter() + .withColumn(List.of("region")) + .withOperator(OntologyRowFilterOperator.EQUALS) + .withValue("eu-secret")); + + final OntologyTableMapping mapping = world.build(); + + final Broken broken = + assertInstanceOf( + Broken.class, mapping.classes().getFirst().tables().getFirst().rowFilter()); + assertEquals( + "The row filter of table svc.db.public.customers names a column that the table no longer" + + " has", + broken.reason()); + assertFalse(mapping.toString().contains("eu-secret")); + assertFalse(JsonUtils.pojoToJson(mapping).contains("eu-secret")); + } + + @Test + void aFilterWhoseValueNoLongerParsesGivesTheReasonAndNoValue() { + final World world = new World(); + world.bind( + world.type("Customer"), + world.table("customers", "id", "region"), + OntologyBindingRole.IDENTITY, + "id", + new OntologyRowFilter() + .withColumn(List.of("region")) + .withOperator(OntologyRowFilterOperator.EQUALS) + .withValue("not-a-number-secret")); + + final OntologyTableMapping mapping = world.build(); + + final Broken broken = + assertInstanceOf( + Broken.class, mapping.classes().getFirst().tables().getFirst().rowFilter()); + assertEquals( + "A value of the row filter of table svc.db.public.customers no longer parses as the data" + + " type of column region", + broken.reason()); + assertFalse(mapping.toString().contains("not-a-number-secret")); + assertFalse(JsonUtils.pojoToJson(mapping).contains("not-a-number-secret")); + } + + @Test + void aFilterThatStillAppliesIsParsedAndABindingWithNoFilterHasNone() { + final World world = new World(); + final OntologyConcept customer = world.type("Customer"); + world.bind( + customer, + world.table("customers", "id", "region"), + OntologyBindingRole.IDENTITY, + "id", + new OntologyRowFilter() + .withColumn(List.of("region")) + .withOperator(OntologyRowFilterOperator.GREATER_THAN) + .withValue(7)); + world.bind(customer, world.table("notes", "id"), OntologyBindingRole.CONTRIBUTING, "id"); + + final OntologyTableMapping mapping = world.build(); + + final List tables = mapping.classes().getFirst().tables(); + final Applies applies = assertInstanceOf(Applies.class, tables.get(0).rowFilter()); + assertEquals(List.of("region"), applies.filter().column()); + assertEquals(OntologyRowFilterOperator.GREATER_THAN, applies.filter().operator()); + assertEquals(1, applies.filter().values().size()); + assertNull(tables.get(1).rowFilter()); + assertEquals( + "{\"filter\":{\"column\":[\"region\"],\"operator\":\"greaterThan\"," + + "\"values\":[{\"type\":\"INT\",\"source\":\"7\"}]}}", + JsonUtils.pojoToJson(tables.get(0).rowFilter())); + } + + @Test + void aRelationColumnCarriesItsJoinStatusTargetPairsAndTheClassesThatIdentifyTheTarget() { + final World world = new World(); + final OntologyProperty placed = world.relation("placedBy"); + final OntologyProperty approved = world.relation("approvedBy"); + final Table customers = world.table("customers", "id"); + world.bind(world.type("Customer"), customers, OntologyBindingRole.IDENTITY, "id"); + world.bind( + world.type("Order"), + world.table("orders", "id", "customer_id", "approver_id"), + OntologyBindingRole.IDENTITY, + "id", + link(placed, "customer_id", customers, OntologyJoinStatus.CONFIRMED), + link(approved, "approver_id", customers, OntologyJoinStatus.INFERRED)); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding orders = mapping.classes().get(1).tables().getFirst(); + assertEquals(NS + "Order", mapping.classes().get(1).iri().toString()); + assertEquals(2, orders.relationColumns().size()); + final var first = orders.relationColumns().get(0); + assertEquals(NS + "placedBy", first.relationIri().toString()); + assertEquals(List.of("customer_id"), first.columnPath()); + assertEquals(OntologyJoinStatus.CONFIRMED, first.join().status()); + assertEquals(customers.getId(), first.join().targetTableId()); + assertEquals( + List.of(List.of("customer_id")), first.join().on().stream().map(p -> p.child()).toList()); + assertEquals(List.of(List.of("id")), first.join().on().stream().map(p -> p.parent()).toList()); + assertEquals( + List.of(NS + "Customer"), + first.join().objectClasses().stream().map(URI::toString).toList()); + assertEquals(OntologyJoinStatus.INFERRED, orders.relationColumns().get(1).join().status()); + assertEquals(List.of(), orders.dataColumns()); + } + + @Test + void aTableThatIdentifiesTwoClassesGivesOnlyTheOnesInTheDeclaredRange() { + final World world = new World(); + final OntologyProperty placedBy = world.relation("placedBy", "Customer"); + final Table parties = world.table("parties", "id"); + world.bind(world.type("Customer"), parties, OntologyBindingRole.IDENTITY, "id"); + world.bind(world.type("Supplier"), parties, OntologyBindingRole.IDENTITY, "id"); + world.bind( + world.type("Order"), + world.table("orders", "id", "party_id"), + OntologyBindingRole.IDENTITY, + "id", + link(placedBy, "party_id", parties, OntologyJoinStatus.CONFIRMED)); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding orders = mapping.classes().get(1).tables().getFirst(); + assertEquals( + List.of(NS + "Customer"), + orders.relationColumns().getFirst().join().objectClasses().stream() + .map(URI::toString) + .toList()); + } + + @Test + void aRelationWithNoDeclaredRangeGivesEveryClassThatIdentifiesTheTargetInIriOrder() { + final World world = new World(); + final OntologyProperty placedBy = world.relation("placedBy"); + final Table parties = world.table("parties", "id"); + world.bind(world.type("Supplier"), parties, OntologyBindingRole.IDENTITY, "id"); + world.bind(world.type("Customer"), parties, OntologyBindingRole.IDENTITY, "id"); + world.bind( + world.type("Order"), + world.table("orders", "id", "party_id"), + OntologyBindingRole.IDENTITY, + "id", + link(placedBy, "party_id", parties, OntologyJoinStatus.CONFIRMED)); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding orders = mapping.classes().get(1).tables().getFirst(); + assertEquals( + List.of(NS + "Customer", NS + "Supplier"), + orders.relationColumns().getFirst().join().objectClasses().stream() + .map(URI::toString) + .toList()); + } + + @Test + void aRangeThatNamesASuperclassKeepsItsSubclassesAndDropsTheUnrelated() { + final World world = new World(); + final OntologyProperty managedBy = world.relation("managedBy", "Person"); + world.parents.put(NS + "Employee", Set.of(NS + "Person")); + final Table staff = world.table("staff", "id"); + world.bind(world.type("Employee"), staff, OntologyBindingRole.IDENTITY, "id"); + world.bind(world.type("Robot"), staff, OntologyBindingRole.IDENTITY, "id"); + world.bind( + world.type("Team"), + world.table("teams", "id", "manager_id"), + OntologyBindingRole.IDENTITY, + "id", + link(managedBy, "manager_id", staff, OntologyJoinStatus.CONFIRMED)); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding teams = mapping.classes().get(2).tables().getFirst(); + assertEquals(NS + "Team", mapping.classes().get(2).iri().toString()); + assertEquals( + List.of(NS + "Employee"), + teams.relationColumns().getFirst().join().objectClasses().stream() + .map(URI::toString) + .toList()); + } + + @Test + void aRangeClassWithNoIdentityBindingOnTheTargetGivesAnEmptyList() { + final World world = new World(); + final OntologyProperty placedBy = world.relation("placedBy", "Customer"); + final Table parties = world.table("parties", "id"); + world.bind(world.type("Customer"), parties, OntologyBindingRole.CONTRIBUTING, "id"); + world.bind( + world.type("Order"), + world.table("orders", "id", "party_id"), + OntologyBindingRole.IDENTITY, + "id", + link(placedBy, "party_id", parties, OntologyJoinStatus.CONFIRMED)); + + final OntologyTableMapping mapping = world.build(); + + assertEquals( + List.of(), + mapping + .classes() + .get(1) + .tables() + .getFirst() + .relationColumns() + .getFirst() + .join() + .objectClasses()); + } + + @Test + void aJoinOntoAHiddenTableIsCountedAndNotListedAndOntoADeletedTableIsNeither() { + final World world = new World(); + final OntologyProperty placedBy = world.relation("placedBy"); + final OntologyProperty shippedTo = world.relation("shippedTo"); + final Table vault = world.hiddenTable("vault", "id"); + final Table gone = world.table("gone", "id"); + world.tables.remove(gone.getId()); + world.bind( + world.type("Order"), + world.table("orders", "id", "a", "b"), + OntologyBindingRole.IDENTITY, + "id", + link(placedBy, "a", vault, OntologyJoinStatus.CONFIRMED), + link(shippedTo, "b", gone, OntologyJoinStatus.CONFIRMED)); + + final OntologyTableMapping mapping = world.build(); + + assertEquals(List.of(), mapping.classes().getFirst().tables().getFirst().relationColumns()); + assertEquals(1, mapping.hiddenTables()); + assertFalse(JsonUtils.pojoToJson(mapping).contains(vault.getId().toString())); + } + + @Test + void aRelationColumnStoredBeforeJoinsExistedIsListedWithNoJoin() { + final World world = new World(); + final OntologyProperty placedBy = world.relation("placedBy"); + world.bind( + world.type("Order"), + world.table("orders", "id", "a"), + OntologyBindingRole.IDENTITY, + "id", + column(placedBy, "a")); + + final OntologyTableMapping mapping = world.build(); + + final var relation = + mapping.classes().getFirst().tables().getFirst().relationColumns().getFirst(); + assertEquals(NS + "placedBy", relation.relationIri().toString()); + assertNull(relation.join()); + } + + @Test + void aClassWithNoBoundTableIsLeftOutAndADeletedTableIsCountedNowhere() { + final World world = new World(); + world.type("Unbound"); + final Table gone = world.table("gone", "id"); + world.tables.remove(gone.getId()); + world.bind(world.type("OnlyDeleted"), gone, OntologyBindingRole.IDENTITY, "id"); + world.bind( + world.type("Customer"), world.table("customers", "id"), OntologyBindingRole.IDENTITY, "id"); + + final OntologyTableMapping mapping = world.build(); + + assertEquals( + List.of(NS + "Customer"), + mapping.classes().stream().map(type -> type.iri().toString()).toList()); + assertEquals(0, mapping.hiddenTables()); + assertEquals(0, mapping.hiddenClasses()); + } + + @Test + void aPropertyTheVersionLacksIsListedByColumnPathAndAColumnTheTableLostIsListedApart() { + final World world = new World(); + final OntologyProperty lacking = world.data("retired"); + world.properties.remove(lacking.getId()); + final OntologyProperty name = world.data("name"); + world.bind( + world.type("Customer"), + world.table("customers", "id", "old"), + OntologyBindingRole.IDENTITY, + "id", + column(lacking, "old"), + column(name, "dropped")); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding bound = mapping.classes().getFirst().tables().getFirst(); + assertEquals(List.of(List.of("old")), bound.absentFromVersion()); + assertEquals(List.of(List.of("dropped")), bound.missingColumns()); + assertEquals(List.of(), bound.dataColumns()); + assertEquals(0, mapping.hiddenProperties()); + assertFalse(JsonUtils.pojoToJson(mapping).contains(lacking.getId().toString())); + } + + @Test + void aColumnTheTableLostIsNotListedWhenItsPropertyIsHidden() { + final World world = new World(); + final OntologyProperty secret = world.hiddenProperty("secret"); + final OntologyProperty name = world.data("name"); + world.bind( + world.type("Customer"), + world.table("customers", "id"), + OntologyBindingRole.IDENTITY, + "id", + column(secret, "secret_column"), + column(name, "dropped")); + + final OntologyTableMapping mapping = world.build(); + + final TableBinding bound = mapping.classes().getFirst().tables().getFirst(); + assertEquals(List.of(List.of("dropped")), bound.missingColumns()); + assertFalse(JsonUtils.pojoToJson(mapping).contains("secret_column")); + } + + @Test + void theTableCarriesItsIdNameServiceTypeAndColumns() { + final World world = new World(); + final Table customers = world.table("customers", "id", "name"); + world.bind(world.type("Customer"), customers, OntologyBindingRole.IDENTITY, "id"); + + final OntologyTableMapping.TableRef ref = + world.build().classes().getFirst().tables().getFirst().table(); + + assertEquals(customers.getId(), ref.id()); + assertEquals("svc.db.public.customers", ref.fullyQualifiedName()); + assertNull(ref.serviceType()); + assertEquals(List.of("id", "name"), ref.columns().stream().map(Column::getName).toList()); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/TableProfileFactsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/TableProfileFactsTest.java new file mode 100644 index 000000000000..12a8976417d0 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/TableProfileFactsTest.java @@ -0,0 +1,104 @@ +package org.openmetadata.service.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.type.TableProfile; +import org.openmetadata.schema.utils.JsonUtils; + +class TableProfileFactsTest { + @Test + void aProfileWithoutSampleFieldsIsNotSampled() { + final var facts = TableProfileFacts.from(profile("{\"timestamp\":42,\"rowCount\":1500.0}")); + assertEquals(new TableProfileFacts(1500L, 42L, false), facts); + } + + @Test + void aPercentageBelowOneHundredIsSampledAndOneHundredIsNot() { + assertTrue(TableProfileFacts.from(profile(percentage("10"))).sampled()); + assertTrue(TableProfileFacts.from(profile(percentage("99.5"))).sampled()); + assertFalse(TableProfileFacts.from(profile(percentage("100"))).sampled()); + } + + @Test + void aSampleWithNoTypeIsReadAsAPercentage() { + assertTrue(TableProfileFacts.from(profile("{\"timestamp\":1,\"profileSample\":50}")).sampled()); + } + + @Test + void aRowSampleIsSampledOnlyWhenSmallerThanTheTable() { + assertTrue(TableProfileFacts.from(profile(rows("100", "1000"))).sampled()); + assertFalse(TableProfileFacts.from(profile(rows("1000", "1000"))).sampled()); + assertTrue(TableProfileFacts.from(profile(rows("100", null))).sampled()); + } + + @Test + void aRowSampleIsComparedWithTheRawRowCountEvenWhenItIsNotAWholeNumber() { + final var small = TableProfileFacts.from(profile(rowsOf("100", "1000.5"))); + assertTrue(small.sampled()); + assertNull(small.rowCount()); + assertFalse(TableProfileFacts.from(profile(rowsOf("2000", "1000.5"))).sampled()); + } + + @Test + void ofTwoProfilesTheLaterWinsAndATieGoesToTheLargerRowCountInEitherOrder() { + final var older = new TableProfileFacts(99L, 10L, false); + final var newer = new TableProfileFacts(5L, 20L, true); + assertEquals(newer, TableProfileFacts.latest(older, newer)); + assertEquals(newer, TableProfileFacts.latest(newer, older)); + final var small = new TableProfileFacts(5L, 20L, false); + final var large = new TableProfileFacts(50L, 20L, false); + final var uncounted = new TableProfileFacts(null, 20L, false); + assertEquals(large, TableProfileFacts.latest(small, large)); + assertEquals(large, TableProfileFacts.latest(large, small)); + assertEquals(small, TableProfileFacts.latest(uncounted, small)); + assertEquals(small, TableProfileFacts.latest(small, uncounted)); + final var whole = new TableProfileFacts(5L, 20L, false); + assertEquals(newer, TableProfileFacts.latest(whole, newer)); + assertEquals(newer, TableProfileFacts.latest(newer, whole)); + } + + @Test + void aMissingOrInexactRowCountIsAbsentNeverZero() { + assertNull(TableProfileFacts.from(profile("{\"timestamp\":7}")).rowCount()); + assertNull(TableProfileFacts.from(profile("{\"timestamp\":7,\"rowCount\":12.5}")).rowCount()); + assertNull(TableProfileFacts.from(profile("{\"timestamp\":7,\"rowCount\":-3}")).rowCount()); + assertEquals( + 0L, TableProfileFacts.from(profile("{\"timestamp\":7,\"rowCount\":0}")).rowCount()); + } + + @Test + void aProfileWithoutATimestampOrNoProfileYieldsNoFacts() { + assertNull(TableProfileFacts.from(null)); + assertNull(TableProfileFacts.from(new TableProfile().withRowCount(9.0))); + } + + private static String percentage(final String sample) { + return "{\"timestamp\":1,\"rowCount\":10,\"profileSample\":" + + sample + + ",\"profileSampleType\":\"PERCENTAGE\"}"; + } + + private static String rows(final String sample, final String rowCount) { + return "{\"timestamp\":1," + + (rowCount == null ? "" : "\"rowCount\":" + rowCount + ",") + + "\"profileSample\":" + + sample + + ",\"profileSampleType\":\"ROWS\"}"; + } + + private static String rowsOf(final String sample, final String rowCount) { + return "{\"timestamp\":1,\"rowCount\":" + + rowCount + + ",\"profileSample\":" + + sample + + ",\"profileSampleType\":\"ROWS\"}"; + } + + private static TableProfile profile(final String json) { + return JsonUtils.readValue(json, TableProfile.class); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/SqlEngineFamilyTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/SqlEngineFamilyTest.java new file mode 100644 index 000000000000..e0f638520d96 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/SqlEngineFamilyTest.java @@ -0,0 +1,349 @@ +/* + * 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.ontology.sql; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigInteger; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.schema.api.data.OntologyConceptQueryDialect; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.service.exception.BadRequestException; + +class SqlEngineFamilyTest { + private static final String ANSI_NAMES = "order_id, \"order\", \"Amount USD\", \"a`b\"\"c]d\\e\""; + private static final String BACKTICK_NAMES = "`order_id`, `order`, `Amount USD`, `a``b\"c]d\\e`"; + private static final String ESCAPED_BACKTICK_NAMES = + "`order_id`, `order`, `Amount USD`, `a\\`b\"c]d\\\\e`"; + private static final String BANG_PATTERN = "%50!%!_[a]!!\\%"; + private static final String BACKSLASH_PATTERN = "%50\\%\\_[a]!\\\\%"; + private static final String BACKSLASH_SEARCH = "'%50\\\\%\\\\_[a]!\\\\\\\\%'"; + + static Stream serviceTypes() { + return Stream.of( + Arguments.of("Postgres", SqlEngineFamily.POSTGRES, OntologyConceptQueryDialect.ANSI), + Arguments.of("Timescale", SqlEngineFamily.POSTGRES, OntologyConceptQueryDialect.ANSI), + Arguments.of("Redshift", SqlEngineFamily.REDSHIFT, OntologyConceptQueryDialect.ANSI), + Arguments.of("Trino", SqlEngineFamily.TRINO, OntologyConceptQueryDialect.ANSI), + Arguments.of("Presto", SqlEngineFamily.TRINO, OntologyConceptQueryDialect.ANSI), + Arguments.of("Athena", SqlEngineFamily.TRINO, OntologyConceptQueryDialect.ANSI), + Arguments.of("Mysql", SqlEngineFamily.MYSQL, OntologyConceptQueryDialect.MYSQL), + Arguments.of("MariaDB", SqlEngineFamily.MYSQL, OntologyConceptQueryDialect.MYSQL), + Arguments.of("SingleStore", SqlEngineFamily.MYSQL, OntologyConceptQueryDialect.MYSQL), + Arguments.of("Doris", SqlEngineFamily.MYSQL, OntologyConceptQueryDialect.MYSQL), + Arguments.of("StarRocks", SqlEngineFamily.MYSQL, OntologyConceptQueryDialect.MYSQL), + Arguments.of("Clickhouse", SqlEngineFamily.CLICKHOUSE, OntologyConceptQueryDialect.MYSQL), + Arguments.of("BigQuery", SqlEngineFamily.BIGQUERY, OntologyConceptQueryDialect.BIGQUERY), + Arguments.of("Snowflake", SqlEngineFamily.SNOWFLAKE, OntologyConceptQueryDialect.SNOWFLAKE), + Arguments.of("Databricks", SqlEngineFamily.SPARK, OntologyConceptQueryDialect.SPARK), + Arguments.of("UnityCatalog", SqlEngineFamily.SPARK, OntologyConceptQueryDialect.SPARK), + Arguments.of("Hive", SqlEngineFamily.SPARK, OntologyConceptQueryDialect.SPARK), + Arguments.of("Impala", SqlEngineFamily.SPARK, OntologyConceptQueryDialect.SPARK), + Arguments.of("Iomete", SqlEngineFamily.SPARK, OntologyConceptQueryDialect.SPARK), + Arguments.of("Mssql", SqlEngineFamily.TSQL, OntologyConceptQueryDialect.TSQL), + Arguments.of("AzureSQL", SqlEngineFamily.TSQL, OntologyConceptQueryDialect.TSQL), + Arguments.of("Synapse", SqlEngineFamily.TSQL, OntologyConceptQueryDialect.TSQL), + Arguments.of("MicrosoftFabric", SqlEngineFamily.TSQL, OntologyConceptQueryDialect.TSQL)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("serviceTypes") + void aServiceTypeBelongsToOneFamilyAndKeepsItsDialect( + final String serviceType, + final SqlEngineFamily family, + final OntologyConceptQueryDialect dialect) { + assertEquals(family, SqlEngineFamily.ofServiceType(serviceType)); + assertEquals(dialect, family.dialect()); + } + + @Test + void aServiceTypeThatNoFamilyListsIsANamedBadRequest() { + for (final String serviceType : List.of("Oracle", "MongoDB", "mysql")) { + final BadRequestException refusal = + assertThrows(BadRequestException.class, () -> SqlEngineFamily.ofServiceType(serviceType)); + + assertEquals("SQL generation does not support " + serviceType, refusal.getMessage()); + assertEquals(400, refusal.getResponse().getStatus()); + } + } + + static Stream strings() { + return Stream.of( + Arguments.of(SqlEngineFamily.POSTGRES, "E'O''Brien \\\\ co\\: 100%'"), + Arguments.of(SqlEngineFamily.REDSHIFT, "'O''Brien \\\\ co\\: 100%'"), + Arguments.of(SqlEngineFamily.TRINO, "'O''Brien \\ co\\: 100%'"), + Arguments.of(SqlEngineFamily.MYSQL, "'O''Brien \\\\ co\\: 100%'"), + Arguments.of(SqlEngineFamily.CLICKHOUSE, "'O''Brien \\\\ co\\: 100%'"), + Arguments.of(SqlEngineFamily.BIGQUERY, "'O\\'Brien \\\\ co\\: 100%'"), + Arguments.of(SqlEngineFamily.SNOWFLAKE, "'O''Brien \\\\ co\\: 100%'"), + Arguments.of(SqlEngineFamily.SPARK, "'O\\'Brien \\\\ co\\: 100%'"), + Arguments.of(SqlEngineFamily.TSQL, "N'O''Brien \\ co\\: 100%'")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("strings") + void aStringIsWrittenWithTheQuoteAndTheBackslashAsItsFamilyReadsThem( + final SqlEngineFamily family, final String written) { + assertEquals(written, family.inline(of(text("O'Brien \\ co: 100%")))); + } + + @Test + void postgresWritesAStringWithNoBackslashInTheStandardForm() { + assertEquals("'O''Brien'", SqlEngineFamily.POSTGRES.inline(of(text("O'Brien")))); + } + + static Stream literals() { + return Stream.of( + Arguments.of(ColumnDataType.BIGINT, "-42", "-42", "-42"), + Arguments.of(ColumnDataType.DECIMAL, "-0.50", "-0.50", "-0.50"), + Arguments.of( + ColumnDataType.DOUBLE, 1.0E21, "1000000000000000000000", "1000000000000000000000"), + Arguments.of(ColumnDataType.BOOLEAN, true, "TRUE", "1"), + Arguments.of(ColumnDataType.BIT, false, "FALSE", "0"), + Arguments.of( + ColumnDataType.DATE, "2024-02-29", "DATE '2024-02-29'", "CAST(N'2024-02-29' AS date)"), + Arguments.of( + ColumnDataType.TIME, + "23:59:59.5", + "TIME '23\\:59\\:59.5'", + "CAST(N'23\\:59\\:59.5' AS time)"), + Arguments.of( + ColumnDataType.TIMESTAMP, + "2024-01-01T10:30:00", + "TIMESTAMP '2024-01-01 10\\:30\\:00'", + "CAST(N'2024-01-01T10\\:30\\:00' AS datetime2)"), + Arguments.of( + ColumnDataType.TIMESTAMPZ, + "2024-01-01 10:30:00.120000", + "TIMESTAMP '2024-01-01 10\\:30\\:00.12'", + "CAST(N'2024-01-01T10\\:30\\:00.12' AS datetime2)")); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("literals") + void aValueIsWrittenAsALiteralOfItsType( + final ColumnDataType type, final Object raw, final String standard, final String tsql) { + final TypedStatement statement = of(TypedValues.value(column(type), raw)); + + for (final SqlEngineFamily family : EnumSet.complementOf(EnumSet.of(SqlEngineFamily.TSQL))) { + assertEquals(standard, family.inline(statement), family::name); + } + assertEquals(tsql, SqlEngineFamily.TSQL.inline(statement)); + } + + @Test + void aDatetimeColumnTakesADatetimeLiteralOnBigQueryAndATimestampLiteralElsewhere() { + final TypedStatement statement = + of(TypedValues.value(column(ColumnDataType.DATETIME), "2024-01-01 10:30:00.123456")); + + assertEquals( + "DATETIME '2024-01-01 10\\:30\\:00.123456'", SqlEngineFamily.BIGQUERY.inline(statement)); + assertEquals( + "TIMESTAMP '2024-01-01 10\\:30\\:00.123456'", SqlEngineFamily.MYSQL.inline(statement)); + assertEquals( + "CAST(N'2024-01-01T10\\:30\\:00.123456' AS datetime2)", + SqlEngineFamily.TSQL.inline(statement)); + } + + @Test + void aUuidIsWrittenInLowercaseAsAStringAndAsAUuidLiteralOnTrino() { + final TypedStatement statement = + of(TypedValues.value(column(ColumnDataType.UUID), "0F8FAD5B-D9CB-469F-A165-70867728950E")); + + assertEquals( + "'0f8fad5b-d9cb-469f-a165-70867728950e'", SqlEngineFamily.POSTGRES.inline(statement)); + assertEquals( + "UUID '0f8fad5b-d9cb-469f-a165-70867728950e'", SqlEngineFamily.TRINO.inline(statement)); + assertEquals("N'0f8fad5b-d9cb-469f-a165-70867728950e'", SqlEngineFamily.TSQL.inline(statement)); + } + + static Stream names() { + return Stream.of( + Arguments.of(SqlEngineFamily.POSTGRES, ANSI_NAMES), + Arguments.of(SqlEngineFamily.REDSHIFT, ANSI_NAMES), + Arguments.of(SqlEngineFamily.TRINO, ANSI_NAMES), + Arguments.of(SqlEngineFamily.MYSQL, BACKTICK_NAMES), + Arguments.of(SqlEngineFamily.CLICKHOUSE, ESCAPED_BACKTICK_NAMES), + Arguments.of(SqlEngineFamily.BIGQUERY, ESCAPED_BACKTICK_NAMES), + Arguments.of( + SqlEngineFamily.SNOWFLAKE, + "\"order_id\", \"order\", \"Amount USD\", \"a`b\"\"c]d\\e\""), + Arguments.of(SqlEngineFamily.SPARK, BACKTICK_NAMES), + Arguments.of(SqlEngineFamily.TSQL, "[order_id], [order], [Amount USD], [a`b\"c]]d\\e]")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("names") + void aNameIsQuotedSoThatItsFamilyReadsBackTheSameCharacters( + final SqlEngineFamily family, final String written) { + final TypedStatement statement = + statement( + sql -> + sql.name("order_id") + .sql(", ") + .name("order") + .sql(", ") + .name("Amount USD") + .sql(", ") + .name("a`b\"c]d\\e")); + + assertEquals(written, family.inline(statement)); + } + + static Stream searches() { + return Stream.of( + Arguments.of( + SqlEngineFamily.POSTGRES, + "E'%50!%!_[a]!!\\\\%' ESCAPE '!'", + ":p0 ESCAPE '!'", + BANG_PATTERN), + Arguments.of( + SqlEngineFamily.REDSHIFT, + "'%50!%!_[a]!!\\\\%' ESCAPE '!'", + ":p0 ESCAPE '!'", + BANG_PATTERN), + Arguments.of( + SqlEngineFamily.TRINO, "'%50!%!_[a]!!\\%' ESCAPE '!'", ":p0 ESCAPE '!'", BANG_PATTERN), + Arguments.of( + SqlEngineFamily.SNOWFLAKE, + "'%50!%!_[a]!!\\\\%' ESCAPE '!'", + ":p0 ESCAPE '!'", + BANG_PATTERN), + Arguments.of( + SqlEngineFamily.TSQL, + "N'%50!%!_![a]!!\\%' ESCAPE '!'", + ":p0 ESCAPE '!'", + "%50!%!_![a]!!\\%"), + Arguments.of(SqlEngineFamily.MYSQL, BACKSLASH_SEARCH, ":p0", BACKSLASH_PATTERN), + Arguments.of(SqlEngineFamily.CLICKHOUSE, BACKSLASH_SEARCH, ":p0", BACKSLASH_PATTERN), + Arguments.of(SqlEngineFamily.BIGQUERY, BACKSLASH_SEARCH, ":p0", BACKSLASH_PATTERN), + Arguments.of(SqlEngineFamily.SPARK, BACKSLASH_SEARCH, ":p0", BACKSLASH_PATTERN)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("searches") + void aSearchMatchesTheWildcardsOfItsTextAsPlainCharacters( + final SqlEngineFamily family, + final String written, + final String boundText, + final String boundPattern) { + final Column name = column(ColumnDataType.VARCHAR); + final TypedStatement statement = + statement(sql -> sql.contains(TypedValues.searchText(name, "50%_[a]!\\"))); + + final BoundStatement bound = family.bind(statement); + + assertEquals(written, family.inline(statement)); + assertEquals(boundText, bound.text()); + assertEquals(List.of(new ParsedValue.Text(boundPattern)), parsed(bound)); + assertEquals("50%_[a]!\\", bound.parameters().getFirst().source()); + } + + @Test + void everyColonInFinishedTextIsEscapedInANameAndInAValue() { + final TypedStatement statement = + statement(sql -> sql.sql("SELECT ").name("a:b").sql(" = ").value(text(":name ::int \\:x"))); + + assertEquals( + "SELECT \"a\\:b\" = E'\\:name \\:\\:int \\\\\\:x'", + SqlEngineFamily.POSTGRES.inline(statement)); + assertEquals( + "SELECT [a\\:b] = N'\\:name \\:\\:int \\\\:x'", SqlEngineFamily.TSQL.inline(statement)); + } + + @Test + void aFinishedStatementComesInAFormToReadAndAFormToRunFromOneText() { + final TypedStatement statement = + statement(sql -> sql.sql("SELECT ").name("a:b").sql(" = ").value(text(":name ::int \\:x"))); + + final FinishedStatement postgres = SqlEngineFamily.POSTGRES.finish(statement); + final FinishedStatement tsql = SqlEngineFamily.TSQL.finish(statement); + + assertEquals("SELECT \"a:b\" = E':name ::int \\\\:x'", postgres.sql()); + assertEquals("SELECT \"a\\:b\" = E'\\:name \\:\\:int \\\\\\:x'", postgres.escapedSql()); + assertEquals("SELECT [a:b] = N':name ::int \\:x'", tsql.sql()); + assertEquals("SELECT [a\\:b] = N'\\:name \\:\\:int \\\\:x'", tsql.escapedSql()); + } + + @Test + void theBoundFormNamesEachValueAsAParameterAndKeepsEveryValueOutOfItsText() { + final Column qty = column(ColumnDataType.INT); + final TypedStatement statement = + statement( + sql -> + sql.sql("SELECT * FROM t WHERE ") + .name("a:b") + .sql(" IN ") + .values(List.of(TypedValues.value(qty, 1), TypedValues.value(qty, "2"))) + .sql(" AND ") + .name("note") + .sql(" = ") + .value(text("x' OR '1'='1"))); + + final BoundStatement bound = SqlEngineFamily.POSTGRES.bind(statement); + + assertEquals("SELECT * FROM t WHERE \"a\\:b\" IN (:p0, :p1) AND note = :p2", bound.text()); + assertEquals( + List.of( + new ParsedValue.WholeNumber(BigInteger.ONE), + new ParsedValue.WholeNumber(BigInteger.TWO), + new ParsedValue.Text("x' OR '1'='1")), + parsed(bound)); + } + + @Test + void everyFamilyIsCoveredByTheTablesOfThisTest() { + assertEquals( + EnumSet.allOf(SqlEngineFamily.class), + Set.copyOf(strings().map(row -> (SqlEngineFamily) row.get()[0]).toList())); + assertEquals( + EnumSet.allOf(SqlEngineFamily.class), + Set.copyOf(names().map(row -> (SqlEngineFamily) row.get()[0]).toList())); + assertEquals( + EnumSet.allOf(SqlEngineFamily.class), + Set.copyOf(searches().map(row -> (SqlEngineFamily) row.get()[0]).toList())); + } + + private static TypedValue text(final String value) { + return TypedValues.value(column(ColumnDataType.VARCHAR), value); + } + + private static Column column(final ColumnDataType type) { + return new Column().withName("c").withDataType(type); + } + + private static TypedStatement of(final TypedValue value) { + return statement(sql -> sql.value(value)); + } + + private static TypedStatement statement(final Consumer parts) { + final TypedStatement.Builder sql = TypedStatement.builder(); + parts.accept(sql); + return sql.build(); + } + + private static List parsed(final BoundStatement bound) { + return bound.parameters().stream().map(TypedValue::parsed).toList(); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedStatementTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedStatementTest.java new file mode 100644 index 000000000000..a90ce1bd4158 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedStatementTest.java @@ -0,0 +1,176 @@ +/* + * 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.ontology.sql; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.service.exception.BadRequestException; + +class TypedStatementTest { + private static final Column QTY = new Column().withName("qty").withDataType(ColumnDataType.INT); + + @ParameterizedTest + @ValueSource( + strings = { + "'", "\"", "`", "\\", ":", ";", "-", "/", "#", "[", "]", "?", "%", "@", "{", "$", "!", "|", + "&", "+", "\t", "\r", " ", "ʼ", "'" + }) + void statementTextTakesNoCharacterThatOpensAStringANameAParameterOrAComment( + final String character) { + final TypedStatement.Builder sql = TypedStatement.builder(); + + final IllegalArgumentException refusal = + assertThrows(IllegalArgumentException.class, () -> sql.sql("SELECT 1 " + character)); + + assertEquals( + "Statement text takes letters, digits, spaces, line breaks and _ , . ( ) * = < > ~." + + " Pass a name to name() and a value to value()", + refusal.getMessage()); + } + + @Test + void statementTextTakesKeywordsOperatorsAliasesAndNumbersAsTheyAreWritten() { + final String text = + "SELECT TOP 50 t0.*, COUNT(*)\nFROM x t0 WHERE a <= 1 AND b <> 2 AND c >= 3 AND d_1 = 4 AND e ~ f"; + + assertEquals(text, SqlEngineFamily.TRINO.inline(TypedStatement.builder().sql(text).build())); + assertEquals( + text, SqlEngineFamily.TRINO.bind(TypedStatement.builder().sql(text).build()).text()); + } + + @ParameterizedTest + @ValueSource(strings = {"a\nb", "a\u0000b", "\t", "a\u007f", "a\u0085b", "a\u009fb"}) + void aNameThatHoldsAControlCharacterIsRefusedWhenTheStatementIsBuilt(final String name) { + final TypedStatement.Builder sql = TypedStatement.builder(); + + final BadRequestException refusal = + assertThrows(BadRequestException.class, () -> sql.name(name)); + + assertEquals( + "SQL generation does not support a name that holds a control character", + refusal.getMessage()); + assertEquals(400, refusal.getResponse().getStatus()); + } + + @Test + void aNestedStatementIndentsItsLinesAndKeepsItsNamesAndValues() { + final Column note = new Column().withName("note").withDataType(ColumnDataType.VARCHAR); + final TypedStatement inner = + TypedStatement.builder() + .sql("SELECT t0.id\nFROM x t0\nWHERE ") + .column("t0", List.of("note")) + .sql(" = ") + .value(TypedValues.value(note, "a b")) + .build(); + + assertEquals( + "SELECT COUNT(*)\nFROM (\n SELECT t0.id\n FROM x t0\n WHERE t0.note = 'a b'\n) c", + SqlEngineFamily.TRINO + .finish( + TypedStatement.builder() + .sql("SELECT COUNT(*)\nFROM (\n ") + .nested(inner, "\n ") + .sql("\n) c") + .build()) + .sql()); + } + + @Test + void aColumnIsItsAliasAndEachSegmentOfItsPathAsAName() { + assertEquals( + "t1.\"Address\".city", + SqlEngineFamily.POSTGRES.inline( + TypedStatement.builder().column("t1", List.of("Address", "city")).build())); + assertEquals( + "`Address`.`city`", + SqlEngineFamily.MYSQL.inline( + TypedStatement.builder().column(null, List.of("Address", "city")).build())); + } + + @Test + void aListOfValuesIsWrittenInParenthesesWithOneCommaBetweenTwoValues() { + final List three = + List.of(TypedValues.value(QTY, 1), TypedValues.value(QTY, 2), TypedValues.value(QTY, 3)); + + assertEquals( + "(1, 2, 3)", SqlEngineFamily.MYSQL.inline(TypedStatement.builder().values(three).build())); + assertEquals( + "(1)", + SqlEngineFamily.MYSQL.inline(TypedStatement.builder().values(three.subList(0, 1)).build())); + } + + @Test + void aSearchTakesCharacterDataOnly() { + final TypedStatement.Builder sql = TypedStatement.builder(); + + assertEquals( + "LIKE searches character data only", + assertThrows(IllegalArgumentException.class, () -> sql.contains(TypedValues.value(QTY, 1))) + .getMessage()); + } + + @ParameterizedTest + @EnumSource(OntologyRowFilterOperator.class) + void aRowFilterIsWrittenAsOnePredicateForEachOperator(final OntologyRowFilterOperator operator) { + final String predicate = + switch (operator) { + case EQUALS -> "t0.`qty` = 5"; + case NOT_EQUALS -> "t0.`qty` <> 5"; + case LESS_THAN -> "t0.`qty` < 5"; + case LESS_THAN_OR_EQUALS -> "t0.`qty` <= 5"; + case GREATER_THAN -> "t0.`qty` > 5"; + case GREATER_THAN_OR_EQUALS -> "t0.`qty` >= 5"; + case IN -> "t0.`qty` IN (5, 6)"; + case IS_NULL -> "t0.`qty` IS NULL"; + case IS_NOT_NULL -> "t0.`qty` IS NOT NULL"; + }; + final Object value = + switch (operator) { + case IN -> List.of(5, 6); + case IS_NULL, IS_NOT_NULL -> null; + default -> 5; + }; + final OntologyRowFilter filter = + new OntologyRowFilter().withColumn(List.of("qty")).withOperator(operator).withValue(value); + + final TypedStatement.Builder sql = TypedStatement.builder(); + TypedValues.rowFilter(QTY, filter).appendTo(sql, "t0"); + + assertEquals(predicate, SqlEngineFamily.MYSQL.inline(sql.build())); + } + + @Test + void aRowFilterWithNoAliasNamesItsColumnAlone() { + final OntologyRowFilter filter = + new OntologyRowFilter() + .withColumn(List.of("qty")) + .withOperator(OntologyRowFilterOperator.GREATER_THAN) + .withValue("7"); + + final TypedStatement.Builder sql = TypedStatement.builder(); + TypedValues.rowFilter(QTY, filter).appendTo(sql, null); + + assertEquals("[qty] > 7", SqlEngineFamily.TSQL.inline(sql.build())); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedValuesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedValuesTest.java new file mode 100644 index 000000000000..fa2056251763 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/ontology/sql/TypedValuesTest.java @@ -0,0 +1,383 @@ +/* + * 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.ontology.sql; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.OntologyRowFilter; +import org.openmetadata.schema.type.OntologyRowFilterOperator; +import org.openmetadata.service.exception.BadRequestException; + +class TypedValuesTest { + private static final String WHOLE = + "a whole number is written in ASCII digits, with a leading minus sign when negative and no" + + " leading zeros"; + private static final String DECIMAL = + "a decimal number is written in ASCII digits with at most one decimal point, a leading" + + " minus sign when negative, and no exponent or leading zeros"; + private static final String TIMESTAMP = + "a timestamp is written YYYY-MM-DD hh:mm:ss with at most six fraction digits and no offset"; + + static Stream parsedValues() { + return Stream.of( + Arguments.of(ColumnDataType.INT, 42, new ParsedValue.WholeNumber(BigInteger.valueOf(42))), + Arguments.of(ColumnDataType.INT, "-0", new ParsedValue.WholeNumber(BigInteger.ZERO)), + Arguments.of( + ColumnDataType.BIGINT, + "-9223372036854775808", + new ParsedValue.WholeNumber(BigInteger.valueOf(Long.MIN_VALUE))), + Arguments.of( + ColumnDataType.LARGEINT, + new BigInteger("170141183460469231731687303715884105727"), + new ParsedValue.WholeNumber(new BigInteger("170141183460469231731687303715884105727"))), + Arguments.of( + ColumnDataType.TINYINT, 255, new ParsedValue.WholeNumber(BigInteger.valueOf(255))), + Arguments.of( + ColumnDataType.DECIMAL, "0.10", new ParsedValue.DecimalNumber(new BigDecimal("0.10"))), + Arguments.of( + ColumnDataType.DOUBLE, 100.0, new ParsedValue.DecimalNumber(new BigDecimal("100.0"))), + Arguments.of( + ColumnDataType.NUMBER, + 1.0E21, + new ParsedValue.DecimalNumber(new BigDecimal("1000000000000000000000"))), + Arguments.of(ColumnDataType.NUMERIC, 7, new ParsedValue.DecimalNumber(new BigDecimal("7"))), + Arguments.of(ColumnDataType.VARCHAR, "O'Brien", new ParsedValue.Text("O'Brien")), + Arguments.of(ColumnDataType.TEXT, 42, new ParsedValue.Text("42")), + Arguments.of(ColumnDataType.STRING, 1.5, new ParsedValue.Text("1.5")), + Arguments.of(ColumnDataType.BOOLEAN, true, new ParsedValue.Bool(true)), + Arguments.of(ColumnDataType.BIT, false, new ParsedValue.Bool(false)), + Arguments.of( + ColumnDataType.DATE, + "2024-02-29", + new ParsedValue.CalendarDate(LocalDate.of(2024, 2, 29))), + Arguments.of( + ColumnDataType.TIME, + "23:59:59.5", + new ParsedValue.TimeOfDay(LocalTime.of(23, 59, 59, 500_000_000))), + Arguments.of( + ColumnDataType.TIMESTAMP, + "2024-01-01T10:30:00", + new ParsedValue.Timestamp(LocalDateTime.of(2024, 1, 1, 10, 30, 0))), + Arguments.of( + ColumnDataType.DATETIME, + "2024-01-01 10:30:00.123456", + new ParsedValue.Timestamp(LocalDateTime.of(2024, 1, 1, 10, 30, 0, 123_456_000))), + Arguments.of( + ColumnDataType.UUID, + "0F8FAD5B-D9CB-469F-A165-70867728950E", + new ParsedValue.Uuid(UUID.fromString("0f8fad5b-d9cb-469f-a165-70867728950e")))); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("parsedValues") + void aValueParsesAsTheTypeOfItsColumn( + final ColumnDataType type, final Object raw, final ParsedValue parsed) { + final TypedValue value = TypedValues.value(column("c", type), raw); + + assertEquals(parsed, value.parsed()); + assertEquals(type, value.type()); + } + + static Stream refusedValues() { + return Stream.of( + Arguments.of(ColumnDataType.INT, "1 OR 1=1", "INT: " + WHOLE), + Arguments.of(ColumnDataType.INT, 1.5, "INT: " + WHOLE), + Arguments.of(ColumnDataType.INT, 1.0, "INT: " + WHOLE), + Arguments.of(ColumnDataType.INT, true, "INT: " + WHOLE), + Arguments.of(ColumnDataType.INT, List.of(1), "INT: " + WHOLE), + Arguments.of( + ColumnDataType.INT, + "2147483648", + "INT: the type holds whole numbers from -2147483648 to 2147483647"), + Arguments.of( + ColumnDataType.TINYINT, 256, "TINYINT: the type holds whole numbers from -128 to 255"), + Arguments.of( + ColumnDataType.BYTEINT, 128, "BYTEINT: the type holds whole numbers from -128 to 127"), + Arguments.of(ColumnDataType.DECIMAL, "1e3", "DECIMAL: " + DECIMAL), + Arguments.of(ColumnDataType.DECIMAL, ".5", "DECIMAL: " + DECIMAL), + Arguments.of(ColumnDataType.DOUBLE, Double.NaN, "DOUBLE: " + DECIMAL), + Arguments.of(ColumnDataType.FLOAT, Double.POSITIVE_INFINITY, "FLOAT: " + DECIMAL), + Arguments.of(ColumnDataType.VARCHAR, true, "VARCHAR: a string or a number is expected"), + Arguments.of( + ColumnDataType.VARCHAR, Map.of("a", 1), "VARCHAR: a string or a number is expected"), + Arguments.of( + ColumnDataType.BOOLEAN, "true", "BOOLEAN: a boolean is the JSON value true or false"), + Arguments.of(ColumnDataType.BIT, 1, "BIT: a boolean is the JSON value true or false"), + Arguments.of( + ColumnDataType.DATE, + "2023-02-29", + "DATE: a date is written YYYY-MM-DD and names a real calendar day"), + Arguments.of( + ColumnDataType.DATE, + "0000-01-01", + "DATE: a date is written YYYY-MM-DD and names a real calendar day"), + Arguments.of( + ColumnDataType.DATE, + 20240229, + "DATE: a date is written YYYY-MM-DD and names a real calendar day"), + Arguments.of( + ColumnDataType.TIME, + "24:00:00", + "TIME: a time is written hh:mm:ss with at most six fraction digits"), + Arguments.of( + ColumnDataType.TIME, + "10:30:00.1234567", + "TIME: a time is written hh:mm:ss with at most six fraction digits"), + Arguments.of(ColumnDataType.TIMESTAMP, "2024-01-01T10:30:00Z", "TIMESTAMP: " + TIMESTAMP), + Arguments.of(ColumnDataType.TIMESTAMP, "2024-02-30 10:30:00", "TIMESTAMP: " + TIMESTAMP), + Arguments.of(ColumnDataType.DATETIME, "2024-01-01 10:60:00", "DATETIME: " + TIMESTAMP), + Arguments.of(ColumnDataType.TIMESTAMPZ, "2024-01-01", "TIMESTAMPZ: " + TIMESTAMP), + Arguments.of( + ColumnDataType.UUID, + "0f8fad5b-d9cb-469f-a165-70867728950e' OR '1'='1", + "UUID: a UUID is written as 32 hexadecimal digits in groups of 8, 4, 4, 4 and 12")); + } + + @ParameterizedTest(name = "{0} {1}") + @MethodSource("refusedValues") + void aValueThatDoesNotParseIsRefusedWithItsColumnItsTypeAndWhatTheTypeExpects( + final ColumnDataType type, final Object raw, final String problem) { + assertRefused( + "The value for column qty does not parse as " + problem, + () -> TypedValues.value(column("qty", type), raw)); + } + + @Test + void aStringTakesAtMost1024CharactersAndNoControlCharacter() { + final Column status = column("status", ColumnDataType.VARCHAR); + + assertEquals( + new ParsedValue.Text("a".repeat(1024)), + TypedValues.value(status, "a".repeat(1024)).parsed()); + assertRefused( + "The value for column status must have at most 1024 characters", + () -> TypedValues.value(status, "a".repeat(1025))); + for (final String control : List.of("\n", "\t", "\u0000", "\u007f", "\u0085", "\u009f")) { + assertRefused( + "The value for column status must not hold a control character", + () -> TypedValues.value(status, "a" + control + "b")); + } + assertEquals(new ParsedValue.Text("a
b c"), TypedValues.value(status, "a
b c").parsed()); + } + + @Test + void aNumberTakesTheLengthCapOfAStringBeforeItsDigitsAreWrittenOut() { + final Column status = column("status", ColumnDataType.VARCHAR); + final Column amount = column("amount", ColumnDataType.DECIMAL); + + assertEquals( + new ParsedValue.Text("9".repeat(1024)), + TypedValues.value(status, new BigInteger("9".repeat(1024))).parsed()); + assertRefused( + "The value for column status must have at most 1024 characters", + () -> TypedValues.value(status, new BigInteger("9".repeat(1025)))); + assertRefused( + "The value for column amount must have at most 1024 characters", + () -> TypedValues.value(amount, new BigDecimal("1E+2000000000"))); + assertRefused( + "The value for column amount must have at most 1024 characters", + () -> TypedValues.value(amount, new BigDecimal("1E-2000000000"))); + assertEquals( + new ParsedValue.DecimalNumber(new BigDecimal("1000")), + TypedValues.value(amount, new BigDecimal("1E+3")).parsed()); + } + + @Test + void aTypedValueKeepsTheTextItArrivedAs() { + final Column qty = column("qty", ColumnDataType.INT); + final Column amount = column("amount", ColumnDataType.DECIMAL); + final Column name = column("name", ColumnDataType.VARCHAR); + + assertEquals("-0", TypedValues.value(qty, "-0").source()); + assertEquals("42", TypedValues.value(qty, 42).source()); + assertEquals("100.0", TypedValues.value(amount, 100.0).source()); + assertEquals("1000", TypedValues.value(amount, new BigDecimal("1E+3")).source()); + assertEquals( + "true", TypedValues.value(column("active", ColumnDataType.BOOLEAN), true).source()); + assertEquals( + "2024-01-01T10:30:00", + TypedValues.value(column("created_at", ColumnDataType.TIMESTAMP), "2024-01-01T10:30:00") + .source()); + assertEquals("O'Brien", TypedValues.value(name, "O'Brien").source()); + assertEquals("50%", TypedValues.searchText(name, "50%").source()); + assertEquals(TypedValues.value(qty, "0"), TypedValues.value(qty, "0")); + assertNotEquals(TypedValues.value(qty, "-0"), TypedValues.value(qty, "0")); + } + + @Test + void aTypedValueShowsItsDataTypeAndNeverItsValueWhenItIsLogged() { + assertEquals( + "TypedValue[VARCHAR]", + TypedValues.value(column("name", ColumnDataType.VARCHAR), "O'Brien").toString()); + } + + @Test + void aNullValueIsRefused() { + assertRefused( + "The value for column qty is null", + () -> TypedValues.value(column("qty", ColumnDataType.INT), null)); + } + + @ParameterizedTest + @EnumSource( + value = ColumnDataType.class, + names = { + "JSON", "ARRAY", "STRUCT", "MAP", "BINARY", "BLOB", "UINT", "LONG", "NTEXT", "MONEY" + }) + void aDataTypeWithNoWrittenFormTakesNoValue(final ColumnDataType type) { + assertRefused( + "SQL generation does not support column type " + type.value() + " of column payload", + () -> TypedValues.value(column("payload", type), "a")); + } + + @Test + void aKeyTakesOneValueForEachOfItsColumnsInOrder() { + final List columns = + List.of(column("tenant", ColumnDataType.VARCHAR), column("id", ColumnDataType.INT)); + + assertEquals( + List.of(new ParsedValue.Text(" eu"), new ParsedValue.WholeNumber(BigInteger.valueOf(42))), + TypedValues.key(columns, List.of(" eu", 42)).stream().map(TypedValue::parsed).toList()); + assertRefused( + "The key has 2 columns but the request gives 1 value", + () -> TypedValues.key(columns, List.of(" eu"))); + assertRefused( + "The key has 1 column but the request gives 2 values", + () -> TypedValues.key(columns.subList(1, 2), List.of(42, 43))); + assertRefused( + "The value for column id is null", + () -> TypedValues.key(columns, Arrays.asList("eu", null))); + } + + @Test + void searchTextIsCharacterDataOfAtMost256CharactersForACharacterColumn() { + final Column name = column("name", ColumnDataType.VARCHAR); + + assertEquals(new ParsedValue.Text("50%_off"), TypedValues.searchText(name, "50%_off").parsed()); + assertEquals( + new ParsedValue.Text("a".repeat(256)), + TypedValues.searchText(name, "a".repeat(256)).parsed()); + assertRefused( + "Search text must have at most 256 characters", + () -> TypedValues.searchText(name, "a".repeat(257))); + assertRefused( + "Search text must not hold a control character", + () -> TypedValues.searchText(name, "a\rb")); + assertRefused("Search text is null", () -> TypedValues.searchText(name, null)); + assertRefused( + "A search reads character data, and column qty has data type INT", + () -> TypedValues.searchText(column("qty", ColumnDataType.INT), "1")); + assertRefused( + "SQL generation does not support column type JSON of column payload", + () -> TypedValues.searchText(column("payload", ColumnDataType.JSON), "1")); + } + + @Test + void aRowFilterTakesNoValueForANullTestOneForAComparisonAndAListForIn() { + final Column qty = column("qty", ColumnDataType.INT); + + assertEquals( + List.of(), + TypedValues.rowFilter(qty, filter(OntologyRowFilterOperator.IS_NULL, null)).values()); + assertEquals( + List.of(new ParsedValue.WholeNumber(BigInteger.TEN)), + parsed(TypedValues.rowFilter(qty, filter(OntologyRowFilterOperator.LESS_THAN, 10)))); + assertEquals( + List.of( + new ParsedValue.WholeNumber(BigInteger.ONE), + new ParsedValue.WholeNumber(BigInteger.TWO)), + parsed(TypedValues.rowFilter(qty, filter(OntologyRowFilterOperator.IN, List.of(1, "2"))))); + assertEquals( + List.of("qty"), + TypedValues.rowFilter(qty, filter(OntologyRowFilterOperator.IS_NOT_NULL, null)).column()); + } + + @Test + void aNullTestAppliesToAColumnOfAnyTypeBecauseItTakesNoValue() { + final TypedRowFilter filter = + TypedValues.rowFilter( + column("qty", ColumnDataType.JSON), + filter(OntologyRowFilterOperator.IS_NOT_NULL, null)); + + assertEquals(OntologyRowFilterOperator.IS_NOT_NULL, filter.operator()); + assertEquals(List.of(), filter.values()); + } + + @Test + void aRowFilterListMustHoldOneToAHundredValuesThatEachParse() { + final Column qty = column("qty", ColumnDataType.INT); + final String size = "A row filter on column qty with `in` takes a list of 1 to 100 values"; + + assertRefused(size, () -> TypedValues.rowFilter(qty, filter(OntologyRowFilterOperator.IN, 1))); + assertRefused( + size, () -> TypedValues.rowFilter(qty, filter(OntologyRowFilterOperator.IN, List.of()))); + assertRefused( + size, + () -> + TypedValues.rowFilter( + qty, filter(OntologyRowFilterOperator.IN, Collections.nCopies(101, 1)))); + assertRefused( + "The value for column qty does not parse as INT: " + WHOLE, + () -> + TypedValues.rowFilter( + qty, filter(OntologyRowFilterOperator.IN, List.of(1, "2 OR 1=1")))); + assertRefused( + "The value for column qty does not parse as INT: " + WHOLE, + () -> TypedValues.rowFilter(qty, filter(OntologyRowFilterOperator.EQUALS, List.of(1, 2)))); + } + + private static List parsed(final TypedRowFilter filter) { + return filter.values().stream().map(TypedValue::parsed).toList(); + } + + private static OntologyRowFilter filter( + final OntologyRowFilterOperator operator, final Object value) { + return new OntologyRowFilter() + .withColumn(List.of("qty")) + .withOperator(operator) + .withValue(value); + } + + private static Column column(final String name, final ColumnDataType type) { + return new Column().withName(name).withDataType(type); + } + + private static void assertRefused(final String message, final Executable call) { + final BadRequestException refusal = assertThrows(BadRequestException.class, call); + + assertEquals(message, refusal.getMessage()); + assertEquals(400, refusal.getResponse().getStatus()); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java index 6e5f75f58411..11baec06ed30 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/NativeOntologyRdfImporterTest.java @@ -43,6 +43,7 @@ import org.openmetadata.schema.type.RelationshipCharacteristic; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.ontology.NativeOntologyCsvCodec; import org.openmetadata.service.ontology.NativeOntologyDocument; import org.openmetadata.service.ontology.OntologyPackCatalog; import org.openmetadata.service.ontology.OntologyPackContentLoader; @@ -434,6 +435,111 @@ void anAxiomNamingAPropertyThePlanRefusesIsRefusedWithIt() { assertEquals(1, preview.getSummary().getCounts().getSkippedRelations()); } + @Test + void aDisplayNameFlagIsReadAndAbsenceLeavesNoFlag() { + final var document = + readDocument( + """ + ex:name a owl:DatatypeProperty ; + true . + ex:code a owl:DatatypeProperty . + """); + + final var byIri = + document.properties().stream() + .collect(java.util.stream.Collectors.toMap(p -> p.getIri().toString(), p -> p)); + assertEquals(true, byIri.get("https://example.org/name").getIsDisplayName()); + assertNull(byIri.get("https://example.org/code").getIsDisplayName()); + } + + @Test + void reimportingACsvExportKeepsTheStoredDisplayNameFlag() { + final var stored = imported(root(), FLAGGED_NAME); + + final var preview = importer.preview(importer.read(csvRequest(FLAGGED_NAME)), stored); + + assertEquals(0, preview.getChangeSet().getOperations().size()); + assertEquals(0, preview.getSummary().getCounts().getUpdatedProperties()); + final var edited = + importer.preview( + importer.read( + csvRequest(FLAGGED_NAME.replace("rdfs:label \"name\"", "rdfs:label \"given\""))), + stored); + final var property = edited.getChangeSet().getOperations().getFirst().getProperty(); + assertEquals("given", property.getDisplayName()); + assertEquals(true, property.getIsDisplayName()); + } + + @Test + void aCsvRowThatStopsTheFlaggedPropertyBeingADataPropertyDropsTheFlag() { + final var stored = imported(root(), FLAGGED_NAME); + final String asObject = + TURTLE_PREFIXES + + """ + ex:Customer a owl:Class ; rdfs:label "Customer" . + ex:name a owl:ObjectProperty ; rdfs:label "name" ; + rdfs:domain ex:Customer ; rdfs:range ex:Customer . + """; + + final var preview = importer.preview(importer.read(csvRequest(asObject)), stored); + + assertEquals(1, preview.getChangeSet().getOperations().size()); + assertEquals(1, preview.getSummary().getCounts().getUpdatedProperties()); + final var property = preview.getChangeSet().getOperations().getFirst().getProperty(); + assertEquals(OntologyPropertyKind.OBJECT, property.getKind()); + assertNull(property.getIsDisplayName()); + } + + private PreviewNativeOntologyImport csvRequest(String turtle) { + return new PreviewNativeOntologyImport() + .withFormat(NativeOntologyImportFormat.CSV) + .withData(NativeOntologyCsvCodec.write(importer.read(turtleRequest(turtle)).document())); + } + + @Test + void aTurtleImportTakesTheDisplayNameFlagFromTheFile() { + final var root = root(); + final var stored = imported(root, FLAGGED_NAME); + final String unflagged = + TURTLE_PREFIXES + + """ + ex:Customer a owl:Class ; rdfs:label "Customer" . + ex:name a owl:DatatypeProperty ; rdfs:label "name" ; rdfs:domain ex:Customer . + """; + + assertEquals( + 0, + importer + .preview(importer.read(turtleRequest(FLAGGED_NAME)), stored) + .getChangeSet() + .getOperations() + .size()); + final var cleared = importer.preview(importer.read(turtleRequest(unflagged)), stored); + assertEquals(1, cleared.getChangeSet().getOperations().size()); + assertNull(cleared.getChangeSet().getOperations().getFirst().getProperty().getIsDisplayName()); + } + + @Test + void aDisplayNameFlagThatIsNotTrueIsRefused() { + for (final String value : List.of("false", "\"true\"", "\"true\"^^xsd:string")) { + final var model = + importer.parse( + TURTLE_PREFIXES + + "ex:name a owl:DatatypeProperty ;" + + " " + + value + + " .", + RdfSerializationFormat.TURTLE); + try { + final var thrown = + assertThrows(BadRequestException.class, () -> NativeOntologyRdfImporter.read(model)); + assertEquals("Display-name intent must be true", thrown.getMessage(), value); + } finally { + model.close(); + } + } + } + @Test void skippedReportStaysSmallWhateverTheSourceStates() { final var document = @@ -1500,6 +1606,14 @@ void aRequestWithoutARecognizableFormatNamesTheFiveFormats() { @prefix ex: . """; + private static final String FLAGGED_NAME = + TURTLE_PREFIXES + + """ + ex:Customer a owl:Class ; rdfs:label "Customer" . + ex:name a owl:DatatypeProperty ; rdfs:label "name" ; rdfs:domain ex:Customer ; + true . + """; + private NativeOntologyDocument readDocument(final String turtle) { return readRaw(TURTLE_PREFIXES + turtle); } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseExportFixture.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseExportFixture.java index 5eedc17bea77..5f1a1c1fccd0 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseExportFixture.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseExportFixture.java @@ -17,6 +17,7 @@ import org.openmetadata.schema.entity.data.OntologyConcept; import org.openmetadata.schema.entity.data.OntologyProperty; import org.openmetadata.schema.entity.data.OntologyRelease; +import org.openmetadata.schema.entity.data.OntologyShape; import org.openmetadata.schema.type.OntologyAxiomType; import org.openmetadata.schema.type.OntologyConceptType; import org.openmetadata.schema.type.OntologyExpression; @@ -152,6 +153,7 @@ private static MemberKind kind(final EntityInterface definition) { case OntologyConcept ignored -> MemberKind.CONCEPT; case OntologyProperty ignored -> MemberKind.PROPERTY; case OntologyAxiom ignored -> MemberKind.AXIOM; + case OntologyShape ignored -> MemberKind.SHAPE; default -> throw new IllegalArgumentException(); }; } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseProjectionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseProjectionTest.java index a5c88b7a82d7..ddda2f342f5c 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseProjectionTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseProjectionTest.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -533,6 +534,37 @@ void dataEnumerationsRetainTypedValuesAndIdentifierIntent(final List p.getIri().toString(), p -> String.valueOf(p.getIsDisplayName()))); + assertEquals(Map.of(EX + "name", "true", EX + "code", "null"), flags); + } finally { + parsed.close(); + } + } finally { + exported.close(); + } + assertNativeReimportIsNoOp(bundle, RdfSerializationFormat.TURTLE); + } + private static Stream> enumeratedValues() { return Stream.of( List.of(new OntologyLiteral().withValue(""), new OntologyLiteral().withValue("Gold")), @@ -900,7 +932,7 @@ void rejectsAValidDigestWhenPayloadIdentityOrOwnershipIsWrong() { @Test void unsupportedMembersAndMissingRootsCannotDisappearFromExport() { Bundle bundle = bundle(List.of(concept("Customer"))); - bundle.members().getLast().setMemberKind(MemberKind.SHAPE); + bundle.members().getLast().setMemberKind(MemberKind.ASSOCIATION); reseal(bundle); assertThrows( BadRequestException.class, diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseShapeExportTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseShapeExportTest.java new file mode 100644 index 000000000000..4b258da38f04 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyReleaseShapeExportTest.java @@ -0,0 +1,152 @@ +/* + * 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.rdf; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.openmetadata.service.rdf.OntologyReleaseExportFixture.CUSTOMER; +import static org.openmetadata.service.rdf.OntologyReleaseExportFixture.EX; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.OntologyDefinition; +import org.openmetadata.schema.api.data.OntologyReleaseExportOptions; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.ontology.OntologyReleaseManifest; +import org.openmetadata.service.rdf.OntologyReleaseExportFixture.Sealed; + +/** Shapes in a sealed release: exported as SHACL, and invisible to the OWL graph formats. */ +class OntologyReleaseShapeExportTest { + private static final OntologyShape SHAPE = + new OntologyShape() + .withId(OntologyReleaseExportFixture.id("customer-shape")) + .withName("CustomerShape") + .withDisplayName("Customer shape") + .withDescription("") + .withOntology(OntologyReleaseExportFixture.ROOT.getEntityReference()) + .withTargetConcept(CUSTOMER.getIri()) + .withSeverity(OntologyShapeSeverity.INFO) + .withConstraints( + List.of( + new OntologyShapeConstraint() + .withId("buys") + .withPath(URI.create(EX + "buysFrom")) + .withMinCount(1), + new OntologyShapeConstraint() + .withId("buys-max") + .withPath(URI.create(EX + "buysFrom")) + .withMaxCount(5))); + + private static final Sealed WITH_SHAPE = sealed(true); + private static final Sealed WITHOUT_SHAPE = sealed(false); + + @Test + void shaclExportReadsBackWithTheConstraintIdsOfTheSealedShape() { + final String shacl = + OntologyReleaseExporter.render( + WITH_SHAPE.release(), + WITH_SHAPE.members(), + OntologyExportFormat.SHACL, + new OntologyReleaseExportOptions(), + BoundAssetLinks.NONE); + + final var parsed = OntologyShaclReader.read(shacl); + + assertEquals(List.of(), parsed.unsupported()); + assertEquals(1, parsed.shapes().size()); + final var shape = parsed.shapes().getFirst(); + assertEquals("CustomerShape", shape.name()); + assertEquals(CUSTOMER.getIri(), shape.targetConcept()); + assertEquals(OntologyShapeSeverity.INFO, shape.severity()); + assertEquals( + List.of("buys", "buys-max"), + shape.constraints().stream().map(OntologyShapeConstraint::getId).toList()); + } + + @Test + void aReleaseWithoutShapesExportsEmptyShacl() { + final String shacl = + OntologyReleaseExporter.render( + WITHOUT_SHAPE.release(), + WITHOUT_SHAPE.members(), + OntologyExportFormat.SHACL, + new OntologyReleaseExportOptions(), + BoundAssetLinks.NONE); + + assertEquals(List.of(), OntologyShaclReader.read(shacl).shapes()); + } + + @Test + void theOwlGraphOfAReleaseIsTheSameWithOrWithoutItsShapes() { + final var options = new OntologyReleaseExportOptions(); + final String with = + OntologyReleaseExporter.render( + WITH_SHAPE.release(), + WITH_SHAPE.members(), + OntologyExportFormat.TURTLE, + options, + BoundAssetLinks.NONE); + final String without = + OntologyReleaseExporter.render( + WITHOUT_SHAPE.release(), + WITHOUT_SHAPE.members(), + OntologyExportFormat.TURTLE, + options, + BoundAssetLinks.NONE); + + assertTrue( + OntologyReleaseExportFixture.turtle(with) + .isIsomorphicWith(OntologyReleaseExportFixture.turtle(without)), + "a shape adds no statement to the OWL graph"); + } + + @Test + void aSealedShapeChangesTheDigestAndStillVerifies() { + assertNotEquals( + WITHOUT_SHAPE.release().getContentDigest(), WITH_SHAPE.release().getContentDigest()); + OntologyReleaseManifest.verify(WITH_SHAPE.release(), WITH_SHAPE.members()); + } + + @Test + void boundAssetLinksAreRefusedForShacl() { + final var refused = + assertThrows( + BadRequestException.class, + () -> + OntologyReleaseExporter.render( + WITH_SHAPE.release(), + WITH_SHAPE.members(), + OntologyExportFormat.SHACL, + new OntologyReleaseExportOptions().withIncludeBoundAssets(true), + BoundAssetLinks.NONE)); + assertEquals("Bound asset links cannot be written to shacl", refused.getMessage()); + } + + private static Sealed sealed(final boolean withShape) { + final List definitions = new ArrayList<>(); + definitions.add(CUSTOMER); + definitions.add(OntologyReleaseExportFixture.property("buysFrom", "soldTo")); + if (withShape) { + definitions.add(SHAPE); + } + return OntologyReleaseExportFixture.seal(definitions); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclReaderTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclReaderTest.java new file mode 100644 index 000000000000..d569c0d4d835 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclReaderTest.java @@ -0,0 +1,211 @@ +/* + * 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.rdf; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.net.URI; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.openmetadata.schema.api.data.OntologyShapeUnsupportedConstruct; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.service.exception.BadRequestException; + +/** What the SHACL reader keeps, reports and refuses; every report is named in the result. */ +class OntologyShaclReaderTest { + private static final String HEAD = + """ + @prefix sh: . + @prefix ex: . + @prefix xsd: . + @prefix rdf: . + """; + + @Test + @Timeout(value = 20, unit = TimeUnit.SECONDS) + void aListThatLoopsBackOnItselfIsReportedAndItsConstraintLeftOut() { + final String file = + HEAD + + """ + ex:S a sh:NodeShape ; sh:targetClass ex:P ; sh:property ex:Sp . + ex:Sp sh:path ex:name ; sh:in _:l1 . + _:l1 rdf:first "a" ; rdf:rest _:l1 . + """; + + final OntologyShaclReader.Parsed parsed = OntologyShaclReader.read(file); + + assertEquals( + List.of( + "sh:in: The value is not a well-formed list of at most 1000 IRIs and literals; the" + + " constraint was left out", + "sh:property: A property shape with no supported constraint was left out"), + reports(parsed)); + assertEquals(List.of(), parsed.shapes().getFirst().constraints()); + } + + @Test + @Timeout(value = 20, unit = TimeUnit.SECONDS) + void aListThatEndsEarlyOrRunsPastTheCellCapIsReported() { + final StringBuilder longList = new StringBuilder("( "); + for (int cell = 0; cell <= OntologyShaclReader.MAX_LIST_CELLS; cell++) { + longList.append("\"v").append(cell).append("\" "); + } + final String unterminated = + HEAD + + """ + ex:S a sh:NodeShape ; sh:targetClass ex:P ; + sh:property [ sh:path ex:name ; sh:minCount 1 ; sh:in _:l1 ] . + _:l1 rdf:first "a" . + """; + final String tooLong = + HEAD + + "ex:S a sh:NodeShape ; sh:targetClass ex:P ; sh:property [ sh:path ex:name ;" + + " sh:minCount 1 ; sh:in " + + longList + + ") ] .\n"; + + final OntologyShaclReader.Parsed ended = OntologyShaclReader.read(unterminated); + final OntologyShaclReader.Parsed overCap = OntologyShaclReader.read(tooLong); + + for (final OntologyShaclReader.Parsed parsed : List.of(ended, overCap)) { + assertEquals( + List.of( + "sh:in: The value is not a well-formed list of at most 1000 IRIs and literals; the" + + " constraint was left out"), + reports(parsed)); + assertEquals( + Integer.valueOf(1), parsed.shapes().getFirst().constraints().getFirst().getMinCount()); + assertNull(parsed.shapes().getFirst().constraints().getFirst().getIn()); + } + } + + @Test + void aPredicateWithTwoValuesIsReportedAndTheFirstInLexicalOrderIsKept() { + final String file = + HEAD + + """ + ex:S a sh:NodeShape ; sh:name "Zed" , "Alpha" ; sh:targetClass ex:P ; + sh:property [ sh:path ex:knows ; sh:class ex:B , ex:A ; sh:pattern "b$" , "^a" ; + sh:datatype xsd:string , xsd:integer ; sh:minCount 2 , 1 ] . + """; + + final OntologyShaclReader.Parsed parsed = OntologyShaclReader.read(file); + + final String once = "Only one value is held; the first in lexical order was used"; + assertEquals( + List.of( + "sh:name: " + once, + "sh:minCount: " + once, + "sh:class: " + once, + "sh:datatype: " + once, + "sh:pattern: " + once), + reports(parsed)); + assertEquals("Alpha", parsed.shapes().getFirst().name()); + final OntologyShapeConstraint kept = parsed.shapes().getFirst().constraints().getFirst(); + assertEquals(Integer.valueOf(1), kept.getMinCount()); + assertEquals(URI.create("https://example.org/onto/A"), kept.getClassIri()); + assertEquals(URI.create("http://www.w3.org/2001/XMLSchema#integer"), kept.getDatatypeIri()); + assertEquals("^a", kept.getPattern()); + } + + @Test + void aLanguageTaggedLiteralIsReportedAndItsConstraintLeftOut() { + final String file = + HEAD + + """ + ex:S a sh:NodeShape ; sh:targetClass ex:P ; + sh:property [ sh:path ex:label ; sh:minCount 1 ; sh:in ( "chat"@fr "cat"@en ) ] , + [ sh:path ex:title ; sh:minCount 1 ; sh:minInclusive "a"@en ; sh:maxInclusive "z" ] . + """; + + final OntologyShaclReader.Parsed parsed = OntologyShaclReader.read(file); + + assertEquals( + List.of( + "sh:in: A list value that is not an IRI or a plain or typed literal is not held; the" + + " constraint was left out", + "sh:minInclusive: A language-tagged literal is not held; the constraint was left out"), + reports(parsed).stream().sorted().toList()); + final List constraints = parsed.shapes().getFirst().constraints(); + assertEquals(2, constraints.size()); + assertNull(constraints.get(0).getIn()); + assertNull(constraints.get(1).getMinInclusive()); + assertEquals("z", constraints.get(1).getMaxInclusive().getValue()); + } + + @Test + void aSuffixThatTellsTwoEqualNamesApartStaysWithinTheNameLength() { + final String name = "n".repeat(256); + final String file = + HEAD + + "ex:S1 a sh:NodeShape ; sh:name \"" + + name + + "\" ; sh:targetClass ex:P ; sh:property [ sh:path ex:a ; sh:minCount 1 ] .\n" + + "ex:S2 a sh:NodeShape ; sh:name \"" + + name + + "\" ; sh:targetClass ex:P ; sh:property [ sh:path ex:a ; sh:minCount 1 ] .\n"; + + final List names = + OntologyShaclReader.read(file).shapes().stream() + .map(OntologyShaclReader.ParsedShape::name) + .toList(); + + assertEquals(List.of("n".repeat(255) + "2", "n".repeat(256)), names); + } + + @Test + void aNameLongerThanTheLimitIsKeptSoTheCallerCanRefuseIt() { + final String file = + HEAD + + "ex:S1 a sh:NodeShape ; sh:name \"" + + "n".repeat(300) + + "\" ; sh:targetClass ex:P ; sh:property [ sh:path ex:a ; sh:minCount 1 ] .\n"; + + assertEquals(300, OntologyShaclReader.read(file).shapes().getFirst().name().length()); + } + + @Test + void aFileOverTheShapeCapIsRefused() { + final StringBuilder file = new StringBuilder(HEAD); + for (int shape = 0; shape <= OntologyShaclReader.MAX_SHAPES; shape++) { + file.append("ex:S").append(shape).append(" a sh:NodeShape ; sh:targetClass ex:P .\n"); + } + + final BadRequestException refused = + assertThrows(BadRequestException.class, () -> OntologyShaclReader.read(file.toString())); + + assertEquals("A file holds at most 1000 shapes", refused.getMessage()); + } + + @Test + void aRelativeIdentifierIsRefused() { + assertThrows( + BadRequestException.class, + () -> + OntologyShaclReader.read( + "@prefix sh: .\n a sh:NodeShape .\n")); + } + + private static List reports(final OntologyShaclReader.Parsed parsed) { + return parsed.unsupported().stream() + .map( + (OntologyShapeUnsupportedConstruct item) -> + item.getConstruct() + ": " + item.getMessage()) + .toList(); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclRoundTripTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclRoundTripTest.java new file mode 100644 index 000000000000..940d8d538d48 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/OntologyShaclRoundTripTest.java @@ -0,0 +1,203 @@ +/* + * 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.rdf; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.util.List; +import java.util.UUID; +import org.apache.jena.rdf.model.Model; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.api.data.OntologyShapeUnsupportedConstruct; +import org.openmetadata.schema.entity.data.Ontology; +import org.openmetadata.schema.entity.data.OntologyShape; +import org.openmetadata.schema.type.OntologyLiteral; +import org.openmetadata.schema.type.OntologyShapeConstraint; +import org.openmetadata.schema.type.OntologyShapeSeverity; +import org.openmetadata.schema.type.OntologyShapeValue; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.exception.BadRequestException; + +class OntologyShaclRoundTripTest { + private static final URI PERSON = URI.create("https://example.org/onto/Person"); + private static final URI NAME = URI.create("https://example.org/onto/name"); + private static final URI AGE = URI.create("https://example.org/onto/age"); + private static final URI STATUS = URI.create("https://example.org/onto/status"); + private static final URI XSD_INTEGER = URI.create("http://www.w3.org/2001/XMLSchema#integer"); + + @Test + void exportedShapesImportBackWithEveryConstraintIdAndTheirOrder() { + final OntologyShape person = + shape( + "Person shape", + PERSON, + OntologyShapeSeverity.WARNING, + new OntologyShapeConstraint() + .withId("z-first") + .withPath(NAME) + .withMinCount(1) + .withMaxCount(1) + .withPattern("^[A-Z]"), + new OntologyShapeConstraint() + .withId("age.range") + .withPath(AGE) + .withDatatypeIri(XSD_INTEGER) + .withMinInclusive(new OntologyLiteral().withValue("0").withDatatypeIri(XSD_INTEGER)) + .withMaxInclusive( + new OntologyLiteral().withValue("150").withDatatypeIri(XSD_INTEGER)), + new OntologyShapeConstraint() + .withId("status_in") + .withPath(STATUS) + .withClassIri(URI.create("https://example.org/onto/Status")) + .withIn( + List.of( + new OntologyShapeValue() + .withIri(URI.create("https://example.org/onto/Active")), + new OntologyShapeValue() + .withLiteral(new OntologyLiteral().withValue("retired"))))); + final OntologyShape empty = shape("Plain", PERSON, OntologyShapeSeverity.VIOLATION); + + final String turtle = turtle(person, empty); + final OntologyShaclReader.Parsed parsed = OntologyShaclReader.read(turtle); + + assertEquals(List.of(), parsed.unsupported()); + assertEquals( + List.of("Person shape", "Plain"), + parsed.shapes().stream().map(OntologyShaclReader.ParsedShape::name).toList()); + final OntologyShaclReader.ParsedShape read = parsed.shapes().get(0); + assertEquals(PERSON, read.targetConcept()); + assertEquals(OntologyShapeSeverity.WARNING, read.severity()); + assertEquals("Person shape display", read.displayName()); + assertEquals("Person shape description", read.description()); + assertEquals( + JsonUtils.pojoToJson(person.getConstraints()), JsonUtils.pojoToJson(read.constraints())); + assertEquals( + List.of("z-first", "age.range", "status_in"), + read.constraints().stream().map(OntologyShapeConstraint::getId).toList()); + assertEquals(List.of(), parsed.shapes().get(1).constraints()); + } + + @Test + void aFileFromElsewhereImportsItsSupportedPartsAndNamesTheRest() { + final String file = + """ + @prefix sh: . + @prefix ex: . + @prefix xsd: . + + ex:PersonShape a sh:NodeShape ; + sh:targetClass ex:Person ; + sh:closed true ; + sh:property [ sh:path ex:name ; sh:minCount 1 ; sh:minLength 2 ] ; + sh:property [ sh:path ex:age ; sh:datatype xsd:integer ; sh:or ( [ sh:minInclusive 0 ] [ sh:maxInclusive 5 ] ) ] ; + sh:property [ sh:path [ sh:inversePath ex:knows ] ; sh:minCount 1 ] ; + sh:property [ sh:path ex:nick ; sh:uniqueLang true ] ; + sh:sparql [ sh:select "SELECT $this WHERE { }" ] . + + ex:Orphan a sh:NodeShape ; sh:targetNode ex:Alice . + """; + + final OntologyShaclReader.Parsed parsed = OntologyShaclReader.read(file); + + assertEquals(1, parsed.shapes().size()); + final OntologyShaclReader.ParsedShape person = parsed.shapes().get(0); + assertEquals("PersonShape", person.name()); + assertEquals( + List.of("age=null/null", "name=1/null"), + person.constraints().stream() + .map( + c -> + c.getPath().toString().replaceAll(".*/", "") + + "=" + + c.getMinCount() + + "/" + + c.getMaxCount()) + .sorted() + .toList()); + assertEquals( + List.of("c1", "c2"), + person.constraints().stream().map(OntologyShapeConstraint::getId).toList()); + assertEquals( + List.of( + "sh:closed", + "sh:minLength", + "sh:or", + "sh:path", + "sh:property", + "sh:sparql", + "sh:targetClass", + "sh:targetNode", + "sh:uniqueLang"), + parsed.unsupported().stream() + .map(OntologyShapeUnsupportedConstruct::getConstruct) + .distinct() + .sorted() + .toList()); + assertTrue( + parsed.unsupported().stream() + .anyMatch( + item -> + item.getConstruct().equals("sh:path") && "PersonShape".equals(item.getShape())), + "a property path that is not a single IRI is named with its shape"); + } + + @Test + void aShapeWithoutOneTargetClassIsLeftOutAndNamed() { + final OntologyShaclReader.Parsed parsed = + OntologyShaclReader.read( + """ + @prefix sh: . + @prefix ex: . + ex:NoTarget a sh:NodeShape ; sh:property [ sh:path ex:name ; sh:minCount 1 ] . + """); + + assertEquals(List.of(), parsed.shapes()); + assertEquals("sh:targetClass", parsed.unsupported().get(0).getConstruct()); + assertEquals("https://example.org/onto/NoTarget", parsed.unsupported().get(0).getShape()); + } + + @Test + void textThatIsNotTurtleIsRefused() { + assertThrows(BadRequestException.class, () -> OntologyShaclReader.read("this is { not turtle")); + } + + private static String turtle(final OntologyShape... shapes) { + final Model model = + OntologyShaclWriter.write( + new Ontology().withIri(URI.create("https://example.org/onto")), List.of(shapes)); + try { + return RdfGraphSerializer.asString(model, RdfSerializationFormat.TURTLE); + } finally { + model.close(); + } + } + + private static OntologyShape shape( + final String name, + final URI target, + final OntologyShapeSeverity severity, + final OntologyShapeConstraint... constraints) { + return new OntologyShape() + .withId(UUID.randomUUID()) + .withName(name) + .withDisplayName(name + " display") + .withDescription(name + " description") + .withTargetConcept(target) + .withSeverity(severity) + .withConstraints(List.of(constraints)); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfExcludedEntitiesTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfExcludedEntitiesTest.java index a1e6867ccaee..fed2d24707ba 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfExcludedEntitiesTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfExcludedEntitiesTest.java @@ -37,6 +37,11 @@ void nativeWorkingDefinitionsNeverEnterGenericProjection() { .forEach(type -> assertTrue(RdfExcludedEntities.isExcluded(type))); } + @Test + void aChangeSetNeverEntersTheProjectionOrItsRelationshipEdges() { + assertTrue(RdfExcludedEntities.isExcluded(Entity.ONTOLOGY_CHANGE_SET)); + } + @Test @DisplayName("aiChart is excluded from RDF") void aiChartIsExcluded() { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyChangeSetEndpointRightsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyChangeSetEndpointRightsTest.java new file mode 100644 index 000000000000..e778f87de51e --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyChangeSetEndpointRightsTest.java @@ -0,0 +1,111 @@ +/* + * 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.resources.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PATCH; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.TreeMap; +import org.junit.jupiter.api.Test; + +/** + * Every endpoint of the change set resource, its own and the ones it inherits, states the right it + * asks. A new endpoint fails this test until its row is added below, so whoever adds it decides + * whether it may return operations and which right a caller needs first. + */ +class OntologyChangeSetEndpointRightsTest { + private static final String DRAFT_READ = "draft read right"; + private static final String BASE = "/v1/ontologyChangeSets"; + + /** The right each endpoint asks before it writes anything or answers, as HTTP method and path. */ + private static final Map RIGHT_OF = + Map.ofEntries( + Map.entry("GET " + BASE, DRAFT_READ + " for every row"), + Map.entry("POST " + BASE, "EditAll on the scope, then the right of each definition"), + Map.entry("GET " + BASE + "/{id}", DRAFT_READ), + Map.entry("GET " + BASE + "/{id}/versions", DRAFT_READ), + Map.entry("GET " + BASE + "/{id}/versions/{version}", DRAFT_READ), + Map.entry("GET " + BASE + "/history", DRAFT_READ + " for each change set, else dropped"), + Map.entry("PUT " + BASE + "/{id}/operations", DRAFT_READ + ", then EditAll, then lease"), + Map.entry("POST " + BASE + "/{id}/undo", DRAFT_READ + ", then EditAll, then lease"), + Map.entry("POST " + BASE + "/{id}/redo", DRAFT_READ + ", then EditAll, then lease"), + Map.entry("POST " + BASE + "/{id}/discard", DRAFT_READ + ", then EditAll, then lease"), + Map.entry("POST " + BASE + "/{id}/submit", "EditAll on the scope, then lease"), + Map.entry("POST " + BASE + "/{id}/apply", "EditAll on the scope, then lease"), + Map.entry("DELETE " + BASE + "/{id}", DRAFT_READ + ", then Delete"), + Map.entry("PUT " + BASE + "/restore", DRAFT_READ + ", then EditAll"), + Map.entry("GET " + BASE + "/{id}/context", "ViewAll, and the answer holds no operations"), + Map.entry( + "GET " + BASE + "/name/{fqn}/context", + "ViewAll, and the answer holds no operations")); + + @Test + void everyEndpointOfTheResourceStatesItsRight() { + assertEquals(RIGHT_OF.keySet(), endpointsOf(OntologyChangeSetResource.class).keySet()); + } + + @Test + void everyRowNamesARight() { + RIGHT_OF.forEach((endpoint, right) -> assertFalse(right.isBlank(), endpoint)); + } + + @Test + void theResourceExposesNoEndpointTwice() { + final Map counts = new TreeMap<>(); + for (final Method method : OntologyChangeSetResource.class.getMethods()) { + final String endpoint = endpointOf(method); + if (endpoint != null) { + counts.merge(endpoint, 1, Integer::sum); + } + } + + counts.forEach((endpoint, count) -> assertEquals(1, count, endpoint)); + } + + private static Map endpointsOf(final Class resource) { + final Map endpoints = new TreeMap<>(); + for (final Method method : resource.getMethods()) { + final String endpoint = endpointOf(method); + if (endpoint != null) { + endpoints.put(endpoint, method); + } + } + return endpoints; + } + + private static String endpointOf(final Method method) { + final String verb = verbOf(method); + final Path own = method.getAnnotation(Path.class); + final Path base = OntologyChangeSetResource.class.getAnnotation(Path.class); + return verb == null ? null : verb + " " + base.value() + (own == null ? "" : own.value()); + } + + private static String verbOf(final Method method) { + String verb = null; + verb = method.isAnnotationPresent(GET.class) ? "GET" : verb; + verb = method.isAnnotationPresent(POST.class) ? "POST" : verb; + verb = method.isAnnotationPresent(PUT.class) ? "PUT" : verb; + verb = method.isAnnotationPresent(DELETE.class) ? "DELETE" : verb; + verb = method.isAnnotationPresent(PATCH.class) ? "PATCH" : verb; + return verb; + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionRightsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionRightsTest.java new file mode 100644 index 000000000000..63a5ee5325ca --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/resources/ontology/OntologyDeclinedDefinitionRightsTest.java @@ -0,0 +1,311 @@ +/* + * 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.resources.ontology; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import jakarta.ws.rs.BadRequestException; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PATCH; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.core.SecurityContext; +import java.lang.reflect.Method; +import java.net.URI; +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.openmetadata.schema.api.data.DeclineOntologyDefinitions; +import org.openmetadata.schema.api.data.MatchOntologyDeclinedDefinitions; +import org.openmetadata.schema.entity.data.OntologyChangeSet; +import org.openmetadata.schema.entity.data.OntologyConcept; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OntologyChangeOperation; +import org.openmetadata.schema.type.OntologyChangeOperationType; +import org.openmetadata.service.Entity; +import org.openmetadata.service.jdbi3.CollectionDAO; +import org.openmetadata.service.jdbi3.OntologyChangeSetRepository; +import org.openmetadata.service.jdbi3.OntologyDeclinedDefinitionDAO; +import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.policyevaluator.OperationContext; +import org.openmetadata.service.security.policyevaluator.ResourceContext; +import org.openmetadata.service.security.policyevaluator.ResourceContextInterface; +import org.openmetadata.service.util.EntityUtil.Fields; + +/** + * The declined-definition endpoints return or store the IRIs of a change set's operations, so each + * asks the right that reading those operations needs before it reads or writes anything. A new + * endpoint on the path fails this test until its row is added below, and the rows are then held to + * their word by calling each endpoint with a caller the authorizer refuses. + */ +class OntologyDeclinedDefinitionRightsTest { + private static final String BASE = "/v1/ontologies/{id}/declinedDefinitions"; + private static final String DRAFT_READ = "EditAll on the ontology"; + + private static final Map RIGHT_OF = + Map.of( + "POST " + BASE, + "EditAll on the change set, then " + + DRAFT_READ + + " that owns it, then the ontology match", + "GET " + BASE, + DRAFT_READ, + "POST " + BASE + "/match", + DRAFT_READ); + + private final UUID ontologyId = UUID.randomUUID(); + private final UUID otherOntologyId = UUID.randomUUID(); + private final UUID changeSetId = UUID.randomUUID(); + private final SecurityContext caller = Mockito.mock(SecurityContext.class); + + /** A decision of the mocked authorizer: the resource type, its id and the operation asked. */ + private record Asked(String resourceType, Object scope, MetadataOperation operation) {} + + @Test + void everyDeclinedDefinitionEndpointStatesItsRight() { + final Map endpoints = new TreeMap<>(); + for (final Method method : OntologyResource.class.getMethods()) { + final String endpoint = endpointOf(method); + if (endpoint != null && endpoint.contains("declinedDefinitions")) { + endpoints.put(endpoint, method); + } + } + + assertEquals(RIGHT_OF.keySet(), endpoints.keySet()); + RIGHT_OF.forEach((endpoint, right) -> assertFalse(right.isBlank(), endpoint)); + } + + @Test + void aCallerRefusedTheDraftReadStoresNothingAndLearnsNothing() { + final Scene scene = new Scene(ontologyId, Set.of(ontologyId)); + + try (Scene.Open ignored = scene.open()) { + assertThrows( + AuthorizationException.class, + () -> scene.endpoint().decline(caller, ontologyId, scene.request())); + } + + assertEquals( + List.of( + new Asked(Entity.ONTOLOGY_CHANGE_SET, changeSetId, MetadataOperation.EDIT_ALL), + new Asked(Entity.ONTOLOGY, ontologyId, MetadataOperation.EDIT_ALL)), + scene.asked); + Mockito.verifyNoInteractions(scene.dao); + } + + @Test + void aChangeSetOfAnotherOntologyIsRefusedTheReadBeforeItIsRefusedTheMismatch() { + final Scene scene = new Scene(otherOntologyId, Set.of(otherOntologyId)); + + try (Scene.Open ignored = scene.open()) { + assertThrows( + AuthorizationException.class, + () -> scene.endpoint().decline(caller, ontologyId, scene.request())); + } + + assertEquals( + new Asked(Entity.ONTOLOGY, otherOntologyId, MetadataOperation.EDIT_ALL), + scene.asked.getLast()); + Mockito.verifyNoInteractions(scene.dao); + } + + @Test + void aCallerWhoMayReadTheChangeSetOfAnotherOntologyIsToldItDoesNotBelong() { + final Scene scene = new Scene(otherOntologyId, Set.of()); + + try (Scene.Open ignored = scene.open()) { + final BadRequestException refusal = + assertThrows( + BadRequestException.class, + () -> scene.endpoint().decline(caller, ontologyId, scene.request())); + assertEquals( + "Change set '" + changeSetId + "' does not belong to ontology '" + ontologyId + "'", + refusal.getMessage()); + } + + Mockito.verifyNoInteractions(scene.dao); + } + + @Test + void aCallerWhoMayReadTheChangeSetDeclinesItsOperation() { + final Scene scene = new Scene(ontologyId, Set.of()); + + try (Scene.Open ignored = scene.open()) { + assertEquals( + 1, scene.endpoint().decline(caller, ontologyId, scene.request()).getRecords().size()); + } + + Mockito.verify(scene.dao).insertIfAbsent(Mockito.any()); + } + + @Test + void listAndMatchAskTheDraftReadRightOnTheOntologyBeforeTheyReadAnything() { + final Scene scene = new Scene(ontologyId, Set.of(ontologyId)); + + try (Scene.Open ignored = scene.open()) { + assertThrows( + AuthorizationException.class, () -> scene.endpoint().list(caller, ontologyId, 50, null)); + assertThrows( + AuthorizationException.class, + () -> + scene + .endpoint() + .match( + caller, + ontologyId, + new MatchOntologyDeclinedDefinitions().withCandidates(List.of()))); + } + + assertEquals( + List.of( + new Asked(Entity.ONTOLOGY, ontologyId, MetadataOperation.EDIT_ALL), + new Asked(Entity.ONTOLOGY, ontologyId, MetadataOperation.EDIT_ALL)), + scene.asked); + Mockito.verifyNoInteractions(scene.dao); + } + + /** + * One change set holding one concept, owned by {@code changeSetOntology}, and an authorizer that + * refuses the draft read right on the ontologies it is given. + */ + private final class Scene { + final List asked = new ArrayList<>(); + final OntologyDeclinedDefinitionDAO dao = Mockito.mock(OntologyDeclinedDefinitionDAO.class); + private final Authorizer authorizer = Mockito.mock(Authorizer.class); + private final OntologyChangeSet changeSet; + private final UUID operationId = UUID.randomUUID(); + + Scene(final UUID changeSetOntology, final Set refusedOntologies) { + changeSet = + new OntologyChangeSet() + .withId(changeSetId) + .withOntology(new EntityReference().withId(changeSetOntology).withType("ontology")) + .withOperations( + List.of( + new OntologyChangeOperation() + .withId(operationId) + .withOperationType(OntologyChangeOperationType.UPSERT_CONCEPT) + .withConcept( + new OntologyConcept() + .withId(UUID.randomUUID()) + .withName("Order") + .withIri(URI.create("https://example.org/sales/Order"))))); + Mockito.doAnswer( + call -> { + final ResourceContextInterface context = call.getArgument(2); + final OperationContext operation = call.getArgument(1); + final Object scope = scopes.get(context); + asked.add( + new Asked( + context.getResource(), scope, operation.getOperations(context).getFirst())); + if (Entity.ONTOLOGY.equals(context.getResource()) + && refusedOntologies.contains(scope)) { + throw new AuthorizationException("denied"); + } + return null; + }) + .when(authorizer) + .authorize( + Mockito.any(SecurityContext.class), + Mockito.any(OperationContext.class), + Mockito.any(ResourceContextInterface.class)); + final Principal principal = Mockito.mock(Principal.class); + Mockito.when(principal.getName()).thenReturn("editor"); + Mockito.when(caller.getUserPrincipal()).thenReturn(principal); + } + + private final Map scopes = new java.util.IdentityHashMap<>(); + + DeclineOntologyDefinitions request() { + return new DeclineOntologyDefinitions() + .withChangeSetId(changeSetId) + .withOperationIds(Set.of(operationId)); + } + + OntologyDeclinedDefinitionEndpoint endpoint() { + return new OntologyDeclinedDefinitionEndpoint(authorizer); + } + + Open open() { + final MockedStatic entity = Mockito.mockStatic(Entity.class); + final CollectionDAO collection = Mockito.mock(CollectionDAO.class); + Mockito.when(collection.ontologyDeclinedDefinitionDAO()).thenReturn(dao); + entity.when(Entity::getCollectionDAO).thenReturn(collection); + final OntologyChangeSetRepository repository = + Mockito.mock(OntologyChangeSetRepository.class); + Mockito.when(repository.getFields("operations")).thenReturn(Mockito.mock(Fields.class)); + Mockito.when( + repository.get( + Mockito.isNull(), + Mockito.eq(changeSetId), + Mockito.any(Fields.class), + Mockito.eq(Include.ALL), + Mockito.eq(false))) + .thenReturn(changeSet); + entity + .when(() -> Entity.getEntityRepository(Entity.ONTOLOGY_CHANGE_SET)) + .thenReturn(repository); + final MockedConstruction contexts = + Mockito.mockConstruction( + ResourceContext.class, + (context, creation) -> { + scopes.put(context, creation.arguments().get(1)); + Mockito.when(context.getResource()) + .thenReturn((String) creation.arguments().get(0)); + }); + return new Open(entity, contexts); + } + + record Open(MockedStatic entity, MockedConstruction contexts) + implements AutoCloseable { + @Override + public void close() { + contexts.close(); + entity.close(); + } + } + } + + private static String endpointOf(final Method method) { + final String verb = verbOf(method); + final Path own = method.getAnnotation(Path.class); + final Path base = OntologyResource.class.getAnnotation(Path.class); + return verb == null ? null : verb + " " + base.value() + (own == null ? "" : own.value()); + } + + private static String verbOf(final Method method) { + String verb = null; + verb = method.isAnnotationPresent(GET.class) ? "GET" : verb; + verb = method.isAnnotationPresent(POST.class) ? "POST" : verb; + verb = method.isAnnotationPresent(PUT.class) ? "PUT" : verb; + verb = method.isAnnotationPresent(DELETE.class) ? "DELETE" : verb; + verb = method.isAnnotationPresent(PATCH.class) ? "PATCH" : verb; + return verb; + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/SuggestionTypeRoutingTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/SuggestionTypeRoutingTest.java new file mode 100644 index 000000000000..4b731abf8f93 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/SuggestionTypeRoutingTest.java @@ -0,0 +1,98 @@ +/* + * 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.tasks; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; + +import java.io.InputStream; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.jdbi3.TaskFormSchemaRepository; +import org.openmetadata.service.jdbi3.TaskRepository; + +class SuggestionTypeRoutingTest { + + @ParameterizedTest + @CsvSource({ + "Description,DescriptionSuggestion", + "Tag,TagSuggestion", + "TableConstraint,TableConstraintSuggestion", + "tableconstraint,TableConstraintSuggestion" + }) + void aSuggestionTypeMapsToItsSeededForm(String suggestionType, String expectedForm) + throws Exception { + TaskFormSchemaRepository repository = mock(TaskFormSchemaRepository.class, CALLS_REAL_METHODS); + Method method = + TaskFormSchemaRepository.class.getDeclaredMethod("getSuggestionSchemaName", Object.class); + method.setAccessible(true); + + Object form = method.invoke(repository, Map.of("suggestionType", suggestionType)); + + assertEquals(Optional.of(expectedForm), form); + } + + @Test + void theSeededTableConstraintFormIsASuggestionForm() throws Exception { + try (InputStream stream = + getClass() + .getClassLoader() + .getResourceAsStream("json/data/taskFormSchemas/TableConstraintSuggestion.json")) { + Map form = + JsonUtils.readValue(new String(stream.readAllBytes(), StandardCharsets.UTF_8), Map.class); + + assertEquals("TableConstraintSuggestion", form.get("name")); + assertEquals("Suggestion", form.get("taskType")); + assertEquals("MetadataUpdate", form.get("taskCategory")); + assertTrue(form.toString().contains("suggestedValue")); + } + } + + @ParameterizedTest + @CsvSource({ + "Description,EDIT_DESCRIPTION", + "Tag,EDIT_TAGS", + "Owner,EDIT_OWNERS", + "Tier,EDIT_TIER", + "Domain,EDIT_ALL", + "CustomProperty,EDIT_CUSTOM_FIELDS", + "TableConstraint,EDIT_ALL" + }) + void approvingASuggestionNeedsTheOperationForItsType( + String suggestionType, MetadataOperation expected) throws Exception { + TaskRepository repository = mock(TaskRepository.class, CALLS_REAL_METHODS); + Task task = + new Task() + .withId(UUID.randomUUID()) + .withType(TaskEntityType.Suggestion) + .withPayload( + Map.of("suggestionType", suggestionType, "fieldPath", "x", "suggestedValue", "y")); + Method method = TaskRepository.class.getDeclaredMethod("getOperationForSuggestion", Task.class); + method.setAccessible(true); + + assertEquals(expected, method.invoke(repository, task)); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java new file mode 100644 index 000000000000..b0e64c8b58c3 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TableConstraintSuggestionTest.java @@ -0,0 +1,996 @@ +/* + * 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.tasks; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import jakarta.json.JsonPatch; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.feed.TaskFormSchema; +import org.openmetadata.schema.entity.feed.UiSchema; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.TableConstraint; +import org.openmetadata.schema.type.TableConstraint.ConstraintType; +import org.openmetadata.schema.type.TableConstraint.RelationshipType; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.type.TaskResolutionType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.governance.approval.ApprovalDecisionService; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.TableRepository; +import org.openmetadata.service.jdbi3.TaskFormSchemaRepository; + +class TableConstraintSuggestionTest { + private static final String ORDERS = "svc.db.schema.orders"; + private static final String CUSTOMERS = "svc.db.schema.customers"; + private MockedStatic entity; + private Table orders; + private TableRepository tableRepository; + private TaskFormSchemaRepository formRepository; + + @BeforeEach + void setUp() { + orders = table("orders", ORDERS, "order_id", "customer_id", "email"); + Table customers = table("customers", CUSTOMERS, "id"); + tableRepository = mock(TableRepository.class); + formRepository = mock(TaskFormSchemaRepository.class); + entity = mockStatic(Entity.class); + entity.when(() -> Entity.getEntityRepository(Entity.TABLE)).thenAnswer(i -> tableRepository); + entity + .when(() -> Entity.getEntityRepository(Entity.TASK_FORM_SCHEMA)) + .thenAnswer(i -> formRepository); + entity + .when(() -> Entity.getEntity(any(EntityReference.class), anyString(), any(Include.class))) + .thenAnswer(invocation -> orders); + entity + .when(() -> Entity.getEntityByName(eq(Entity.TABLE), anyString(), anyString(), any())) + .thenAnswer( + invocation -> { + String fqn = invocation.getArgument(1); + if (CUSTOMERS.equals(fqn)) { + return customers; + } + throw EntityNotFoundException.byName(fqn); + }); + } + + @AfterEach + void tearDown() { + entity.close(); + } + + @Test + void aPrimaryKeyOnExistingColumns_isAccepted() { + Task task = task(Entity.TABLE, constraint(ConstraintType.PRIMARY_KEY, List.of("order_id"))); + + assertDoesNotThrow(() -> TableConstraintSuggestion.require(task)); + } + + @Test + void aForeignKeyToAnotherTablesColumn_isAccepted() { + TableConstraint foreignKey = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of(CUSTOMERS + ".id")) + .withRelationshipType(RelationshipType.MANY_TO_ONE); + + assertDoesNotThrow(() -> TableConstraintSuggestion.require(task(Entity.TABLE, foreignKey))); + } + + @Test + void aTaskAboutAnotherEntityType_isRefused() { + Task task = task(Entity.DASHBOARD, constraint(ConstraintType.UNIQUE, List.of("email"))); + + BadRequestException e = + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)); + + assertEquals( + "A table constraint suggestion must be about a table, not dashboard", e.getMessage()); + } + + @Test + void aSuggestedValueThatIsNotAConstraint_isRefused() { + Task task = taskWithValue("not json at all"); + + BadRequestException e = + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)); + + assertEquals("Suggested value is not a table constraint: not json at all", e.getMessage()); + } + + @Test + void aConstraintWithoutAType_isRefused() { + Task task = taskWithValue("{\"columns\":[\"email\"]}"); + + BadRequestException e = + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)); + + assertEquals( + "Suggested value is not a table constraint: it has no constraintType", e.getMessage()); + } + + @Test + void aColumnTheTableDoesNotHave_isRefused() { + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("missing"))); + + BadRequestException e = + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)); + + assertEquals("Column 'missing' is not a column of table '" + ORDERS + "'", e.getMessage()); + } + + @Test + void aReferredColumnThatResolvesToNothing_isRefused() { + TableConstraint missingTable = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of("svc.db.schema.ghosts.id")); + TableConstraint missingColumn = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of(CUSTOMERS + ".nope")); + + assertEquals( + "Referred column 'svc.db.schema.ghosts.id' does not resolve to a column of an existing table", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.require(task(Entity.TABLE, missingTable))) + .getMessage()); + assertEquals( + "Referred column '" + + CUSTOMERS + + ".nope' does not resolve to a column of an existing table", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.require(task(Entity.TABLE, missingColumn))) + .getMessage()); + } + + @Test + void aSortKey_isRefused() { + Task task = task(Entity.TABLE, constraint(ConstraintType.SORT_KEY, List.of("order_id"))); + + BadRequestException e = + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)); + + assertEquals( + "Table constraint type SORT_KEY cannot be suggested; use PRIMARY_KEY, UNIQUE or FOREIGN_KEY", + e.getMessage()); + } + + @Test + void aFieldPathOtherThanTableConstraints_isRefused() { + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + @SuppressWarnings("unchecked") + Map payload = (Map) task.getPayload(); + payload.put("fieldPath", "description"); + + BadRequestException e = + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)); + + assertEquals( + "Field path of a table constraint suggestion must be 'tableConstraints', not 'description'", + e.getMessage()); + } + + @Test + void aSecondPrimaryKey_isRefusedAtApprovalNamingTheExistingOne() { + orders.setTableConstraints( + List.of(constraint(ConstraintType.PRIMARY_KEY, List.of("order_id")))); + Task task = task(Entity.TABLE, constraint(ConstraintType.PRIMARY_KEY, List.of("email"))); + + BadRequestException e = + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.requireToApply(task, null, null)); + + assertEquals( + "Table '" + + ORDERS + + "' already has a primary key on columns [order_id]; " + + "a table has one primary key", + e.getMessage()); + } + + @Test + void anEqualConstraintAlreadyOnTheTable_addsNothing() { + TableConstraint present = constraint(ConstraintType.PRIMARY_KEY, List.of("order_id")); + orders.setTableConstraints(List.of(present)); + + assertEquals( + Optional.empty(), + TableConstraintSuggestion.toAdd( + orders, constraint(ConstraintType.PRIMARY_KEY, List.of("order_id")))); + } + + @Test + void aUniqueConstraintBesidesAPrimaryKey_isAdded() { + orders.setTableConstraints( + List.of(constraint(ConstraintType.PRIMARY_KEY, List.of("order_id")))); + TableConstraint unique = constraint(ConstraintType.UNIQUE, List.of("email")); + + assertEquals(Optional.of(unique), TableConstraintSuggestion.toAdd(orders, unique)); + } + + @Test + void applyingASuggestion_addsTheConstraintToTheTableAsTheApprover() throws Exception { + EntityRepository repository = mock(EntityRepository.class); + TableConstraint foreignKey = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of(CUSTOMERS + ".id")) + .withRelationshipType(RelationshipType.MANY_TO_ONE); + + invokeApplySuggestion(task(Entity.TABLE, foreignKey), orders, repository, "approver"); + + ArgumentCaptor patch = ArgumentCaptor.forClass(JsonPatch.class); + verify(repository).patch(any(), eq(orders.getId()), eq("approver"), patch.capture(), any()); + String operations = patch.getValue().toJsonArray().toString(); + assertTrue(operations.contains("\"op\":\"add\""), operations); + assertTrue(operations.contains("\"path\":\"/tableConstraints\""), operations); + assertTrue(operations.contains("\"relationshipType\":\"MANY_TO_ONE\""), operations); + assertTrue(operations.contains("\"referredColumns\":[\"" + CUSTOMERS + ".id\"]"), operations); + } + + @Test + void applyingASuggestionTheTableAlreadyHas_writesNothing() throws Exception { + EntityRepository repository = mock(EntityRepository.class); + orders.setTableConstraints( + new ArrayList<>(List.of(constraint(ConstraintType.UNIQUE, List.of("email"))))); + + invokeApplySuggestion( + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), + orders, + repository, + "approver"); + + verify(repository, never()).patch(any(), any(UUID.class), anyString(), any(), any()); + assertEquals(1, orders.getTableConstraints().size()); + } + + @Test + void aForeignKeyOnTheSameColumnsReferringToAnotherColumn_isNotTheSuggestedOne() { + TableConstraint present = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of(CUSTOMERS + ".other")); + orders.setTableConstraints(List.of(present)); + TableConstraint suggested = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of(CUSTOMERS + ".id")); + + assertEquals(Optional.of(suggested), TableConstraintSuggestion.toAdd(orders, suggested)); + } + + @Test + void aForeignKeyOfTwoColumnsWithOneReferredColumn_isRefused() { + TableConstraint foreignKey = + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id", "order_id")) + .withReferredColumns(List.of(CUSTOMERS + ".id")); + + assertEquals( + "A foreign key needs one referred column for each of its 2 columns, not 1", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.require(task(Entity.TABLE, foreignKey))) + .getMessage()); + } + + @Test + void aForeignKeyWithNoReferredColumns_isRefused() { + TableConstraint foreignKey = constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")); + + assertEquals( + "A foreign key needs one referred column for each of its 1 columns, not 0", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.require(task(Entity.TABLE, foreignKey))) + .getMessage()); + } + + @Test + void aUniqueConstraintWithReferredColumns_isRefused() { + TableConstraint unique = + constraint(ConstraintType.UNIQUE, List.of("email")) + .withReferredColumns(List.of(CUSTOMERS + ".id")); + + assertEquals( + "Only a foreign key has referredColumns, not UNIQUE", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.require(task(Entity.TABLE, unique))) + .getMessage()); + } + + @Test + void aFailureWhileApplying_escapesWithItsCause() throws Exception { + EntityRepository repository = mock(EntityRepository.class); + doThrow(new IllegalStateException("write failed")) + .when(repository) + .patch(any(), any(UUID.class), anyString(), any(), any()); + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + java.lang.reflect.InvocationTargetException thrown = + assertThrows( + java.lang.reflect.InvocationTargetException.class, + () -> invokeApplySuggestion(task, orders, repository, "approver")); + + assertEquals("write failed", thrown.getCause().getMessage()); + } + + @ParameterizedTest + @EnumSource( + value = TaskEntityType.class, + names = {"CustomTask", "DescriptionUpdate"}) + void aTaskOfAnotherTypeCarryingAConstraintPayload_getsNoCheckNoWriteAndNoRethrow( + TaskEntityType otherType) throws Exception { + Task unchecked = taskWithValue("not json at all").withType(otherType); + EntityRepository repository = mock(EntityRepository.class); + doThrow(new IllegalStateException("write failed")) + .when(repository) + .patch(any(), any(UUID.class), anyString(), any(), any()); + Task applied = + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))).withType(otherType); + + assertEquals(false, TableConstraintSuggestion.isTableConstraint(unchecked)); + assertDoesNotThrow(() -> TableConstraintSuggestion.require(unchecked)); + assertDoesNotThrow(() -> TableConstraintSuggestion.requireToApply(unchecked, null, null)); + assertDoesNotThrow(() -> invokeApplySuggestion(applied, orders, repository, "approver")); + verify(repository, never()).patch(any(), any(UUID.class), anyString(), any(), any()); + + Task suggestion = applied.withType(TaskEntityType.Suggestion); + java.lang.reflect.InvocationTargetException thrown = + assertThrows( + java.lang.reflect.InvocationTargetException.class, + () -> invokeApplySuggestion(suggestion, orders, repository, "approver")); + assertEquals("write failed", thrown.getCause().getMessage()); + } + + private static final String KEYS_REFUSED = + "A table constraint suggestion carries only the keys of the suggestion payload (confidence, " + + "currentValue, fieldPath, reasoning, source, suggestedValue, suggestionType); not allowed: "; + + @ParameterizedTest + @ValueSource( + strings = { + "changeRequestId", + "newOwners", + "feedback", + "expirationDate", + "lifecycleMove", + "proposedChanges", + "assignees", + "SuggestedValue", + "suggestedvalue", + " suggestedValue" + }) + void aKeyTheSuggestionPayloadDoesNotDeclare_isRefusedWhenFiledAndWhenApproved(String key) { + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + payloadOf(task).put(key, "x"); + + assertEquals( + KEYS_REFUSED + key, + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)) + .getMessage()); + assertEquals( + KEYS_REFUSED + key, + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.requireToApply(task, null, null)) + .getMessage()); + } + + @Test + void everyKeyTheSuggestionPayloadDeclares_isAccepted() { + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + Map payload = payloadOf(task); + payload.put("currentValue", "[]"); + payload.put("confidence", 80.0); + payload.put("source", "Agent"); + payload.put("reasoning", "The column is unique in the sampled rows"); + + assertEquals(7, payload.size()); + assertDoesNotThrow(() -> TableConstraintSuggestion.require(task)); + assertDoesNotThrow(() -> TableConstraintSuggestion.requireToApply(task, null, null)); + } + + @Test + void severalUndeclaredKeys_areAllNamedInOrder() { + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + payloadOf(task).put("newOwners", "x"); + payloadOf(task).put("changeRequestId", "y"); + + assertEquals( + KEYS_REFUSED + "changeRequestId, newOwners", + assertThrows(BadRequestException.class, () -> TableConstraintSuggestion.require(task)) + .getMessage()); + } + + @Test + void aResolutionPayloadThatAddsAnUndeclaredKey_isRefusedForAConstraintSuggestionOnly() { + Task constraintTask = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + Task descriptionTask = descriptionTask(); + Map resolution = Map.of("changeRequestId", "x"); + + assertEquals( + KEYS_REFUSED + "changeRequestId", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.requireNoNewKeys(constraintTask, resolution, null)) + .getMessage()); + assertDoesNotThrow( + () -> + TableConstraintSuggestion.requireNoNewKeys( + constraintTask, Map.of("source", "User"), null)); + assertDoesNotThrow( + () -> TableConstraintSuggestion.requireNoNewKeys(constraintTask, null, null)); + assertDoesNotThrow( + () -> TableConstraintSuggestion.requireNoNewKeys(descriptionTask, resolution, null)); + } + + @ParameterizedTest + @EnumSource( + value = TaskResolutionType.class, + names = {"Approved", "Rejected"}) + void aNewValueUnderAnUndeclaredValueField_isRefusedForEveryResolution(TaskResolutionType type) { + boundTo(form(Map.of("type", "suggestion", "valueField", "changeRequestId"), Map.of())); + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + BadRequestException refused = + assertThrows( + BadRequestException.class, () -> resolve(task, type, UUID.randomUUID().toString())); + + assertEquals(KEYS_REFUSED + "changeRequestId", refused.getMessage()); + } + + @Test + void aRejectionWithNoNewValueUnderAnUndeclaredValueField_passesTheKeyCheck() { + boundTo(form(Map.of("type", "suggestion", "valueField", "changeRequestId"), Map.of())); + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + assertEquals(DECISION_REACHED, resolveToTheDecision(task, TaskResolutionType.Rejected, null)); + } + + @Test + void aNewValueUnderADeclaredValueField_passesTheKeyCheck() { + boundTo(form(Map.of("type", "suggestion", "valueField", "reasoning"), Map.of())); + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + assertEquals(DECISION_REACHED, resolveToTheDecision(task, TaskResolutionType.Rejected, "why")); + } + + @Test + void aStoredLifecycleMove_doesNotStopARejectionAndStopsApproval() { + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + payloadOf(task).put("lifecycleMove", "Archive"); + + assertEquals(DECISION_REACHED, resolveToTheDecision(task, TaskResolutionType.Rejected, null)); + assertEquals( + KEYS_REFUSED + "lifecycleMove", + assertThrows( + BadRequestException.class, () -> resolve(task, TaskResolutionType.Approved, null)) + .getMessage()); + } + + private static final String DECISION_REACHED = "the decision was recorded"; + + private static void resolve(Task task, TaskResolutionType type, String newValue) { + TaskWorkflowHandler.getInstance() + .resolveTask(task, null, type, newValue, null, null, "approver"); + } + + /** Runs a resolution up to the point where it would record the resolver's decision. */ + private static String resolveToTheDecision(Task task, TaskResolutionType type, String newValue) { + try (MockedStatic decisions = + mockStatic(ApprovalDecisionService.class)) { + decisions + .when(() -> ApprovalDecisionService.recordForTask(any(), any(), any(), any(), any())) + .thenThrow(new IllegalStateException(DECISION_REACHED)); + resolve(task, type, newValue); + return "the resolution went on"; + } catch (IllegalStateException reached) { + return reached.getMessage(); + } + } + + @SuppressWarnings("unchecked") + private static Map payloadOf(Task task) { + return (Map) task.getPayload(); + } + + @Test + void aResolutionCannotTurnADescriptionSuggestionIntoAConstraint() { + Task description = descriptionTask(); + Map resolution = + Map.of( + "suggestionType", + "TableConstraint", + "fieldPath", + "tableConstraints", + "suggestedValue", + JsonUtils.pojoToJson(constraint(ConstraintType.PRIMARY_KEY, List.of("order_id")))); + + assertEquals( + "A resolution cannot change the suggestion type of a task to or from TableConstraint: " + + "the task is 'Description', the resolution says 'TableConstraint'", + assertThrows( + BadRequestException.class, + () -> TableConstraintSuggestion.requireSameSuggestionType(description, resolution)) + .getMessage()); + } + + @Test + void aResolutionCannotTurnAConstraintSuggestionIntoAnotherType() { + Task constraintTask = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + assertEquals( + "A resolution cannot change the suggestion type of a task to or from TableConstraint: " + + "the task is 'TableConstraint', the resolution says 'Owner'", + assertThrows( + BadRequestException.class, + () -> + TableConstraintSuggestion.requireSameSuggestionType( + constraintTask, Map.of("suggestionType", "Owner"))) + .getMessage()); + } + + @Test + void aResolutionBetweenOtherTypesOrOfTheSameType_isNotRefusedHere() { + Task constraintTask = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + assertDoesNotThrow( + () -> + TableConstraintSuggestion.requireSameSuggestionType( + descriptionTask(), Map.of("suggestionType", "Tag"))); + assertDoesNotThrow( + () -> + TableConstraintSuggestion.requireSameSuggestionType( + constraintTask, Map.of("suggestionType", "TableConstraint"))); + assertDoesNotThrow( + () -> TableConstraintSuggestion.requireSameSuggestionType(constraintTask, null)); + assertDoesNotThrow( + () -> + TableConstraintSuggestion.requireSameSuggestionType( + constraintTask, Map.of("reasoning", "no type given"))); + assertEquals( + "A resolution cannot change the suggestion type of a task to or from TableConstraint: " + + "the task is 'Description', the resolution says 'TableConstraint'", + assertThrows( + BadRequestException.class, + () -> + TableConstraintSuggestion.requireSameSuggestionType( + descriptionTask(), Map.of("suggestionType", "TableConstraint"))) + .getMessage()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "tableconstraint", + "Tableconstraint", + "TABLECONSTRAINT", + " TableConstraint", + "TableConstraint " + }) + void aResolutionNamingTheTypeWithAnotherCaseOrSpacing_isRefused(String spelling) { + Task constraintTask = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + assertEquals( + "A resolution cannot change the suggestion type of a task to or from TableConstraint: " + + "the task is 'TableConstraint', the resolution says '" + + spelling + + "'", + assertThrows( + BadRequestException.class, + () -> + TableConstraintSuggestion.requireSameSuggestionType( + constraintTask, Map.of("suggestionType", spelling))) + .getMessage()); + } + + @Test + void approving_runsTheTableRepositoryValidationOnTheConstraintsWithTheNewOneAdded() { + TableConstraint present = constraint(ConstraintType.UNIQUE, List.of("order_id")); + orders.setTableConstraints(List.of(present)); + TableConstraint suggested = constraint(ConstraintType.UNIQUE, List.of("email")); + + TableConstraintSuggestion.requireToApply(task(Entity.TABLE, suggested), null, null); + + ArgumentCaptor

  • validated = ArgumentCaptor.forClass(Table.class); + verify(tableRepository).validateTableConstraints(validated.capture(), eq(Set.of())); + assertEquals(List.of(present, suggested), validated.getValue().getTableConstraints()); + } + + @Test + void aTableRepositoryRefusalOfTheConstraints_refusesApproving() { + doThrow(new IllegalArgumentException("Table not found: " + CUSTOMERS)) + .when(tableRepository) + .validateTableConstraints(any(Table.class), any()); + Task task = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))); + + assertEquals( + "Table not found: " + CUSTOMERS, + assertThrows( + IllegalArgumentException.class, + () -> TableConstraintSuggestion.requireToApply(task, null, null)) + .getMessage()); + } + + @Test + void approvingAnEqualConstraint_doesNotValidateTheTable() { + orders.setTableConstraints(List.of(constraint(ConstraintType.UNIQUE, List.of("email")))); + doThrow(new IllegalArgumentException("Table not found: " + CUSTOMERS)) + .when(tableRepository) + .validateTableConstraints(any(Table.class), any()); + + TableConstraintSuggestion.requireToApply( + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), null, null); + + verify(tableRepository, never()).validateTableConstraints(any(Table.class), any()); + Task notThereYet = task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("order_id"))); + assertEquals( + "Table not found: " + CUSTOMERS, + assertThrows( + IllegalArgumentException.class, + () -> TableConstraintSuggestion.requireToApply(notThereYet, null, null)) + .getMessage()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "approval handler with no approve actions", + "suggestion handler with the approve action setDescription", + "suggestion handler with the approve action patchEntityField", + "custom handler with the approve action replaceOwners" + }) + void approving_underAnyForm_addsTheConstraintAndMakesNoOtherChange(String formName) + throws Exception { + boundTo(formName); + EntityRepository repository = tableRepository; + TableConstraint unique = constraint(ConstraintType.UNIQUE, List.of("email")); + Task approved = task(Entity.TABLE, unique); + payloadOf(approved) + .put( + "newOwners", + List.of( + Map.of("id", UUID.randomUUID().toString(), "type", "user", "name", "newcomer"))); + + invokeApplyEntityChanges(approved, true, repository); + + ArgumentCaptor patch = ArgumentCaptor.forClass(JsonPatch.class); + verify(repository, times(1)) + .patch(any(), eq(orders.getId()), eq("approver"), patch.capture(), any()); + assertEquals( + "[{\"op\":\"add\",\"path\":\"/tableConstraints\",\"value\":[{\"constraintType\":\"UNIQUE\"," + + "\"columns\":[\"email\"]}]}]", + patch.getValue().toJsonArray().toString()); + assertEquals(null, orders.getDescription()); + assertEquals(null, orders.getOwners()); + } + + @Test + void approving_withTheDefaultForm_addsTheSameConstraint() throws Exception { + EntityRepository repository = tableRepository; + + invokeApplyEntityChanges( + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), true, repository); + + verify(repository, times(1)) + .patch(any(), eq(orders.getId()), eq("approver"), any(JsonPatch.class), any()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "approval handler with no approve actions", + "suggestion handler with the approve action setDescription" + }) + void rejecting_underAnyForm_writesNothing(String formName) throws Exception { + boundTo(formName); + EntityRepository repository = tableRepository; + + invokeApplyEntityChanges( + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), false, repository); + + verify(repository, never()).patch(any(), any(UUID.class), anyString(), any(), any()); + } + + @Test + void rejecting_underAFormWhoseRejectActionAppliesTheSuggestion_writesNothing() throws Exception { + when(formRepository.resolve(anyString(), any(), any())) + .thenReturn( + Optional.of( + form( + Map.of("type", "suggestion"), + Map.of( + "reject", Map.of("actions", List.of(Map.of("type", "applySuggestion"))))))); + EntityRepository repository = tableRepository; + + invokeApplyEntityChanges( + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), false, repository); + + verify(repository, never()).patch(any(), any(UUID.class), anyString(), any(), any()); + } + + @Test + void aFailureWhileApprovingUnderAnyForm_escapesSoTheTaskStaysOpen() throws Exception { + boundTo("approval handler with no approve actions"); + doThrow(new IllegalStateException("write failed")) + .when(tableRepository) + .patch(any(), any(UUID.class), anyString(), any(), any()); + + java.lang.reflect.InvocationTargetException thrown = + assertThrows( + java.lang.reflect.InvocationTargetException.class, + () -> + invokeApplyEntityChanges( + task(Entity.TABLE, constraint(ConstraintType.UNIQUE, List.of("email"))), + true, + tableRepository)); + + assertEquals("write failed", thrown.getCause().getMessage()); + } + + @Test + void aDescriptionSuggestionUnderTheDefaultForm_isStillAppliedByTheSameCall() throws Exception { + ArgumentCaptor patch = ArgumentCaptor.forClass(JsonPatch.class); + + invokeApplyEntityChanges(descriptionTask(), true, tableRepository); + + verify(tableRepository, times(1)) + .patch(any(), eq(orders.getId()), eq("approver"), patch.capture(), any()); + assertTrue(patch.getValue().toJsonArray().toString().contains("/description")); + } + + private void boundTo(TaskFormSchema form) { + when(formRepository.resolve(anyString(), any(), any())).thenReturn(Optional.of(form)); + } + + private void boundTo(String formName) { + TaskFormSchema form = + switch (formName) { + case "approval handler with no approve actions" -> form( + Map.of("type", "approval"), Map.of("approve", Map.of("actions", List.of()))); + case "suggestion handler with the approve action setDescription" -> form( + Map.of("type", "suggestion"), + Map.of("approve", Map.of("actions", List.of(Map.of("type", "setDescription"))))); + case "suggestion handler with the approve action patchEntityField" -> form( + Map.of("type", "suggestion"), + Map.of( + "approve", + Map.of( + "actions", + List.of( + Map.of( + "type", + "patchEntityField", + "entityField", + "description", + "value", + "patched by the form"))))); + default -> form( + Map.of("type", "custom"), + Map.of("approve", Map.of("actions", List.of(Map.of("type", "replaceOwners"))))); + }; + when(formRepository.resolve(anyString(), any(), any())).thenReturn(Optional.of(form)); + } + + private static TaskFormSchema form(Map handler, Map execution) { + return new TaskFormSchema() + .withUiSchema( + new UiSchema() + .withAdditionalProperty("ui:handler", handler) + .withAdditionalProperty("ui:execution", execution)); + } + + private static void invokeApplyEntityChanges( + Task task, boolean approved, EntityRepository repository) throws Exception { + Method applyEntityChanges = + TaskWorkflowHandler.class.getDeclaredMethod( + "applyEntityChanges", + Task.class, + boolean.class, + String.class, + Object.class, + String.class); + applyEntityChanges.setAccessible(true); + applyEntityChanges.invoke( + TaskWorkflowHandler.getInstance(), task, approved, null, null, "approver"); + } + + private Task descriptionTask() { + Map payload = new java.util.LinkedHashMap<>(); + payload.put("suggestionType", "Description"); + payload.put("fieldPath", "description"); + payload.put("suggestedValue", "a description"); + return new Task() + .withId(UUID.randomUUID()) + .withType(TaskEntityType.Suggestion) + .withAbout( + new EntityReference() + .withId(orders.getId()) + .withType(Entity.TABLE) + .withFullyQualifiedName(ORDERS)) + .withPayload(payload); + } + + private static void invokeApplySuggestion( + Task task, Table table, EntityRepository repository, String user) throws Exception { + Method applySuggestion = + TaskWorkflowHandler.class.getDeclaredMethod( + "applySuggestion", + Task.class, + Object.class, + EntityInterface.class, + EntityRepository.class, + String.class); + applySuggestion.setAccessible(true); + applySuggestion.invoke( + TaskWorkflowHandler.getInstance(), task, task.getPayload(), table, repository, user); + } + + private static final String FILED = "{\"constraintType\":\"UNIQUE\",\"columns\":[\"email\"]}"; + private static final String OTHER = + "{\"constraintType\":\"PRIMARY_KEY\",\"columns\":[\"order_id\"]}"; + + @Test + void anApprovalWithANewValue_namesTheFiledConstraintNotTheNewValue() { + Task task = taskWithValue(FILED); + + assertEquals( + Optional.of("Added table constraint: UNIQUE on [email]"), + TaskWorkflowHandler.resolutionComment(task, true, null, OTHER)); + } + + @Test + void anApprovalWhosePayloadCarriesAnotherConstraint_namesThatConstraint() { + assertEquals( + Optional.of("Added table constraint: PRIMARY_KEY on [order_id]"), + TaskWorkflowHandler.resolutionComment( + taskWithValue(FILED), true, Map.of("suggestedValue", OTHER), null)); + } + + @Test + void anApprovalWithoutANewValue_namesTheFiledConstraint() { + Task task = taskWithValue(FILED); + + assertEquals( + Optional.of("Added table constraint: UNIQUE on [email]"), + TaskWorkflowHandler.resolutionComment(task, true, null, null)); + } + + @Test + void anApprovalOfAForeignKey_namesItsReferredColumns() { + Task task = + task( + Entity.TABLE, + constraint(ConstraintType.FOREIGN_KEY, List.of("customer_id")) + .withReferredColumns(List.of(CUSTOMERS + ".id"))); + + assertEquals( + Optional.of( + "Added table constraint: FOREIGN_KEY on [customer_id] referring to [svc.db.schema.customers.id]"), + TaskWorkflowHandler.resolutionComment(task, true, null, null)); + } + + @Test + void anApprovalOfAConstraintTheTableHas_saysSo() { + orders.setTableConstraints(List.of(constraint(ConstraintType.UNIQUE, List.of("email")))); + + assertEquals( + Optional.of("Table already has constraint: UNIQUE on [email]"), + TaskWorkflowHandler.resolutionComment(taskWithValue(FILED), true, null, null)); + } + + @Test + void aRejectionWithANewValue_leavesNoComment() { + assertEquals( + Optional.empty(), + TaskWorkflowHandler.resolutionComment(taskWithValue(FILED), false, null, OTHER)); + } + + @Test + void aDescriptionSuggestionsComment_keepsItsText() { + Task description = + new Task() + .withId(UUID.randomUUID()) + .withType(TaskEntityType.Suggestion) + .withPayload( + Map.of( + "suggestionType", + "Description", + "fieldPath", + "description", + "suggestedValue", + "The filed text")); + + assertEquals( + Optional.of("Resolved with value: The approver's text"), + TaskWorkflowHandler.resolutionComment(description, true, null, "The approver's text")); + assertEquals( + Optional.empty(), + TaskWorkflowHandler.resolutionComment(description, true, null, "The filed text")); + } + + private static Table table(String name, String fqn, String... columns) { + List columnList = new ArrayList<>(); + for (String column : columns) { + columnList.add(new Column().withName(column)); + } + return new Table() + .withId(UUID.randomUUID()) + .withName(name) + .withFullyQualifiedName(fqn) + .withColumns(columnList); + } + + private static TableConstraint constraint(ConstraintType type, List columns) { + return new TableConstraint().withConstraintType(type).withColumns(columns); + } + + private Task task(String aboutType, TableConstraint constraint) { + return taskWithValue(aboutType, JsonUtils.pojoToJson(constraint)); + } + + private Task taskWithValue(String value) { + return taskWithValue(Entity.TABLE, value); + } + + private Task taskWithValue(String aboutType, String value) { + Map payload = new java.util.LinkedHashMap<>(); + payload.put("suggestionType", "TableConstraint"); + payload.put("fieldPath", "tableConstraints"); + payload.put("suggestedValue", value); + return new Task() + .withId(UUID.randomUUID()) + .withType(TaskEntityType.Suggestion) + .withAbout( + new EntityReference() + .withId(orders.getId()) + .withType(aboutType) + .withFullyQualifiedName(ORDERS)) + .withPayload(payload); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java index 68fc7e8809b8..ccf1530eb0fe 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TaskWorkflowHandlerTest.java @@ -153,6 +153,93 @@ void testRejectWithRequiresCommentTransitionAllowsMissingComment() { } } + @Test + void anApprovalPostsItsCommentAndThenResolvesTheTask() { + Task task = standaloneDescriptionTask(); + TaskRepository taskRepository = mock(TaskRepository.class); + when(taskRepository.resolveTask(any(), any(TaskResolution.class), any(), anyString(), any())) + .thenReturn(task); + + resolveStandalone(task, taskRepository, TaskResolutionType.Approved, "An edited description"); + + ArgumentCaptor posted = ArgumentCaptor.forClass(TaskComment.class); + var order = Mockito.inOrder(taskRepository); + order.verify(taskRepository).addComment(eq(task), posted.capture()); + order + .verify(taskRepository) + .resolveTask(eq(task), any(TaskResolution.class), any(), eq("alice"), any()); + assertEquals( + "Resolved with description: An edited description", posted.getValue().getMessage()); + } + + @Test + void aRejectionPostsNoCommentEvenWhenItCarriesAValue() { + Task task = standaloneDescriptionTask(); + TaskRepository taskRepository = mock(TaskRepository.class); + when(taskRepository.resolveTask(any(), any(TaskResolution.class), any(), anyString(), any())) + .thenReturn(task); + + resolveStandalone( + task, taskRepository, TaskResolutionType.Rejected, "An edited description", "Not right"); + + verify(taskRepository, never()).addComment(any(), any()); + verify(taskRepository) + .resolveTask(eq(task), any(TaskResolution.class), any(), eq("alice"), any()); + } + + @Test + void theCommentIsAlreadyPostedWhenTheResolutionThrows() { + Task task = standaloneDescriptionTask(); + TaskRepository taskRepository = mock(TaskRepository.class); + when(taskRepository.resolveTask(any(), any(TaskResolution.class), any(), anyString(), any())) + .thenThrow(new IllegalStateException("the task could not be saved")); + + IllegalStateException thrown = + assertThrows( + IllegalStateException.class, + () -> + resolveStandalone( + task, taskRepository, TaskResolutionType.Approved, "An edited description")); + + assertEquals("the task could not be saved", thrown.getMessage()); + ArgumentCaptor posted = ArgumentCaptor.forClass(TaskComment.class); + verify(taskRepository).addComment(eq(task), posted.capture()); + assertEquals( + "Resolved with description: An edited description", posted.getValue().getMessage()); + } + + private static Task standaloneDescriptionTask() { + return new Task() + .withId(UUID.randomUUID()) + .withStatus(TaskEntityStatus.Open) + .withType(TaskEntityType.DescriptionUpdate); + } + + private static void resolveStandalone( + Task task, TaskRepository taskRepository, TaskResolutionType type, String newValue) { + resolveStandalone(task, taskRepository, type, newValue, null); + } + + private static void resolveStandalone( + Task task, + TaskRepository taskRepository, + TaskResolutionType type, + String newValue, + String comment) { + WorkflowHandler workflowHandler = mock(WorkflowHandler.class); + EntityUtil.Fields fields = new EntityUtil.Fields(Set.of("about")); + try (MockedStatic workflowMock = Mockito.mockStatic(WorkflowHandler.class); + MockedStatic entityMock = Mockito.mockStatic(Entity.class)) { + workflowMock.when(WorkflowHandler::getInstance).thenReturn(workflowHandler); + when(workflowHandler.hasActiveRuntimeTask(task.getId())).thenReturn(false); + entityMock.when(() -> Entity.getEntityRepository(Entity.TASK)).thenReturn(taskRepository); + when(taskRepository.getFields(anyString())).thenReturn(fields); + + TaskWorkflowHandler.getInstance() + .resolveTask(task, null, type, newValue, null, comment, "alice"); + } + } + @Test void testDefaultRuntimeTaskReadinessWaitIsBoundedBelowOneSecond() { assertTrue(TaskWorkflowHandler.DEFAULT_RUNTIME_TASK_READINESS_WAIT_MILLIS < 1_000L); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TestCaseSuggestionTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TestCaseSuggestionTest.java new file mode 100644 index 000000000000..4127ca0ed74c --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/tasks/TestCaseSuggestionTest.java @@ -0,0 +1,433 @@ +/* + * 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.tasks; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.openmetadata.schema.api.tests.CreateTestCase; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.tests.TestCaseGeneratedBy; +import org.openmetadata.schema.tests.TestCaseGeneratedByBinding; +import org.openmetadata.schema.tests.TestCaseParameterValue; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.type.TestCaseProposal; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.BadRequestException; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.TaskFormSchemaRepository; + +class TestCaseSuggestionTest { + private static final String ORDERS = "svc.db.schema.orders"; + private static final String LINK = "<#E::table::svc.db.schema.orders>"; + private static final String NAME = "shapeCheck_0123456789abcdef_89abcdef"; + private static final String STATEMENT = "SELECT COUNT(*) FROM t WHERE a \\: 1"; + private static final String DIGEST = + "eaeb9c3b192276e2837faaf6e15106f0a27ac7f3c958ca51a2b6ef18fcc7e2a0"; + private static final String IDENTITY = "a".repeat(64); + + private MockedStatic entity; + private Table orders; + private boolean testExists; + + @BeforeEach + void setUp() { + orders = + new Table().withId(UUID.randomUUID()).withName("orders").withFullyQualifiedName(ORDERS); + entity = mockStatic(Entity.class); + entity + .when(() -> Entity.getEntityRepository(Entity.TASK_FORM_SCHEMA)) + .thenAnswer(i -> mock(TaskFormSchemaRepository.class)); + entity + .when(() -> Entity.getEntity(any(EntityReference.class), anyString(), any(Include.class))) + .thenAnswer(invocation -> orders); + entity + .when(() -> Entity.getEntityByName(eq(Entity.TEST_CASE), anyString(), anyString(), any())) + .thenAnswer( + invocation -> { + if (testExists) { + return new org.openmetadata.schema.tests.TestCase().withName(NAME); + } + throw EntityNotFoundException.byName(invocation.getArgument(1)); + }); + } + + @AfterEach + void tearDown() { + entity.close(); + } + + @Test + void theDigestIsTheSha256OfTheCanonicalJsonOfTheTestEntityLinkAndParameters() { + assertEquals( + DIGEST, TestCaseSuggestion.digest("tableCustomSQLQuery", LINK, parameters(STATEMENT))); + } + + @Test + void theDigestChangesWithTheStatementAndWithTheOrderOfTheParameters() { + List reversed = new java.util.ArrayList<>(parameters(STATEMENT)); + java.util.Collections.reverse(reversed); + assertEquals( + false, DIGEST.equals(TestCaseSuggestion.digest("tableCustomSQLQuery", LINK, reversed))); + assertEquals( + false, + DIGEST.equals( + TestCaseSuggestion.digest( + "tableCustomSQLQuery", LINK, parameters(STATEMENT + " AND b = 2")))); + } + + @Test + void aProposalOfTheTableTheTaskIsAboutIsAccepted() { + assertDoesNotThrow(() -> TestCaseSuggestion.require(task(proposal()))); + } + + @Test + void aTaskOfAnotherSuggestionTypeIsNotChecked() { + Task other = task(proposal()); + ((Map) other.getPayload()).put("suggestionType", "Description"); + assertDoesNotThrow(() -> TestCaseSuggestion.require(other)); + } + + @Test + void aProposalAboutAnotherEntityTypeIsRefused() { + Task task = task(proposal()); + task.getAbout().setType(Entity.DASHBOARD); + assertEquals( + "A test case suggestion must be about a table, not dashboard", + refusal(() -> TestCaseSuggestion.require(task))); + } + + @Test + void aWrongFieldPathIsRefused() { + Task task = task(proposal()); + ((Map) task.getPayload()).put("fieldPath", "description"); + assertEquals( + "Field path of a test case suggestion must be 'testCases', not 'description'", + refusal(() -> TestCaseSuggestion.require(task))); + } + + @Test + void aTestOtherThanTheCustomStatementIsRefused() { + assertEquals( + "A test case suggestion proposes the test tableCustomSQLQuery, not columnValuesToBeNotNull", + refusal( + () -> + TestCaseSuggestion.require( + task( + with(p -> p.getTestCase().setTestDefinition("columnValuesToBeNotNull")))))); + } + + @Test + void aTestOfAnotherTableOrOfAColumnIsRefused() { + assertEquals( + "A test case suggestion proposes a test of the table it is about, svc.db.schema.orders, not <#E::table::svc.db.schema.items>", + refusal( + () -> + TestCaseSuggestion.require( + task( + with( + p -> + p.getTestCase() + .setEntityLink("<#E::table::svc.db.schema.items>")))))); + assertEquals( + "A test case suggestion proposes a test of the table it is about, svc.db.schema.orders, not <#E::table::svc.db.schema.orders::columns::id>", + refusal( + () -> + TestCaseSuggestion.require( + task( + with( + p -> + p.getTestCase() + .setEntityLink( + "<#E::table::svc.db.schema.orders::columns::id>")))))); + } + + @Test + void parametersOtherThanTheFourInTheirOrderAreRefused() { + assertEquals( + "A test case suggestion proposes the parameters [sqlExpression, strategy, operator, threshold] in that order, not [sqlExpression, strategy, operator, threshold, partitionExpression]", + refusal( + () -> + TestCaseSuggestion.require( + task( + with( + p -> { + List five = + new java.util.ArrayList<>(p.getTestCase().getParameterValues()); + five.add( + new TestCaseParameterValue() + .withName("partitionExpression") + .withValue("a = 1")); + p.getTestCase().setParameterValues(five); + }))))); + } + + @Test + void aStrategyOperatorOrThresholdThatDoesNotCountViolationsIsRefused() { + String message = + "A test case suggestion counts the records in violation: strategy COUNT, operator <= and threshold 0, with a statement"; + assertEquals( + message, + refusal( + () -> + TestCaseSuggestion.require( + task( + with(p -> p.getTestCase().getParameterValues().get(1).setValue("ROWS")))))); + assertEquals( + message, + refusal( + () -> + TestCaseSuggestion.require( + task(with(p -> p.getTestCase().getParameterValues().get(3).setValue("5")))))); + } + + @Test + void aTestThatComputesPassedAndFailedRowsIsRefused() { + assertEquals( + "A test case suggestion proposes a test that does not compute passed and failed rows", + refusal( + () -> + TestCaseSuggestion.require( + task(with(p -> p.getTestCase().setComputePassedFailedRowCount(true)))))); + } + + @Test + void aDigestThatIsNotTheDigestOfTheContentIsRefused() { + String message = + refusal( + () -> + TestCaseSuggestion.require( + task( + with( + p -> + p.getTestCase() + .getParameterValues() + .get(0) + .setValue(STATEMENT + " OR 1 = 1"))))); + assertEquals( + true, + message.startsWith( + "The content digest of a test case suggestion must be that of its test definition," + + " entity link and parameter values: ")); + } + + @Test + void aProposalWithNoInspectionQueryIsRefused() { + assertEquals( + "A test case suggestion carries the inspection query", + refusal(() -> TestCaseSuggestion.require(task(with(p -> p.setInspectionQuery(null)))))); + } + + @Test + void aProposalWithNoGeneratingClassIsRefusedWhenFiled() { + final String message = "A test case suggestion names the class it was generated for"; + assertEquals( + message, + refusal( + () -> TestCaseSuggestion.require(task(with(p -> p.getGeneratedBy().setClass_(null)))))); + assertEquals( + message, + refusal( + () -> + TestCaseSuggestion.require( + task(with(p -> p.getGeneratedBy().setClass_(new EntityReference())))))); + assertEquals( + message, + refusal(() -> TestCaseSuggestion.require(task(with(p -> p.setGeneratedBy(null)))))); + } + + @Test + void aResolutionThatLeavesNoGeneratingClassIsRefusedWhenApproved() { + final TestCaseProposal withoutClass = with(p -> p.getGeneratedBy().setClass_(null)); + final Map resolved = + Map.of("suggestedValue", JsonUtils.pojoToJson(withoutClass)); + + assertEquals( + "A test case suggestion names the class it was generated for", + refusal(() -> TestCaseSuggestion.requireToApply(task(proposal()), resolved, null))); + assertDoesNotThrow(() -> TestCaseSuggestion.requireToApply(task(proposal()), null, null)); + } + + @Test + void aValueThatIsNotAProposalIsRefused() { + Task task = task(proposal()); + ((Map) task.getPayload()).put("suggestedValue", "not json"); + assertEquals( + "Suggested value is not a test case proposal", + refusal(() -> TestCaseSuggestion.require(task))); + } + + @Test + void aKeyTheSuggestionPayloadDoesNotDeclareIsRefusedWhenFiling() { + Task task = task(proposal()); + ((Map) task.getPayload()).put("comment", "hello"); + String message = refusal(() -> TestCaseSuggestion.require(task)); + assertEquals( + true, + message.startsWith("A test case suggestion carries only the keys") + && message.endsWith("not allowed: comment")); + } + + @Test + void aResolutionCannotChangeTheSuggestionTypeToOrFromATestCase() { + Task task = task(proposal()); + BadRequestException toDescription = + assertThrows( + BadRequestException.class, + () -> + TableConstraintSuggestion.requireSameSuggestionType( + task, Map.of("suggestionType", "Description"))); + assertEquals( + "A resolution cannot change the suggestion type of a task to or from TestCase: the task is 'TestCase', the resolution says 'Description'", + toDescription.getMessage()); + Task description = task(proposal()); + ((Map) description.getPayload()).put("suggestionType", "Description"); + assertEquals( + "A resolution cannot change the suggestion type of a task to or from TestCase: the task is 'Description', the resolution says 'TestCase'", + assertThrows( + BadRequestException.class, + () -> + TableConstraintSuggestion.requireSameSuggestionType( + description, Map.of("suggestionType", "TestCase"))) + .getMessage()); + } + + @Test + void aResolutionCannotAddAKeyToATestCaseSuggestion() { + BadRequestException e = + assertThrows( + BadRequestException.class, + () -> + TableConstraintSuggestion.requireNoNewKeys( + task(proposal()), Map.of("comment", "x"), null)); + assertEquals(true, e.getMessage().startsWith("A test case suggestion carries only the keys")); + } + + @Test + void anApprovalsCommentNamesTheTestAndItsTableAndNeverTheNewValue() { + Task task = task(proposal()); + assertEquals( + Optional.of("Created test case " + NAME + " on table " + ORDERS), + TaskWorkflowHandler.resolutionComment(task, true, null, null)); + assertEquals( + Optional.of("Created test case " + NAME + " on table " + ORDERS), + TaskWorkflowHandler.resolutionComment(task, true, null, "something the approver typed")); + } + + @Test + void anApprovalsCommentSaysSoWhenTheTableHasTheTest() { + testExists = true; + assertEquals( + Optional.of("Test case already exists " + NAME + " on table " + ORDERS), + TaskWorkflowHandler.resolutionComment(task(proposal()), true, null, null)); + } + + @Test + void aRejectionLeavesNoComment() { + assertEquals( + Optional.empty(), + TaskWorkflowHandler.resolutionComment(task(proposal()), false, null, null)); + } + + @Test + void theTestToCreateIsTheProposalWithItsInspectionQueryAndWhereItComesFrom() { + TestCaseProposal proposal = proposal(); + CreateTestCase create = proposal.getTestCase(); + assertEquals("tableCustomSQLQuery", create.getTestDefinition()); + assertEquals(LINK, create.getEntityLink()); + assertEquals("SELECT k FROM t", proposal.getInspectionQuery()); + assertEquals(DIGEST, proposal.getGeneratedBy().getContentDigest()); + assertEquals(IDENTITY, proposal.getGeneratedBy().getIdentity()); + } + + private static String refusal(final Runnable filing) { + return assertThrows(BadRequestException.class, filing::run).getMessage(); + } + + private static List parameters(final String statement) { + return List.of( + new TestCaseParameterValue().withName("sqlExpression").withValue(statement), + new TestCaseParameterValue().withName("strategy").withValue("COUNT"), + new TestCaseParameterValue().withName("operator").withValue("<="), + new TestCaseParameterValue().withName("threshold").withValue("0")); + } + + private static TestCaseProposal proposal() { + return new TestCaseProposal() + .withTestCase( + new CreateTestCase() + .withName(NAME) + .withTestDefinition("tableCustomSQLQuery") + .withEntityLink(LINK) + .withParameterValues(new java.util.ArrayList<>(parameters(STATEMENT)))) + .withInspectionQuery("SELECT k FROM t") + .withGeneratedBy( + new TestCaseGeneratedBy() + .withIdentity(IDENTITY) + .withShape( + new EntityReference().withId(UUID.randomUUID()).withType("ontologyShape")) + .withConstraintId("c1") + .withPart("minCount") + .withClass( + new EntityReference().withId(UUID.randomUUID()).withType("ontologyConcept")) + .withReadBindings( + List.of( + new TestCaseGeneratedByBinding() + .withConceptId(UUID.randomUUID()) + .withAssetId(UUID.randomUUID()) + .withRevision(3L))) + .withContentDigest(DIGEST)); + } + + private static TestCaseProposal with(final java.util.function.Consumer change) { + TestCaseProposal proposal = proposal(); + change.accept(proposal); + return proposal; + } + + private Task task(final TestCaseProposal proposal) { + Map payload = new LinkedHashMap<>(); + payload.put("suggestionType", "TestCase"); + payload.put("fieldPath", "testCases"); + payload.put("suggestedValue", JsonUtils.pojoToJson(proposal)); + return new Task() + .withId(UUID.randomUUID()) + .withType(TaskEntityType.Suggestion) + .withAbout( + new EntityReference() + .withId(orders.getId()) + .withType(Entity.TABLE) + .withFullyQualifiedName(ORDERS)) + .withPayload(payload); + } +} diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..1d73a27d81e1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND (t0.`total` < 0 OR t0.`total` > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..1872950eb8dc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + LEFT JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`id` IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..808ce2a45354 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..e8ba12c522f7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..7c7d69698321 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..697bc219f126 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..068ea33528ad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + LEFT JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..8e7b1685b7a9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..52be2b6fcd02 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6f2c6387e28a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-class.sql new file mode 100644 index 000000000000..16eabdcfe8f8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + LEFT JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + AND t2.`sku` IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..ee5641bff7e4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..893f5946b728 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + LEFT JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..705f31232957 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`quantity` < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..a0b9ef55ac3d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`channel` NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..175572d640ce --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..79a6a85a0798 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..49196ce3ee90 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + LEFT JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..ff8d659ee01d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..6099ce177166 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..01056703deae --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/bigquery/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..1d73a27d81e1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND (t0.`total` < 0 OR t0.`total` > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..808ce2a45354 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..e8ba12c522f7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..7c7d69698321 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..697bc219f126 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..8e7b1685b7a9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..52be2b6fcd02 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6f2c6387e28a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..ee5641bff7e4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..705f31232957 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`quantity` < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..a0b9ef55ac3d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`channel` NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..175572d640ce --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..79a6a85a0798 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..ff8d659ee01d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..6099ce177166 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..01056703deae --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/clickhouse/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..1d73a27d81e1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND (t0.`total` < 0 OR t0.`total` > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..1872950eb8dc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + LEFT JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`id` IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..808ce2a45354 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..e8ba12c522f7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..7c7d69698321 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..697bc219f126 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..068ea33528ad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + LEFT JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..8e7b1685b7a9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..52be2b6fcd02 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6f2c6387e28a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-class.sql new file mode 100644 index 000000000000..16eabdcfe8f8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + LEFT JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + AND t2.`sku` IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..ee5641bff7e4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..893f5946b728 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + LEFT JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..705f31232957 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`quantity` < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..a0b9ef55ac3d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`channel` NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..175572d640ce --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..79a6a85a0798 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..49196ce3ee90 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + LEFT JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..ff8d659ee01d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..6099ce177166 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..01056703deae --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/mysql/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..0424efab4920 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND (t0.total < 0 OR t0.total > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..e8b526e25b83 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + LEFT JOIN shop.customers t1 ON t1.id = t0.customer_id + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.id IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..ca0de2e9e236 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS v0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..f6df07377880 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS v0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..a0a8702e4ad4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.tier NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..c5fd69b43c18 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1, t1.tier AS v0 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.tier IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..783fe4c0a7c9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1, t1.tier AS v0 + FROM shop.crm_customers t0 + LEFT JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-pattern.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-pattern.sql new file mode 100644 index 000000000000..af76a2ba991b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/compositeKey-accountTier-pattern.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND NOT (CAST(t1.tier AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](:|\\.|''|\\\\)*[^ ]{2,}$') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..3b59b222c3c6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.name NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..ee64c4d60a6a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.name AS v0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.name IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6e9bc87dd775 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.name AS v0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-pattern.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-pattern.sql new file mode 100644 index 000000000000..60c08e139675 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/filteredIdentity-personName-pattern.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND NOT (CAST(t0.name AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](:|\\.|''|\\\\)*[^ ]{2,}$') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-class.sql new file mode 100644 index 000000000000..ceab9398db9a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + LEFT JOIN shop.products t2 ON t2.sku = t1.product_sku + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL + AND t2.sku IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..13d702c9be7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS v0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..7cb768754e5f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS v0 + FROM shop.orders t0 + LEFT JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..d3ebc94092bb --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.quantity < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..741fa3a54ae8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.channel NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..c3bc8bfd4570 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.city NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..dbbfbf1c9562 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.city IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..e62692145e27 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + LEFT JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-pattern.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-pattern.sql new file mode 100644 index 000000000000..dd8a49db126a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/repeatedContribution-addressCity-pattern.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND NOT (CAST(t1.city AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](:|\\.|''|\\\\)*[^ ]{2,}$') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..e5e6417bd8b3 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..1651cc3a9726 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..134119552105 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-pattern.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-pattern.sql new file mode 100644 index 000000000000..a415b6e1626d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/postgres/unfilteredIdentity-customerEmail-pattern.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND NOT (CAST(t0.email AS text) COLLATE "C" ~ E'^[A-Z][a-z0-9]+[^\\n\\r](:|\\.|''|\\\\)*[^ ]{2,}$') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..0424efab4920 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND (t0.total < 0 OR t0.total > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..e8b526e25b83 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + LEFT JOIN shop.customers t1 ON t1.id = t0.customer_id + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.id IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..ca0de2e9e236 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS v0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..f6df07377880 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS v0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..a0a8702e4ad4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.tier NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..c5fd69b43c18 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1, t1.tier AS v0 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.tier IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..783fe4c0a7c9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1, t1.tier AS v0 + FROM shop.crm_customers t0 + LEFT JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..3b59b222c3c6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.name NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..ee64c4d60a6a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.name AS v0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.name IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6e9bc87dd775 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.name AS v0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-class.sql new file mode 100644 index 000000000000..ceab9398db9a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + LEFT JOIN shop.products t2 ON t2.sku = t1.product_sku + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL + AND t2.sku IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..13d702c9be7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS v0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..7cb768754e5f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS v0 + FROM shop.orders t0 + LEFT JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..d3ebc94092bb --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.quantity < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..741fa3a54ae8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.channel NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..c3bc8bfd4570 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.city NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..dbbfbf1c9562 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.city IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..e62692145e27 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + LEFT JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..e5e6417bd8b3 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..1651cc3a9726 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..134119552105 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/redshift/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..0a95cedfa6a2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."orders" t0 + WHERE t0."id" IS NOT NULL + AND (t0."total" < 0 OR t0."total" > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..1214f1bcd739 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."orders" t0 + LEFT JOIN "shop"."customers" t1 ON t1."id" = t0."customer_id" + WHERE t0."id" IS NOT NULL + AND t0."customer_id" IS NOT NULL + AND t1."id" IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..8d78e30cbf0c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t0."customer_id" AS v0 + FROM "shop"."orders" t0 + WHERE t0."id" IS NOT NULL + AND t0."customer_id" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..2d784e1d3711 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t0."customer_id" AS v0 + FROM "shop"."orders" t0 + WHERE t0."id" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..33784973dd20 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."tenant_id" AS k0, t0."customer_id" AS k1 + FROM "shop"."crm_customers" t0 + JOIN "shop"."crm_customer_profile" t1 ON t1."tenant" = t0."tenant_id" AND t1."customer" = t0."customer_id" + WHERE t0."tenant_id" IS NOT NULL + AND t0."customer_id" IS NOT NULL + AND t1."tier" NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..d921104b6824 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0."tenant_id" AS k0, t0."customer_id" AS k1, t1."tier" AS v0 + FROM "shop"."crm_customers" t0 + JOIN "shop"."crm_customer_profile" t1 ON t1."tenant" = t0."tenant_id" AND t1."customer" = t0."customer_id" + WHERE t0."tenant_id" IS NOT NULL + AND t0."customer_id" IS NOT NULL + AND t1."tier" IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..b673ef120e81 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0."tenant_id" AS k0, t0."customer_id" AS k1, t1."tier" AS v0 + FROM "shop"."crm_customers" t0 + LEFT JOIN "shop"."crm_customer_profile" t1 ON t1."tenant" = t0."tenant_id" AND t1."customer" = t0."customer_id" + WHERE t0."tenant_id" IS NOT NULL + AND t0."customer_id" IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..4c68226a8ef9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."parties" t0 + WHERE t0."id" IS NOT NULL + AND t0."kind" = 'person' + AND t0."name" NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..374bc85ecd26 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t0."name" AS v0 + FROM "shop"."parties" t0 + WHERE t0."id" IS NOT NULL + AND t0."kind" = 'person' + AND t0."name" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..15158e99d787 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t0."name" AS v0 + FROM "shop"."parties" t0 + WHERE t0."id" IS NOT NULL + AND t0."kind" = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-class.sql new file mode 100644 index 000000000000..ca421c084a7b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."orders" t0 + JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" + LEFT JOIN "shop"."products" t2 ON t2."sku" = t1."product_sku" + WHERE t0."id" IS NOT NULL + AND t1."product_sku" IS NOT NULL + AND t2."sku" IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..4f9b6d9f50cc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t1."product_sku" AS v0 + FROM "shop"."orders" t0 + JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t1."product_sku" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..a378cd7d7e3c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t1."product_sku" AS v0 + FROM "shop"."orders" t0 + LEFT JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" + WHERE t0."id" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..241bcb990638 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."orders" t0 + JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t1."quantity" < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..5c334b22eec4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."orders" t0 + WHERE t0."id" IS NOT NULL + AND t0."channel" NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..70192d7dc05e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."customers" t0 + JOIN "shop"."customer_addresses" t1 ON t1."customer_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t1."city" NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..aca3068ba3d6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t1."city" AS v0 + FROM "shop"."customers" t0 + JOIN "shop"."customer_addresses" t1 ON t1."customer_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t1."city" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..c5c3ae499ed2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t1."city" AS v0 + FROM "shop"."customers" t0 + LEFT JOIN "shop"."customer_addresses" t1 ON t1."customer_id" = t0."id" + WHERE t0."id" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..998436d538a7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."customers" t0 + WHERE t0."id" IS NOT NULL + AND t0."email" NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..724ca54fd8c0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t0."email" AS v0 + FROM "shop"."customers" t0 + WHERE t0."id" IS NOT NULL + AND t0."email" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..bf982a855cd2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/snowflake/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0."id" AS k0, t0."email" AS v0 + FROM "shop"."customers" t0 + WHERE t0."id" IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..1d73a27d81e1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND (t0.`total` < 0 OR t0.`total` > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..1872950eb8dc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + LEFT JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`id` IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..808ce2a45354 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..e8ba12c522f7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS v0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..7c7d69698321 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..697bc219f126 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND t1.`tier` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..068ea33528ad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1, t1.`tier` AS v0 + FROM `shop`.`crm_customers` t0 + LEFT JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..8e7b1685b7a9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..52be2b6fcd02 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`name` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6f2c6387e28a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`name` AS v0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-class.sql new file mode 100644 index 000000000000..16eabdcfe8f8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + LEFT JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + AND t2.`sku` IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..ee5641bff7e4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..893f5946b728 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS v0 + FROM `shop`.`orders` t0 + LEFT JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..705f31232957 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`quantity` < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..a0b9ef55ac3d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`channel` NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..175572d640ce --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..79a6a85a0798 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`city` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..49196ce3ee90 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`city` AS v0 + FROM `shop`.`customers` t0 + LEFT JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..ff8d659ee01d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..6099ce177166 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`email` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..01056703deae --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/spark/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`email` AS v0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..0424efab4920 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND (t0.total < 0 OR t0.total > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..e8b526e25b83 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + LEFT JOIN shop.customers t1 ON t1.id = t0.customer_id + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.id IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..ca0de2e9e236 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS v0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..f6df07377880 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS v0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..a0a8702e4ad4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.tier NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..c5fd69b43c18 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1, t1.tier AS v0 + FROM shop.crm_customers t0 + JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND t1.tier IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..783fe4c0a7c9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1, t1.tier AS v0 + FROM shop.crm_customers t0 + LEFT JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..3b59b222c3c6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.name NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..ee64c4d60a6a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.name AS v0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.name IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..6e9bc87dd775 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.name AS v0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-class.sql new file mode 100644 index 000000000000..ceab9398db9a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + LEFT JOIN shop.products t2 ON t2.sku = t1.product_sku + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL + AND t2.sku IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..13d702c9be7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS v0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..7cb768754e5f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS v0 + FROM shop.orders t0 + LEFT JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..d3ebc94092bb --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.quantity < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..741fa3a54ae8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.channel NOT IN ('web', 'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..c3bc8bfd4570 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.city NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..dbbfbf1c9562 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.city IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..e62692145e27 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t1.city AS v0 + FROM shop.customers t0 + LEFT JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..e5e6417bd8b3 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email NOT IN ('a', 'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..1651cc3a9726 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + AND t0.email IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..134119552105 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/trino/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.id AS k0, t0.email AS v0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-orderTotal-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-orderTotal-range.sql new file mode 100644 index 000000000000..b87f095c8a04 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-orderTotal-range.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL + AND (t0.[total] < 0 OR t0.[total] > 100.50) +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-class.sql new file mode 100644 index 000000000000..73882b6e7d84 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-class.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + LEFT JOIN [shop].[customers] t1 ON t1.[id] = t0.[customer_id] + WHERE t0.[id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL + AND t1.[id] IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-maxCount.sql new file mode 100644 index 000000000000..f0a84689a648 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[customer_id] AS v0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-minCount.sql new file mode 100644 index 000000000000..7a46e4b035b1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/columnRelation-placedBy-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[customer_id] AS v0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-in.sql new file mode 100644 index 000000000000..27d65332f916 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-in.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[tenant_id] AS k0, t0.[customer_id] AS k1 + FROM [shop].[crm_customers] t0 + JOIN [shop].[crm_customer_profile] t1 ON t1.[tenant] = t0.[tenant_id] AND t1.[customer] = t0.[customer_id] + WHERE t0.[tenant_id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL + AND t1.[tier] NOT IN (N'a', N'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-maxCount.sql new file mode 100644 index 000000000000..78f7bc2e3c41 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-maxCount.sql @@ -0,0 +1,14 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.[tenant_id] AS k0, t0.[customer_id] AS k1, t1.[tier] AS v0 + FROM [shop].[crm_customers] t0 + JOIN [shop].[crm_customer_profile] t1 ON t1.[tenant] = t0.[tenant_id] AND t1.[customer] = t0.[customer_id] + WHERE t0.[tenant_id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL + AND t1.[tier] IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-minCount.sql new file mode 100644 index 000000000000..5129f52ebf0f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/compositeKey-accountTier-minCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0, k.k1 + FROM ( + SELECT DISTINCT t0.[tenant_id] AS k0, t0.[customer_id] AS k1, t1.[tier] AS v0 + FROM [shop].[crm_customers] t0 + LEFT JOIN [shop].[crm_customer_profile] t1 ON t1.[tenant] = t0.[tenant_id] AND t1.[customer] = t0.[customer_id] + WHERE t0.[tenant_id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL + ) k + GROUP BY k.k0, k.k1 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-in.sql new file mode 100644 index 000000000000..624ff507bf51 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[parties] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'person' + AND t0.[name] NOT IN (N'a', N'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-maxCount.sql new file mode 100644 index 000000000000..9f07851c3248 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[name] AS v0 + FROM [shop].[parties] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'person' + AND t0.[name] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-minCount.sql new file mode 100644 index 000000000000..5eb1fbc91391 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/filteredIdentity-personName-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[name] AS v0 + FROM [shop].[parties] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'person' + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-class.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-class.sql new file mode 100644 index 000000000000..82c8e62d2327 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-class.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] + LEFT JOIN [shop].[products] t2 ON t2.[sku] = t1.[product_sku] + WHERE t0.[id] IS NOT NULL + AND t1.[product_sku] IS NOT NULL + AND t2.[sku] IS NULL +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-maxCount.sql new file mode 100644 index 000000000000..e8ffc7525f05 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[product_sku] AS v0 + FROM [shop].[orders] t0 + JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t1.[product_sku] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-minCount.sql new file mode 100644 index 000000000000..f1bb8d5d8c59 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-contains-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[product_sku] AS v0 + FROM [shop].[orders] t0 + LEFT JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-itemQuantity-range.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-itemQuantity-range.sql new file mode 100644 index 000000000000..d56f372abfd3 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-itemQuantity-range.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t1.[quantity] < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-orderChannel-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-orderChannel-in.sql new file mode 100644 index 000000000000..74e5327eb72e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/linkTable-orderChannel-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[channel] NOT IN (N'web', N'store') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-in.sql new file mode 100644 index 000000000000..3d8fd667b32f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-in.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[customers] t0 + JOIN [shop].[customer_addresses] t1 ON t1.[customer_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t1.[city] NOT IN (N'a', N'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-maxCount.sql new file mode 100644 index 000000000000..d07ae9cd8996 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-maxCount.sql @@ -0,0 +1,13 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[city] AS v0 + FROM [shop].[customers] t0 + JOIN [shop].[customer_addresses] t1 ON t1.[customer_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t1.[city] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-minCount.sql new file mode 100644 index 000000000000..4ccb13e53841 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/repeatedContribution-addressCity-minCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[city] AS v0 + FROM [shop].[customers] t0 + LEFT JOIN [shop].[customer_addresses] t1 ON t1.[customer_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 2 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-in.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-in.sql new file mode 100644 index 000000000000..890cbcf6696e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-in.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[customers] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[email] NOT IN (N'a', N'b') +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-maxCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-maxCount.sql new file mode 100644 index 000000000000..ed917185d238 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-maxCount.sql @@ -0,0 +1,12 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[email] AS v0 + FROM [shop].[customers] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[email] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING COUNT(*) > 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-minCount.sql b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-minCount.sql new file mode 100644 index 000000000000..53b4f6fab4f2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/shape-checks/tsql/unfilteredIdentity-customerEmail-minCount.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS violations +FROM ( + SELECT k.k0 + FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[email] AS v0 + FROM [shop].[customers] t0 + WHERE t0.[id] IS NOT NULL + ) k + GROUP BY k.k0 + HAVING SUM(CASE WHEN k.v0 IS NOT NULL THEN 1 ELSE 0 END) < 1 +) c diff --git a/openmetadata-service/src/test/resources/ontology/sql-value-cases.json b/openmetadata-service/src/test/resources/ontology/sql-value-cases.json new file mode 100644 index 000000000000..095929fefad9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/sql-value-cases.json @@ -0,0 +1,688 @@ +[ +{"id": "RFV-001", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-002", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-003", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-004", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-005", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-006", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O\\'Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-007", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-008", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O\\'Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-009", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-010", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "x' OR '1'='1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' OR ''1''=''1'"}, "failureImpact": "The text after the quote runs as SQL and the filter selects every row.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-011", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "x' OR '1'='1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' OR ''1''=''1'"}, "failureImpact": "The text after the quote runs as SQL and the filter selects every row.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-012", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "x' OR '1'='1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' OR ''1''=''1'"}, "failureImpact": "The text after the quote runs as SQL and the filter selects every row.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-013", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "x' OR '1'='1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' OR ''1''=''1'"}, "failureImpact": "The text after the quote runs as SQL and the filter selects every row.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-014", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "x' OR '1'='1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' OR ''1''=''1'"}, "failureImpact": "The text after the quote runs as SQL and the filter selects every row.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-015", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "x' OR '1'='1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x\\' OR \\'1\\'=\\'1'"}, "failureImpact": "The text after the quote runs as SQL and the filter selects every row.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-016", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "x' OR '1'='1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' OR ''1''=''1'"}, "failureImpact": "The text after the quote runs as SQL and the filter selects every row.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-017", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "x' OR '1'='1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x\\' OR \\'1\\'=\\'1'"}, "failureImpact": "The text after the quote runs as SQL and the filter selects every row.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-018", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "x' OR '1'='1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'x'' OR ''1''=''1'"}, "failureImpact": "The text after the quote runs as SQL and the filter selects every row.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-019", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "E'\\\\'"}, "failureImpact": "A lone backslash escapes the closing quote on backslash engines and the literal never ends.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-020", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'"}, "failureImpact": "A lone backslash escapes the closing quote on backslash engines and the literal never ends.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-021", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\'"}, "failureImpact": "A lone backslash escapes the closing quote on backslash engines and the literal never ends.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-022", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'"}, "failureImpact": "A lone backslash escapes the closing quote on backslash engines and the literal never ends.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-023", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'"}, "failureImpact": "A lone backslash escapes the closing quote on backslash engines and the literal never ends.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-024", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'"}, "failureImpact": "A lone backslash escapes the closing quote on backslash engines and the literal never ends.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-025", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'"}, "failureImpact": "A lone backslash escapes the closing quote on backslash engines and the literal never ends.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-026", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'"}, "failureImpact": "A lone backslash escapes the closing quote on backslash engines and the literal never ends.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-027", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'\\'"}, "failureImpact": "A lone backslash escapes the closing quote on backslash engines and the literal never ends.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-028", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "E'\\\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-029", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-030", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-031", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-032", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-033", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\\\' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-034", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-035", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\\\' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-036", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-037", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "abc\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "E'abc\\\\'"}, "failureImpact": "A trailing backslash escapes the closing quote on backslash engines.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-038", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "abc\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'abc\\\\'"}, "failureImpact": "A trailing backslash escapes the closing quote on backslash engines.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-039", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "abc\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'abc\\'"}, "failureImpact": "A trailing backslash escapes the closing quote on backslash engines.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-040", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "abc\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'abc\\\\'"}, "failureImpact": "A trailing backslash escapes the closing quote on backslash engines.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-041", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "abc\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'abc\\\\'"}, "failureImpact": "A trailing backslash escapes the closing quote on backslash engines.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-042", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "abc\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'abc\\\\'"}, "failureImpact": "A trailing backslash escapes the closing quote on backslash engines.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-043", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "abc\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'abc\\\\'"}, "failureImpact": "A trailing backslash escapes the closing quote on backslash engines.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-044", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "abc\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'abc\\\\'"}, "failureImpact": "A trailing backslash escapes the closing quote on backslash engines.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-045", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "abc\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'abc\\'"}, "failureImpact": "A trailing backslash escapes the closing quote on backslash engines.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-046", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "'; DROP TABLE orders; --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'''; DROP TABLE orders; --'"}, "failureImpact": "A statement separator after a broken quote appends a second statement.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-047", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "'; DROP TABLE orders; --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'''; DROP TABLE orders; --'"}, "failureImpact": "A statement separator after a broken quote appends a second statement.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-048", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "'; DROP TABLE orders; --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'''; DROP TABLE orders; --'"}, "failureImpact": "A statement separator after a broken quote appends a second statement.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-049", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "'; DROP TABLE orders; --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'''; DROP TABLE orders; --'"}, "failureImpact": "A statement separator after a broken quote appends a second statement.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-050", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "'; DROP TABLE orders; --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'''; DROP TABLE orders; --'"}, "failureImpact": "A statement separator after a broken quote appends a second statement.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-051", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "'; DROP TABLE orders; --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\'; DROP TABLE orders; --'"}, "failureImpact": "A statement separator after a broken quote appends a second statement.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-052", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "'; DROP TABLE orders; --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'''; DROP TABLE orders; --'"}, "failureImpact": "A statement separator after a broken quote appends a second statement.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-053", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "'; DROP TABLE orders; --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\'; DROP TABLE orders; --'"}, "failureImpact": "A statement separator after a broken quote appends a second statement.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-054", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "'; DROP TABLE orders; --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'''; DROP TABLE orders; --'"}, "failureImpact": "A statement separator after a broken quote appends a second statement.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-055", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "x' /* ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' /* '"}, "failureImpact": "An unclosed block comment after a broken quote swallows the rest of the statement.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-056", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "x' /* ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' /* '"}, "failureImpact": "An unclosed block comment after a broken quote swallows the rest of the statement.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-057", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "x' /* ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' /* '"}, "failureImpact": "An unclosed block comment after a broken quote swallows the rest of the statement.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-058", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "x' /* ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' /* '"}, "failureImpact": "An unclosed block comment after a broken quote swallows the rest of the statement.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-059", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "x' /* ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' /* '"}, "failureImpact": "An unclosed block comment after a broken quote swallows the rest of the statement.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-060", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "x' /* ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x\\' /* '"}, "failureImpact": "An unclosed block comment after a broken quote swallows the rest of the statement.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-061", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "x' /* ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' /* '"}, "failureImpact": "An unclosed block comment after a broken quote swallows the rest of the statement.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-062", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "x' /* ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x\\' /* '"}, "failureImpact": "An unclosed block comment after a broken quote swallows the rest of the statement.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-063", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "x' /* ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'x'' /* '"}, "failureImpact": "An unclosed block comment after a broken quote swallows the rest of the statement.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-064", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "x' # ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' # '"}, "failureImpact": "MySQL and ClickHouse read # as a line comment after a broken quote.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-065", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "x' # ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' # '"}, "failureImpact": "MySQL and ClickHouse read # as a line comment after a broken quote.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-066", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "x' # ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' # '"}, "failureImpact": "MySQL and ClickHouse read # as a line comment after a broken quote.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-067", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "x' # ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' # '"}, "failureImpact": "MySQL and ClickHouse read # as a line comment after a broken quote.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-068", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "x' # ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' # '"}, "failureImpact": "MySQL and ClickHouse read # as a line comment after a broken quote.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-069", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "x' # ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x\\' # '"}, "failureImpact": "MySQL and ClickHouse read # as a line comment after a broken quote.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-070", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "x' # ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x'' # '"}, "failureImpact": "MySQL and ClickHouse read # as a line comment after a broken quote.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-071", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "x' # ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'x\\' # '"}, "failureImpact": "MySQL and ClickHouse read # as a line comment after a broken quote.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-072", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "x' # ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'x'' # '"}, "failureImpact": "MySQL and ClickHouse read # as a line comment after a broken quote.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-073", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-074", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-075", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-076", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-077", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-078", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-079", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-080", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-081", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-082", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": ":p0", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\:p0'"}, "failureImpact": "A value that looks like the runner's own placeholder is bound or rejected instead of compared as text.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-083", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": ":p0", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\:p0'"}, "failureImpact": "A value that looks like the runner's own placeholder is bound or rejected instead of compared as text.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-084", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": ":p0", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\:p0'"}, "failureImpact": "A value that looks like the runner's own placeholder is bound or rejected instead of compared as text.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-085", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": ":p0", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\:p0'"}, "failureImpact": "A value that looks like the runner's own placeholder is bound or rejected instead of compared as text.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-086", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": ":p0", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\:p0'"}, "failureImpact": "A value that looks like the runner's own placeholder is bound or rejected instead of compared as text.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-087", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": ":p0", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\:p0'"}, "failureImpact": "A value that looks like the runner's own placeholder is bound or rejected instead of compared as text.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-088", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": ":p0", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\:p0'"}, "failureImpact": "A value that looks like the runner's own placeholder is bound or rejected instead of compared as text.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-089", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": ":p0", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\:p0'"}, "failureImpact": "A value that looks like the runner's own placeholder is bound or rejected instead of compared as text.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-090", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": ":p0", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'\\:p0'"}, "failureImpact": "A value that looks like the runner's own placeholder is bound or rejected instead of compared as text.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-091", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "10:30:00", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'10\\:30\\:00'"}, "failureImpact": "A time written as text must keep its colons after the text() pass.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-092", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "10:30:00", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'10\\:30\\:00'"}, "failureImpact": "A time written as text must keep its colons after the text() pass.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-093", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "10:30:00", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'10\\:30\\:00'"}, "failureImpact": "A time written as text must keep its colons after the text() pass.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-094", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "10:30:00", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'10\\:30\\:00'"}, "failureImpact": "A time written as text must keep its colons after the text() pass.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-095", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "10:30:00", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'10\\:30\\:00'"}, "failureImpact": "A time written as text must keep its colons after the text() pass.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-096", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "10:30:00", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'10\\:30\\:00'"}, "failureImpact": "A time written as text must keep its colons after the text() pass.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-097", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "10:30:00", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'10\\:30\\:00'"}, "failureImpact": "A time written as text must keep its colons after the text() pass.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-098", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "10:30:00", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'10\\:30\\:00'"}, "failureImpact": "A time written as text must keep its colons after the text() pass.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-099", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "10:30:00", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'10\\:30\\:00'"}, "failureImpact": "A time written as text must keep its colons after the text() pass.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-100", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'50%_off'"}, "failureImpact": "In an equality the percent and underscore are plain text and must not be escaped or doubled.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-101", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'50%_off'"}, "failureImpact": "In an equality the percent and underscore are plain text and must not be escaped or doubled.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-102", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'50%_off'"}, "failureImpact": "In an equality the percent and underscore are plain text and must not be escaped or doubled.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-103", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'50%_off'"}, "failureImpact": "In an equality the percent and underscore are plain text and must not be escaped or doubled.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-104", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'50%_off'"}, "failureImpact": "In an equality the percent and underscore are plain text and must not be escaped or doubled.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-105", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'50%_off'"}, "failureImpact": "In an equality the percent and underscore are plain text and must not be escaped or doubled.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-106", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'50%_off'"}, "failureImpact": "In an equality the percent and underscore are plain text and must not be escaped or doubled.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-107", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'50%_off'"}, "failureImpact": "In an equality the percent and underscore are plain text and must not be escaped or doubled.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-108", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'50%_off'"}, "failureImpact": "In an equality the percent and underscore are plain text and must not be escaped or doubled.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-109", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "%(p0)s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%(p0)s'"}, "failureImpact": "A pyformat marker inside a literal must reach the engine unchanged.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-110", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "%(p0)s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%(p0)s'"}, "failureImpact": "A pyformat marker inside a literal must reach the engine unchanged.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-111", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "%(p0)s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%(p0)s'"}, "failureImpact": "A pyformat marker inside a literal must reach the engine unchanged.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-112", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "%(p0)s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%(p0)s'"}, "failureImpact": "A pyformat marker inside a literal must reach the engine unchanged.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-113", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "%(p0)s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%(p0)s'"}, "failureImpact": "A pyformat marker inside a literal must reach the engine unchanged.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-114", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "%(p0)s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%(p0)s'"}, "failureImpact": "A pyformat marker inside a literal must reach the engine unchanged.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-115", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "%(p0)s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%(p0)s'"}, "failureImpact": "A pyformat marker inside a literal must reach the engine unchanged.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-116", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "%(p0)s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%(p0)s'"}, "failureImpact": "A pyformat marker inside a literal must reach the engine unchanged.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-117", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "%(p0)s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'%(p0)s'"}, "failureImpact": "A pyformat marker inside a literal must reach the engine unchanged.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-118", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a ? b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a ? b'"}, "failureImpact": "A qmark marker inside a literal must reach the engine unchanged.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-119", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a ? b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a ? b'"}, "failureImpact": "A qmark marker inside a literal must reach the engine unchanged.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-120", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a ? b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a ? b'"}, "failureImpact": "A qmark marker inside a literal must reach the engine unchanged.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-121", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a ? b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a ? b'"}, "failureImpact": "A qmark marker inside a literal must reach the engine unchanged.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-122", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a ? b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a ? b'"}, "failureImpact": "A qmark marker inside a literal must reach the engine unchanged.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-123", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a ? b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a ? b'"}, "failureImpact": "A qmark marker inside a literal must reach the engine unchanged.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-124", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a ? b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a ? b'"}, "failureImpact": "A qmark marker inside a literal must reach the engine unchanged.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-125", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a ? b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a ? b'"}, "failureImpact": "A qmark marker inside a literal must reach the engine unchanged.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-126", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a ? b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'a ? b'"}, "failureImpact": "A qmark marker inside a literal must reach the engine unchanged.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-127", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "$$x$$", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'$$x$$'"}, "failureImpact": "Dollar quoting on Postgres and Snowflake is inert inside an ordinary literal.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-128", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "$$x$$", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'$$x$$'"}, "failureImpact": "Dollar quoting on Postgres and Snowflake is inert inside an ordinary literal.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-129", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "$$x$$", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'$$x$$'"}, "failureImpact": "Dollar quoting on Postgres and Snowflake is inert inside an ordinary literal.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-130", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "$$x$$", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'$$x$$'"}, "failureImpact": "Dollar quoting on Postgres and Snowflake is inert inside an ordinary literal.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-131", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "$$x$$", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'$$x$$'"}, "failureImpact": "Dollar quoting on Postgres and Snowflake is inert inside an ordinary literal.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-132", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "$$x$$", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'$$x$$'"}, "failureImpact": "Dollar quoting on Postgres and Snowflake is inert inside an ordinary literal.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-133", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "$$x$$", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'$$x$$'"}, "failureImpact": "Dollar quoting on Postgres and Snowflake is inert inside an ordinary literal.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-134", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "$$x$$", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'$$x$$'"}, "failureImpact": "Dollar quoting on Postgres and Snowflake is inert inside an ordinary literal.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-135", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "$$x$$", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'$$x$$'"}, "failureImpact": "Dollar quoting on Postgres and Snowflake is inert inside an ordinary literal.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-136", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "\\x27 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "E'\\\\x27 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\x27 as a quote when the backslash is not doubled.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-137", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "\\x27 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\x27 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\x27 as a quote when the backslash is not doubled.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-138", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "\\x27 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\x27 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\x27 as a quote when the backslash is not doubled.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-139", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "\\x27 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\x27 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\x27 as a quote when the backslash is not doubled.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-140", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "\\x27 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\x27 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\x27 as a quote when the backslash is not doubled.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-141", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "\\x27 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\x27 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\x27 as a quote when the backslash is not doubled.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-142", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "\\x27 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\x27 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\x27 as a quote when the backslash is not doubled.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-143", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "\\x27 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\x27 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\x27 as a quote when the backslash is not doubled.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-144", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "\\x27 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'\\x27 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\x27 as a quote when the backslash is not doubled.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-145", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "\\u0027 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "E'\\\\u0027 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\u0027 as a quote when the backslash is not doubled.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-146", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "\\u0027 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\u0027 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\u0027 as a quote when the backslash is not doubled.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-147", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "\\u0027 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\u0027 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\u0027 as a quote when the backslash is not doubled.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-148", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "\\u0027 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\u0027 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\u0027 as a quote when the backslash is not doubled.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-149", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "\\u0027 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\u0027 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\u0027 as a quote when the backslash is not doubled.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-150", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "\\u0027 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\u0027 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\u0027 as a quote when the backslash is not doubled.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-151", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "\\u0027 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\u0027 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\u0027 as a quote when the backslash is not doubled.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-152", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "\\u0027 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\u0027 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\u0027 as a quote when the backslash is not doubled.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-153", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "\\u0027 OR 1=1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'\\u0027 OR 1=1'"}, "failureImpact": "BigQuery and Snowflake read \\u0027 as a quote when the backslash is not doubled.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-154", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-155", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-156", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-157", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-158", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-159", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-160", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-161", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-162", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-163", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "it''s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'it''''s'"}, "failureImpact": "Text that is already doubled must be doubled again, not passed through.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-164", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "it''s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'it''''s'"}, "failureImpact": "Text that is already doubled must be doubled again, not passed through.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-165", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "it''s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'it''''s'"}, "failureImpact": "Text that is already doubled must be doubled again, not passed through.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-166", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "it''s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'it''''s'"}, "failureImpact": "Text that is already doubled must be doubled again, not passed through.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-167", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "it''s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'it''''s'"}, "failureImpact": "Text that is already doubled must be doubled again, not passed through.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-168", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "it''s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'it\\'\\'s'"}, "failureImpact": "Text that is already doubled must be doubled again, not passed through.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-169", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "it''s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'it''''s'"}, "failureImpact": "Text that is already doubled must be doubled again, not passed through.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-170", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "it''s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'it\\'\\'s'"}, "failureImpact": "Text that is already doubled must be doubled again, not passed through.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-171", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "it''s", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'it''''s'"}, "failureImpact": "Text that is already doubled must be doubled again, not passed through.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-172", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "caf\u00e9 \u65e5\u672c", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'caf\u00e9 \u65e5\u672c'"}, "failureImpact": "Non-ASCII text must keep its characters; T-SQL needs the N prefix or the code page replaces them.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-173", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "caf\u00e9 \u65e5\u672c", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'caf\u00e9 \u65e5\u672c'"}, "failureImpact": "Non-ASCII text must keep its characters; T-SQL needs the N prefix or the code page replaces them.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-174", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "caf\u00e9 \u65e5\u672c", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'caf\u00e9 \u65e5\u672c'"}, "failureImpact": "Non-ASCII text must keep its characters; T-SQL needs the N prefix or the code page replaces them.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-175", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "caf\u00e9 \u65e5\u672c", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'caf\u00e9 \u65e5\u672c'"}, "failureImpact": "Non-ASCII text must keep its characters; T-SQL needs the N prefix or the code page replaces them.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-176", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "caf\u00e9 \u65e5\u672c", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'caf\u00e9 \u65e5\u672c'"}, "failureImpact": "Non-ASCII text must keep its characters; T-SQL needs the N prefix or the code page replaces them.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-177", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "caf\u00e9 \u65e5\u672c", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'caf\u00e9 \u65e5\u672c'"}, "failureImpact": "Non-ASCII text must keep its characters; T-SQL needs the N prefix or the code page replaces them.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-178", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "caf\u00e9 \u65e5\u672c", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'caf\u00e9 \u65e5\u672c'"}, "failureImpact": "Non-ASCII text must keep its characters; T-SQL needs the N prefix or the code page replaces them.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-179", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "caf\u00e9 \u65e5\u672c", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'caf\u00e9 \u65e5\u672c'"}, "failureImpact": "Non-ASCII text must keep its characters; T-SQL needs the N prefix or the code page replaces them.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-180", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "caf\u00e9 \u65e5\u672c", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'caf\u00e9 \u65e5\u672c'"}, "failureImpact": "Non-ASCII text must keep its characters; T-SQL needs the N prefix or the code page replaces them.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-181", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a\u2028b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2028b'"}, "failureImpact": "A Unicode line separator is not a control character and stays inside the literal.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-182", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a\u2028b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2028b'"}, "failureImpact": "A Unicode line separator is not a control character and stays inside the literal.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-183", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a\u2028b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2028b'"}, "failureImpact": "A Unicode line separator is not a control character and stays inside the literal.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-184", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a\u2028b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2028b'"}, "failureImpact": "A Unicode line separator is not a control character and stays inside the literal.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-185", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a\u2028b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2028b'"}, "failureImpact": "A Unicode line separator is not a control character and stays inside the literal.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-186", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a\u2028b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2028b'"}, "failureImpact": "A Unicode line separator is not a control character and stays inside the literal.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-187", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a\u2028b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2028b'"}, "failureImpact": "A Unicode line separator is not a control character and stays inside the literal.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-188", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a\u2028b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2028b'"}, "failureImpact": "A Unicode line separator is not a control character and stays inside the literal.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-189", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a\u2028b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'a\u2028b'"}, "failureImpact": "A Unicode line separator is not a control character and stays inside the literal.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-190", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''"}, "failureImpact": "The longest accepted value doubles in length when escaped and must still render whole.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-191", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''"}, "failureImpact": "The longest accepted value doubles in length when escaped and must still render whole.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-192", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\'\\''"}, "failureImpact": "The longest accepted value doubles in length when escaped and must still render whole.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-193", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''"}, "failureImpact": "The longest accepted value doubles in length when escaped and must still render whole.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-194", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "a\nb", "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["control character", "status"]}, "failureImpact": "A newline ends a line comment and, on T-SQL, a backslash before it continues the string.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-195", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "a\\\nb", "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["control character", "status"]}, "failureImpact": "On T-SQL a backslash followed by a newline is removed from the string, changing the value.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-196", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "a\tb", "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["control character", "status"]}, "failureImpact": "A control character reaches the statement text and the logs.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-197", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "a\u0085b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["control character", "status"]}, "failureImpact": "A C1 control character reaches the statement text.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-198", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "a\u0000b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["at most 1024 characters"]}, "failureImpact": "A NUL truncates the statement in C drivers.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-199", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["at most 1024 characters"]}, "failureImpact": "An over-long value makes statements large and slow to parse.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-200", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "1 OR 1=1", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "A number column written unquoted runs OR 1=1; written quoted, MySQL reads it as 1.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-201", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "1; DROP TABLE orders", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "A statement separator reaches a number position.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-202", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": " 1", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "MySQL compares ' 1' equal to 1, so loose parsing changes which rows match.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-203", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "+1", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "A sign the canonical form does not have makes the rendered text depend on input spelling.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-204", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "1e3", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "MySQL compares '1e3' equal to 1000, so the filter matches rows the editor did not name.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-205", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "0x1F", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "Hex text is a number on some engines and a string on others.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-206", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "1_000", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "Digit separators parse on some engines and not others.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-207", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "\uff11\uff12", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "Java parses full-width digits as 12, and writing them into SQL breaks the statement or compares wrongly.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-208", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "007", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "Leading zeros hide that the value is really text such as a postcode.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-209", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "2147483648", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "A value past the column's range wraps or errors differently per engine.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-210", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "9223372036854775808", "columnType": "BIGINT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "id"]}, "failureImpact": "MySQL CAST wraps this to -9223372036854775808.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["id"], "operator": "equals"}, +{"id": "RFV-211", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": 1.5, "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "A fraction compared with an integer column silently truncates on some engines.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-212", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": true, "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "A boolean in a number position renders as TRUE or 1 depending on engine.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-213", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "An empty number renders as nothing and breaks the statement.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-214", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "NaN", "columnType": "DECIMAL", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "amount"]}, "failureImpact": "NaN written into SQL is a column reference or a special value.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-215", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "Infinity", "columnType": "DECIMAL", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "amount"]}, "failureImpact": "Infinity written into SQL is a column reference.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-216", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "1e400", "columnType": "DECIMAL", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "amount"]}, "failureImpact": "An exponent beyond double range becomes Infinity when parsed as a double.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-217", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": ".5", "columnType": "DECIMAL", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "amount"]}, "failureImpact": "Non-canonical decimals render differently from what was stored.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-218", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "12.30 OR 1=1", "columnType": "DECIMAL", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "amount"]}, "failureImpact": "Text after a valid number runs as SQL.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-219", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "yes", "columnType": "BOOLEAN", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "active"]}, "failureImpact": "Postgres reads 'yes', 'on' and '1' as true, so text booleans match rows the editor did not name.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-220", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "true", "columnType": "BOOLEAN", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "active"]}, "failureImpact": "A boolean sent as text is ambiguous across engines; only a JSON boolean is accepted.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-221", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": 1, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "active"]}, "failureImpact": "A number in a boolean position renders differently per engine.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-222", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "TRUE OR 1=1", "columnType": "BOOLEAN", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "active"]}, "failureImpact": "Text after a boolean runs as SQL.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-223", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "2024-02-30", "columnType": "DATE", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_on"]}, "failureImpact": "An impossible date errors on Postgres and MySQL at run time instead of at save.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-224", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "2023-02-29", "columnType": "DATE", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_on"]}, "failureImpact": "A non-leap-year 29 February is not a date.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-225", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "2024-1-5", "columnType": "DATE", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_on"]}, "failureImpact": "A non-ISO date is read differently under different date-style settings.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-226", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "epoch", "columnType": "DATE", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_on"]}, "failureImpact": "Postgres reads 'epoch' as 1970-01-01, a value the editor did not write.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-227", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "infinity", "columnType": "DATE", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_on"]}, "failureImpact": "Postgres reads 'infinity' as a date past every row.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-228", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "today", "columnType": "DATE", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_on"]}, "failureImpact": "A relative date changes meaning every day the job runs.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-229", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "0000-00-00", "columnType": "DATE", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_on"]}, "failureImpact": "MySQL's zero date is not a date on any other engine.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-230", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "2024-02-29T00:00:00", "columnType": "DATE", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_on"]}, "failureImpact": "A timestamp in a date position is truncated or rejected depending on engine.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-231", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "2024-02-29' OR '1'='1", "columnType": "DATE", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_on"]}, "failureImpact": "Text after a valid date runs as SQL.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-232", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": 20240229, "columnType": "DATE", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_on"]}, "failureImpact": "A number in a date position is read as days or as YYYYMMDD depending on engine.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-233", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "2024-01-01 25:00:00", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_at"]}, "failureImpact": "An impossible time errors at run time instead of at save.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-234", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "allballs", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_at"]}, "failureImpact": "Postgres special time words are not timestamps the editor wrote.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-235", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "2024-01-01T10:30:00Z", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "created_at"]}, "failureImpact": "An offset on a column without a time zone is applied or dropped depending on engine.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-236", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "{}", "columnType": "JSON", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not support column type", "payload"]}, "failureImpact": "A filter on a JSON column has no single literal form across engines.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["payload"], "operator": "equals"}, +{"id": "RFV-237", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "a", "columnType": "ARRAY", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not support column type", "tags"]}, "failureImpact": "A filter on an array column has no single literal form across engines.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["tags"], "operator": "equals"}, +{"id": "RFV-238", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "00", "columnType": "BINARY", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not support column type", "blob"]}, "failureImpact": "A filter on a binary column has no single literal form across engines.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["blob"], "operator": "equals"}, +{"id": "RFV-239", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": [1, "2 OR 1=1"], "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["does not parse as", "qty"]}, "failureImpact": "One bad member of an in list must refuse the whole list.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "in"}, +{"id": "RFV-240", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100], "columnType": "INT", "expectedOutcome": {"kind": "refusedAtSave", "status": 400, "messageContains": ["list of 1 to 100"]}, "failureImpact": "An unbounded in list builds a statement of any size.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "in"}, +{"id": "RFV-241", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": ["OPEN", "O'Brien", "x' OR '1'='1", "a :b"], "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O''Brien', 'x'' OR ''1''=''1', 'a \\:b')"}, "failureImpact": "Each member of an in list needs the same escaping as a single value.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "in"}, +{"id": "RFV-242", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": ["OPEN", "O'Brien", "x' OR '1'='1", "a :b"], "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O''Brien', 'x'' OR ''1''=''1', 'a \\:b')"}, "failureImpact": "Each member of an in list needs the same escaping as a single value.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "in"}, +{"id": "RFV-243", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": ["OPEN", "O'Brien", "x' OR '1'='1", "a :b"], "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O''Brien', 'x'' OR ''1''=''1', 'a \\:b')"}, "failureImpact": "Each member of an in list needs the same escaping as a single value.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "in"}, +{"id": "RFV-244", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": ["OPEN", "O'Brien", "x' OR '1'='1", "a :b"], "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O''Brien', 'x'' OR ''1''=''1', 'a \\:b')"}, "failureImpact": "Each member of an in list needs the same escaping as a single value.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "in"}, +{"id": "RFV-245", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": ["OPEN", "O'Brien", "x' OR '1'='1", "a :b"], "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O''Brien', 'x'' OR ''1''=''1', 'a \\:b')"}, "failureImpact": "Each member of an in list needs the same escaping as a single value.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "in"}, +{"id": "RFV-246", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": ["OPEN", "O'Brien", "x' OR '1'='1", "a :b"], "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O\\'Brien', 'x\\' OR \\'1\\'=\\'1', 'a \\:b')"}, "failureImpact": "Each member of an in list needs the same escaping as a single value.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "in"}, +{"id": "RFV-247", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": ["OPEN", "O'Brien", "x' OR '1'='1", "a :b"], "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O''Brien', 'x'' OR ''1''=''1', 'a \\:b')"}, "failureImpact": "Each member of an in list needs the same escaping as a single value.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "in"}, +{"id": "RFV-248", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": ["OPEN", "O'Brien", "x' OR '1'='1", "a :b"], "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O\\'Brien', 'x\\' OR \\'1\\'=\\'1', 'a \\:b')"}, "failureImpact": "Each member of an in list needs the same escaping as a single value.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "in"}, +{"id": "RFV-249", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": ["OPEN", "O'Brien", "x' OR '1'='1", "a :b"], "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "(N'OPEN', N'O''Brien', N'x'' OR ''1''=''1', N'a \\:b')"}, "failureImpact": "Each member of an in list needs the same escaping as a single value.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "in"}, +{"id": "RFV-250", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": 42, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-251", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": 42, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-252", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": 42, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-253", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": 42, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-254", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": 42, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-255", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": 42, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-256", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": 42, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-257", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": 42, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-258", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": 42, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-259", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "42", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-260", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "42", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-261", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "42", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-262", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "42", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-263", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "42", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-264", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "42", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-265", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "42", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-266", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "42", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-267", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "42", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "42"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-268", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": -1, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "-1"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-269", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": -1, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "-1"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-270", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": -1, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "-1"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-271", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": -1, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "-1"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-272", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": -1, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "-1"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-273", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": -1, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "-1"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-274", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": -1, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "-1"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-275", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": -1, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "-1"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-276", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": -1, "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "-1"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-277", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "-0", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-278", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "-0", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-279", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "-0", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-280", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "-0", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-281", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "-0", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-282", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "-0", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-283", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "-0", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-284", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "-0", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-285", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "-0", "columnType": "INT", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["qty"], "operator": "equals"}, +{"id": "RFV-286", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "0.10", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0.10"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-287", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "0.10", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0.10"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-288", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "0.10", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0.10"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-289", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "0.10", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0.10"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-290", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "0.10", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0.10"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-291", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "0.10", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0.10"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-292", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "0.10", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0.10"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-293", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "0.10", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0.10"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-294", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "0.10", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0.10"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-295", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": 100.0, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "100.0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-296", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": 100.0, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "100.0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-297", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": 100.0, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "100.0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-298", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": 100.0, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "100.0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-299", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": 100.0, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "100.0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-300", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": 100.0, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "100.0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-301", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": 100.0, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "100.0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-302", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": 100.0, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "100.0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-303", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": 100.0, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "100.0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-304", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "-12.345", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "-12.345"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-305", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "-12.345", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "-12.345"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-306", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "-12.345", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "-12.345"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-307", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "-12.345", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "-12.345"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-308", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "-12.345", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "-12.345"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-309", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "-12.345", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "-12.345"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-310", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "-12.345", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "-12.345"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-311", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "-12.345", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "-12.345"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-312", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "-12.345", "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "-12.345"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["amount"], "operator": "equals"}, +{"id": "RFV-313", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": true, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "TRUE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-314", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": true, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "TRUE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-315", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": true, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "TRUE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-316", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": true, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "TRUE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-317", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": true, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "TRUE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-318", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": true, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "TRUE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-319", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": true, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "TRUE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-320", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": true, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "TRUE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-321", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": true, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "1"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-322", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": false, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "FALSE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-323", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": false, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "FALSE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-324", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": false, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "FALSE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-325", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": false, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "FALSE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-326", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": false, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "FALSE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-327", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": false, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "FALSE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-328", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": false, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "FALSE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-329", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": false, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "FALSE"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-330", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": false, "columnType": "BOOLEAN", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["active"], "operator": "equals"}, +{"id": "RFV-331", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "2024-02-29", "columnType": "DATE", "expectedOutcome": {"kind": "rendered", "text": "DATE '2024-02-29'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-332", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "2024-02-29", "columnType": "DATE", "expectedOutcome": {"kind": "rendered", "text": "DATE '2024-02-29'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-333", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "2024-02-29", "columnType": "DATE", "expectedOutcome": {"kind": "rendered", "text": "DATE '2024-02-29'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-334", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "2024-02-29", "columnType": "DATE", "expectedOutcome": {"kind": "rendered", "text": "DATE '2024-02-29'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-335", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "2024-02-29", "columnType": "DATE", "expectedOutcome": {"kind": "rendered", "text": "DATE '2024-02-29'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-336", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "2024-02-29", "columnType": "DATE", "expectedOutcome": {"kind": "rendered", "text": "DATE '2024-02-29'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-337", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "2024-02-29", "columnType": "DATE", "expectedOutcome": {"kind": "rendered", "text": "DATE '2024-02-29'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-338", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "2024-02-29", "columnType": "DATE", "expectedOutcome": {"kind": "rendered", "text": "DATE '2024-02-29'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-339", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "2024-02-29", "columnType": "DATE", "expectedOutcome": {"kind": "rendered", "text": "CAST(N'2024-02-29' AS date)"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["created_on"], "operator": "equals"}, +{"id": "RFV-340", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "2024-01-01T10:30:00", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-341", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "2024-01-01T10:30:00", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-342", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "2024-01-01T10:30:00", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-343", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "2024-01-01T10:30:00", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-344", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "2024-01-01T10:30:00", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-345", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "2024-01-01T10:30:00", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-346", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "2024-01-01T10:30:00", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-347", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "2024-01-01T10:30:00", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-348", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "2024-01-01T10:30:00", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "CAST(N'2024-01-01T10\\:30\\:00' AS datetime2)"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-349", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "2024-01-01 10:30:00.123456", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00.123456'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-350", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "2024-01-01 10:30:00.123456", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00.123456'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-351", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "2024-01-01 10:30:00.123456", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00.123456'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-352", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "2024-01-01 10:30:00.123456", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00.123456'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-353", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "2024-01-01 10:30:00.123456", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00.123456'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-354", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "2024-01-01 10:30:00.123456", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00.123456'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-355", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "2024-01-01 10:30:00.123456", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00.123456'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-356", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "2024-01-01 10:30:00.123456", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "TIMESTAMP '2024-01-01 10\\:30\\:00.123456'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-357", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "2024-01-01 10:30:00.123456", "columnType": "TIMESTAMP", "expectedOutcome": {"kind": "rendered", "text": "CAST(N'2024-01-01T10\\:30\\:00.123456' AS datetime2)"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["created_at"], "operator": "equals"}, +{"id": "RFV-358", "path": "rowFilterValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": 42, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'42'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-359", "path": "rowFilterValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": 42, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'42'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-360", "path": "rowFilterValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": 42, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'42'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-361", "path": "rowFilterValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": 42, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'42'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-362", "path": "rowFilterValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": 42, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'42'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-363", "path": "rowFilterValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": 42, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'42'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-364", "path": "rowFilterValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": 42, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'42'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-365", "path": "rowFilterValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": 42, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'42'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-366", "path": "rowFilterValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": 42, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'42'"}, "failureImpact": "A typed value must render in the one canonical form the column type takes on that engine.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"], "operator": "equals"}, +{"id": "RFV-367", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "abc", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["does not parse as", "qty"]}, "failureImpact": "A value stored before type checks existed, or before re-ingestion changed the column type, is written unquoted into a number position.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals", "note": "Stored filter is {column:[qty], operator:equals, value:'abc'}; the column was VARCHAR when it was saved and is INT now."}, +{"id": "KEY-001", "path": "keyValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["customer_no"]}, +{"id": "KEY-002", "path": "keyValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["customer_no"]}, +{"id": "KEY-003", "path": "keyValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["customer_no"]}, +{"id": "KEY-004", "path": "keyValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["customer_no"]}, +{"id": "KEY-005", "path": "keyValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["customer_no"]}, +{"id": "KEY-006", "path": "keyValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O\\'Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["customer_no"]}, +{"id": "KEY-007", "path": "keyValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["customer_no"]}, +{"id": "KEY-008", "path": "keyValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'O\\'Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["customer_no"]}, +{"id": "KEY-009", "path": "keyValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "O'Brien", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'O''Brien'"}, "failureImpact": "A single quote that is not doubled or escaped ends the literal early.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["customer_no"]}, +{"id": "KEY-010", "path": "keyValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "E'\\\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["customer_no"]}, +{"id": "KEY-011", "path": "keyValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["customer_no"]}, +{"id": "KEY-012", "path": "keyValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["customer_no"]}, +{"id": "KEY-013", "path": "keyValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["customer_no"]}, +{"id": "KEY-014", "path": "keyValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["customer_no"]}, +{"id": "KEY-015", "path": "keyValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\\\' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["customer_no"]}, +{"id": "KEY-016", "path": "keyValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["customer_no"]}, +{"id": "KEY-017", "path": "keyValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'\\\\\\' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["customer_no"]}, +{"id": "KEY-018", "path": "keyValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'\\'' OR 1=1 -- '"}, "failureImpact": "On a backslash engine the backslash eats the doubled quote, so OR 1=1 runs and the rest is commented out.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["customer_no"]}, +{"id": "KEY-019", "path": "keyValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["customer_no"]}, +{"id": "KEY-020", "path": "keyValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["customer_no"]}, +{"id": "KEY-021", "path": "keyValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["customer_no"]}, +{"id": "KEY-022", "path": "keyValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["customer_no"]}, +{"id": "KEY-023", "path": "keyValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["customer_no"]}, +{"id": "KEY-024", "path": "keyValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["customer_no"]}, +{"id": "KEY-025", "path": "keyValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["customer_no"]}, +{"id": "KEY-026", "path": "keyValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["customer_no"]}, +{"id": "KEY-027", "path": "keyValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'a \\:b'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter even inside quotes, so the statement fails or takes a bound value.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["customer_no"]}, +{"id": "KEY-028", "path": "keyValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["customer_no"]}, +{"id": "KEY-029", "path": "keyValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["customer_no"]}, +{"id": "KEY-030", "path": "keyValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["customer_no"]}, +{"id": "KEY-031", "path": "keyValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["customer_no"]}, +{"id": "KEY-032", "path": "keyValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["customer_no"]}, +{"id": "KEY-033", "path": "keyValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["customer_no"]}, +{"id": "KEY-034", "path": "keyValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["customer_no"]}, +{"id": "KEY-035", "path": "keyValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["customer_no"]}, +{"id": "KEY-036", "path": "keyValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a\u2019b\uff07c\u02bcd", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'a\u2019b\uff07c\u02bcd'"}, "failureImpact": "Unicode look-alike quotes are plain characters and must not be treated as, or turned into, a quote.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["customer_no"]}, +{"id": "KEY-037", "path": "keyValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": [" eu", 42], "columnType": "VARCHAR,INT", "expectedOutcome": {"kind": "rendered", "text": "' eu' | 42"}, "failureImpact": "Each part of a composite key renders by its own column type.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": [["tenant_id"], ["customer_id"]]}, +{"id": "KEY-038", "path": "keyValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": [" eu", 42], "columnType": "VARCHAR,INT", "expectedOutcome": {"kind": "rendered", "text": "' eu' | 42"}, "failureImpact": "Each part of a composite key renders by its own column type.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": [["tenant_id"], ["customer_id"]]}, +{"id": "KEY-039", "path": "keyValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": [" eu", 42], "columnType": "VARCHAR,INT", "expectedOutcome": {"kind": "rendered", "text": "' eu' | 42"}, "failureImpact": "Each part of a composite key renders by its own column type.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": [["tenant_id"], ["customer_id"]]}, +{"id": "KEY-040", "path": "keyValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": [" eu", 42], "columnType": "VARCHAR,INT", "expectedOutcome": {"kind": "rendered", "text": "' eu' | 42"}, "failureImpact": "Each part of a composite key renders by its own column type.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": [["tenant_id"], ["customer_id"]]}, +{"id": "KEY-041", "path": "keyValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": [" eu", 42], "columnType": "VARCHAR,INT", "expectedOutcome": {"kind": "rendered", "text": "' eu' | 42"}, "failureImpact": "Each part of a composite key renders by its own column type.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": [["tenant_id"], ["customer_id"]]}, +{"id": "KEY-042", "path": "keyValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": [" eu", 42], "columnType": "VARCHAR,INT", "expectedOutcome": {"kind": "rendered", "text": "' eu' | 42"}, "failureImpact": "Each part of a composite key renders by its own column type.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": [["tenant_id"], ["customer_id"]]}, +{"id": "KEY-043", "path": "keyValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": [" eu", 42], "columnType": "VARCHAR,INT", "expectedOutcome": {"kind": "rendered", "text": "' eu' | 42"}, "failureImpact": "Each part of a composite key renders by its own column type.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": [["tenant_id"], ["customer_id"]]}, +{"id": "KEY-044", "path": "keyValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": [" eu", 42], "columnType": "VARCHAR,INT", "expectedOutcome": {"kind": "rendered", "text": "' eu' | 42"}, "failureImpact": "Each part of a composite key renders by its own column type.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": [["tenant_id"], ["customer_id"]]}, +{"id": "KEY-045", "path": "keyValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": [" eu", 42], "columnType": "VARCHAR,INT", "expectedOutcome": {"kind": "rendered", "text": "N' eu' | 42"}, "failureImpact": "Each part of a composite key renders by its own column type.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": [["tenant_id"], ["customer_id"]]}, +{"id": "KEY-046", "path": "keyValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "42 OR 1=1", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtRequest", "status": 400, "messageContains": ["does not parse as"]}, "failureImpact": "A crafted link runs OR 1=1 as the viewer.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["customer_id"]}, +{"id": "KEY-047", "path": "keyValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "42) UNION SELECT password FROM users --", "columnType": "INT", "expectedOutcome": {"kind": "refusedAtRequest", "status": 400, "messageContains": ["does not parse as"]}, "failureImpact": "A crafted link reads another table as the viewer.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["customer_id"]}, +{"id": "KEY-048", "path": "keyValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": null, "columnType": "INT", "expectedOutcome": {"kind": "refusedAtRequest", "status": 400, "messageContains": ["null"]}, "failureImpact": "A null key is not a record and must not render as NULL or 'null'.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["customer_id"]}, +{"id": "KEY-049", "path": "keyValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": [42, 43], "columnType": "INT", "expectedOutcome": {"kind": "refusedAtRequest", "status": 400, "messageContains": ["key has"]}, "failureImpact": "A key with more parts than the identity table's key changes the statement's shape.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["customer_id"]}, +{"id": "KEY-050", "path": "keyValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "a\nb", "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtRequest", "status": 400, "messageContains": ["control character"]}, "failureImpact": "A control character reaches the statement text.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["customer_no"]}, +{"id": "KEY-051", "path": "keyValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtRequest", "status": 400, "messageContains": ["at most 1024 characters"]}, "failureImpact": "An over-long key makes statements large and slow.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["customer_no"]}, +{"id": "KEY-052", "path": "keyValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "epoch", "columnType": "DATE", "expectedOutcome": {"kind": "refusedAtRequest", "status": 400, "messageContains": ["does not parse as"]}, "failureImpact": "A special date word is not a key value.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_on"]}, +{"id": "SRC-001", "path": "searchText", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "apple", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%apple%' ESCAPE '!'"}, "failureImpact": "Plain text must render as a contains pattern.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-002", "path": "searchText", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "apple", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%apple%' ESCAPE '!'"}, "failureImpact": "Plain text must render as a contains pattern.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-003", "path": "searchText", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "apple", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%apple%' ESCAPE '!'"}, "failureImpact": "Plain text must render as a contains pattern.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-004", "path": "searchText", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "apple", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%apple%'"}, "failureImpact": "Plain text must render as a contains pattern.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-005", "path": "searchText", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "apple", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%apple%'"}, "failureImpact": "Plain text must render as a contains pattern.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-006", "path": "searchText", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "apple", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%apple%'"}, "failureImpact": "Plain text must render as a contains pattern.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-007", "path": "searchText", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "apple", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%apple%' ESCAPE '!'"}, "failureImpact": "Plain text must render as a contains pattern.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-008", "path": "searchText", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "apple", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%apple%'"}, "failureImpact": "Plain text must render as a contains pattern.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-009", "path": "searchText", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "apple", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'%apple%' ESCAPE '!'"}, "failureImpact": "Plain text must render as a contains pattern.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-010", "path": "searchText", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%50!%!_off%' ESCAPE '!'"}, "failureImpact": "Unescaped % and _ match any text, so a search for 50%_off matches 50 percent of everything.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-011", "path": "searchText", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%50!%!_off%' ESCAPE '!'"}, "failureImpact": "Unescaped % and _ match any text, so a search for 50%_off matches 50 percent of everything.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-012", "path": "searchText", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%50!%!_off%' ESCAPE '!'"}, "failureImpact": "Unescaped % and _ match any text, so a search for 50%_off matches 50 percent of everything.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-013", "path": "searchText", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%50\\\\%\\\\_off%'"}, "failureImpact": "Unescaped % and _ match any text, so a search for 50%_off matches 50 percent of everything.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-014", "path": "searchText", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%50\\\\%\\\\_off%'"}, "failureImpact": "Unescaped % and _ match any text, so a search for 50%_off matches 50 percent of everything.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-015", "path": "searchText", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%50\\\\%\\\\_off%'"}, "failureImpact": "Unescaped % and _ match any text, so a search for 50%_off matches 50 percent of everything.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-016", "path": "searchText", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%50!%!_off%' ESCAPE '!'"}, "failureImpact": "Unescaped % and _ match any text, so a search for 50%_off matches 50 percent of everything.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-017", "path": "searchText", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%50\\\\%\\\\_off%'"}, "failureImpact": "Unescaped % and _ match any text, so a search for 50%_off matches 50 percent of everything.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-018", "path": "searchText", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "50%_off", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'%50!%!_off%' ESCAPE '!'"}, "failureImpact": "Unescaped % and _ match any text, so a search for 50%_off matches 50 percent of everything.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-019", "path": "searchText", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "%", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%!%%' ESCAPE '!'"}, "failureImpact": "A lone % must match only rows that contain a percent sign.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-020", "path": "searchText", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "%", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%!%%' ESCAPE '!'"}, "failureImpact": "A lone % must match only rows that contain a percent sign.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-021", "path": "searchText", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "%", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%!%%' ESCAPE '!'"}, "failureImpact": "A lone % must match only rows that contain a percent sign.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-022", "path": "searchText", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "%", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\%%'"}, "failureImpact": "A lone % must match only rows that contain a percent sign.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-023", "path": "searchText", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "%", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\%%'"}, "failureImpact": "A lone % must match only rows that contain a percent sign.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-024", "path": "searchText", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "%", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\%%'"}, "failureImpact": "A lone % must match only rows that contain a percent sign.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-025", "path": "searchText", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "%", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%!%%' ESCAPE '!'"}, "failureImpact": "A lone % must match only rows that contain a percent sign.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-026", "path": "searchText", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "%", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\%%'"}, "failureImpact": "A lone % must match only rows that contain a percent sign.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-027", "path": "searchText", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "%", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'%!%%' ESCAPE '!'"}, "failureImpact": "A lone % must match only rows that contain a percent sign.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-028", "path": "searchText", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "_", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%!_%' ESCAPE '!'"}, "failureImpact": "A lone _ must match only rows that contain an underscore.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-029", "path": "searchText", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "_", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%!_%' ESCAPE '!'"}, "failureImpact": "A lone _ must match only rows that contain an underscore.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-030", "path": "searchText", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "_", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%!_%' ESCAPE '!'"}, "failureImpact": "A lone _ must match only rows that contain an underscore.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-031", "path": "searchText", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "_", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\_%'"}, "failureImpact": "A lone _ must match only rows that contain an underscore.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-032", "path": "searchText", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "_", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\_%'"}, "failureImpact": "A lone _ must match only rows that contain an underscore.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-033", "path": "searchText", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "_", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\_%'"}, "failureImpact": "A lone _ must match only rows that contain an underscore.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-034", "path": "searchText", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "_", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%!_%' ESCAPE '!'"}, "failureImpact": "A lone _ must match only rows that contain an underscore.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-035", "path": "searchText", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "_", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\_%'"}, "failureImpact": "A lone _ must match only rows that contain an underscore.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-036", "path": "searchText", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "_", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'%!_%' ESCAPE '!'"}, "failureImpact": "A lone _ must match only rows that contain an underscore.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-037", "path": "searchText", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a!b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a!!b%' ESCAPE '!'"}, "failureImpact": "The escape character itself must be escaped or it escapes the next character.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-038", "path": "searchText", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a!b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a!!b%' ESCAPE '!'"}, "failureImpact": "The escape character itself must be escaped or it escapes the next character.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-039", "path": "searchText", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a!b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a!!b%' ESCAPE '!'"}, "failureImpact": "The escape character itself must be escaped or it escapes the next character.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-040", "path": "searchText", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a!b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a!b%'"}, "failureImpact": "The escape character itself must be escaped or it escapes the next character.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-041", "path": "searchText", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a!b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a!b%'"}, "failureImpact": "The escape character itself must be escaped or it escapes the next character.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-042", "path": "searchText", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a!b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a!b%'"}, "failureImpact": "The escape character itself must be escaped or it escapes the next character.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-043", "path": "searchText", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a!b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a!!b%' ESCAPE '!'"}, "failureImpact": "The escape character itself must be escaped or it escapes the next character.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-044", "path": "searchText", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a!b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a!b%'"}, "failureImpact": "The escape character itself must be escaped or it escapes the next character.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-045", "path": "searchText", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a!b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'%a!!b%' ESCAPE '!'"}, "failureImpact": "The escape character itself must be escaped or it escapes the next character.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-046", "path": "searchText", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "[abc]", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%[abc]%' ESCAPE '!'"}, "failureImpact": "T-SQL LIKE reads [abc] as a character class.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-047", "path": "searchText", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "[abc]", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%[abc]%' ESCAPE '!'"}, "failureImpact": "T-SQL LIKE reads [abc] as a character class.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-048", "path": "searchText", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "[abc]", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%[abc]%' ESCAPE '!'"}, "failureImpact": "T-SQL LIKE reads [abc] as a character class.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-049", "path": "searchText", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "[abc]", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%[abc]%'"}, "failureImpact": "T-SQL LIKE reads [abc] as a character class.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-050", "path": "searchText", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "[abc]", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%[abc]%'"}, "failureImpact": "T-SQL LIKE reads [abc] as a character class.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-051", "path": "searchText", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "[abc]", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%[abc]%'"}, "failureImpact": "T-SQL LIKE reads [abc] as a character class.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-052", "path": "searchText", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "[abc]", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%[abc]%' ESCAPE '!'"}, "failureImpact": "T-SQL LIKE reads [abc] as a character class.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-053", "path": "searchText", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "[abc]", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%[abc]%'"}, "failureImpact": "T-SQL LIKE reads [abc] as a character class.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-054", "path": "searchText", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "[abc]", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'%![abc]%' ESCAPE '!'"}, "failureImpact": "T-SQL LIKE reads [abc] as a character class.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-055", "path": "searchText", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "E'%\\\\%' ESCAPE '!'"}, "failureImpact": "A backslash is the default LIKE escape on several engines and a string escape on others.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-056", "path": "searchText", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\%' ESCAPE '!'"}, "failureImpact": "A backslash is the default LIKE escape on several engines and a string escape on others.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-057", "path": "searchText", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\%' ESCAPE '!'"}, "failureImpact": "A backslash is the default LIKE escape on several engines and a string escape on others.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-058", "path": "searchText", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\\\\\%'"}, "failureImpact": "A backslash is the default LIKE escape on several engines and a string escape on others.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-059", "path": "searchText", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\\\\\%'"}, "failureImpact": "A backslash is the default LIKE escape on several engines and a string escape on others.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-060", "path": "searchText", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\\\\\%'"}, "failureImpact": "A backslash is the default LIKE escape on several engines and a string escape on others.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-061", "path": "searchText", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\%' ESCAPE '!'"}, "failureImpact": "A backslash is the default LIKE escape on several engines and a string escape on others.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-062", "path": "searchText", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%\\\\\\\\%'"}, "failureImpact": "A backslash is the default LIKE escape on several engines and a string escape on others.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-063", "path": "searchText", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "\\", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'%\\%' ESCAPE '!'"}, "failureImpact": "A backslash is the default LIKE escape on several engines and a string escape on others.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-064", "path": "searchText", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "x' OR 1=1 --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%x'' OR 1=1 --%' ESCAPE '!'"}, "failureImpact": "Search text that breaks the quote runs as the viewer.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-065", "path": "searchText", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "x' OR 1=1 --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%x'' OR 1=1 --%' ESCAPE '!'"}, "failureImpact": "Search text that breaks the quote runs as the viewer.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-066", "path": "searchText", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "x' OR 1=1 --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%x'' OR 1=1 --%' ESCAPE '!'"}, "failureImpact": "Search text that breaks the quote runs as the viewer.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-067", "path": "searchText", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "x' OR 1=1 --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%x'' OR 1=1 --%'"}, "failureImpact": "Search text that breaks the quote runs as the viewer.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-068", "path": "searchText", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "x' OR 1=1 --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%x'' OR 1=1 --%'"}, "failureImpact": "Search text that breaks the quote runs as the viewer.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-069", "path": "searchText", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "x' OR 1=1 --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%x\\' OR 1=1 --%'"}, "failureImpact": "Search text that breaks the quote runs as the viewer.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-070", "path": "searchText", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "x' OR 1=1 --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%x'' OR 1=1 --%' ESCAPE '!'"}, "failureImpact": "Search text that breaks the quote runs as the viewer.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-071", "path": "searchText", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "x' OR 1=1 --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%x\\' OR 1=1 --%'"}, "failureImpact": "Search text that breaks the quote runs as the viewer.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-072", "path": "searchText", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "x' OR 1=1 --", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'%x'' OR 1=1 --%' ESCAPE '!'"}, "failureImpact": "Search text that breaks the quote runs as the viewer.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-073", "path": "searchText", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a \\:b%' ESCAPE '!'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-074", "path": "searchText", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a \\:b%' ESCAPE '!'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-075", "path": "searchText", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a \\:b%' ESCAPE '!'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-076", "path": "searchText", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a \\:b%'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-077", "path": "searchText", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a \\:b%'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-078", "path": "searchText", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a \\:b%'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-079", "path": "searchText", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a \\:b%' ESCAPE '!'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-080", "path": "searchText", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'%a \\:b%'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-081", "path": "searchText", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "N'%a \\:b%' ESCAPE '!'"}, "failureImpact": "SQLAlchemy text() reads :b as a bind parameter.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["name"], "operator": "contains"}, +{"id": "SRC-082", "path": "searchText", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtRequest", "status": 400, "messageContains": ["at most 256 characters"]}, "failureImpact": "Unbounded search text makes every find a large statement.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["name"]}, +{"id": "SRC-083", "path": "searchText", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "a\rb", "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtRequest", "status": 400, "messageContains": ["control character"]}, "failureImpact": "A control character reaches the statement text.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["name"]}, +{"id": "CON-001", "path": "constraintValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": {"minInclusive": {"value": "0"}}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A bound must render as a number, not as text compared with a number.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["amount"]}, +{"id": "CON-002", "path": "constraintValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": {"in": [{"literal": {"value": "OPEN"}}, {"literal": {"value": "O'Brien"}}, {"literal": {"value": "x' OR '1'='1"}}, {"literal": {"value": "a\\b"}}, {"literal": {"value": "a :b"}}]}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O''Brien', 'x'' OR ''1''=''1', E'a\\\\b', 'a \\:b')"}, "failureImpact": "An in list from a shape runs as the service account, so one unescaped member is an injection with its rights.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["status"]}, +{"id": "CON-003", "path": "constraintValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": {"minInclusive": {"value": "0"}}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A bound must render as a number, not as text compared with a number.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["amount"]}, +{"id": "CON-004", "path": "constraintValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": {"in": [{"literal": {"value": "OPEN"}}, {"literal": {"value": "O'Brien"}}, {"literal": {"value": "x' OR '1'='1"}}, {"literal": {"value": "a\\b"}}, {"literal": {"value": "a :b"}}]}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O''Brien', 'x'' OR ''1''=''1', 'a\\\\b', 'a \\:b')"}, "failureImpact": "An in list from a shape runs as the service account, so one unescaped member is an injection with its rights.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["status"]}, +{"id": "CON-005", "path": "constraintValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": {"minInclusive": {"value": "0"}}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A bound must render as a number, not as text compared with a number.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["amount"]}, +{"id": "CON-006", "path": "constraintValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": {"in": [{"literal": {"value": "OPEN"}}, {"literal": {"value": "O'Brien"}}, {"literal": {"value": "x' OR '1'='1"}}, {"literal": {"value": "a\\b"}}, {"literal": {"value": "a :b"}}]}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O''Brien', 'x'' OR ''1''=''1', 'a\\b', 'a \\:b')"}, "failureImpact": "An in list from a shape runs as the service account, so one unescaped member is an injection with its rights.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["status"]}, +{"id": "CON-007", "path": "constraintValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": {"minInclusive": {"value": "0"}}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A bound must render as a number, not as text compared with a number.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["amount"]}, +{"id": "CON-008", "path": "constraintValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": {"in": [{"literal": {"value": "OPEN"}}, {"literal": {"value": "O'Brien"}}, {"literal": {"value": "x' OR '1'='1"}}, {"literal": {"value": "a\\b"}}, {"literal": {"value": "a :b"}}]}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O''Brien', 'x'' OR ''1''=''1', 'a\\\\b', 'a \\:b')"}, "failureImpact": "An in list from a shape runs as the service account, so one unescaped member is an injection with its rights.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["status"]}, +{"id": "CON-009", "path": "constraintValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": {"minInclusive": {"value": "0"}}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A bound must render as a number, not as text compared with a number.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["amount"]}, +{"id": "CON-010", "path": "constraintValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": {"in": [{"literal": {"value": "OPEN"}}, {"literal": {"value": "O'Brien"}}, {"literal": {"value": "x' OR '1'='1"}}, {"literal": {"value": "a\\b"}}, {"literal": {"value": "a :b"}}]}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O''Brien', 'x'' OR ''1''=''1', 'a\\\\b', 'a \\:b')"}, "failureImpact": "An in list from a shape runs as the service account, so one unescaped member is an injection with its rights.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["status"]}, +{"id": "CON-011", "path": "constraintValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": {"minInclusive": {"value": "0"}}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A bound must render as a number, not as text compared with a number.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["amount"]}, +{"id": "CON-012", "path": "constraintValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": {"in": [{"literal": {"value": "OPEN"}}, {"literal": {"value": "O'Brien"}}, {"literal": {"value": "x' OR '1'='1"}}, {"literal": {"value": "a\\b"}}, {"literal": {"value": "a :b"}}]}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O\\'Brien', 'x\\' OR \\'1\\'=\\'1', 'a\\\\b', 'a \\:b')"}, "failureImpact": "An in list from a shape runs as the service account, so one unescaped member is an injection with its rights.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["status"]}, +{"id": "CON-013", "path": "constraintValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": {"minInclusive": {"value": "0"}}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A bound must render as a number, not as text compared with a number.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["amount"]}, +{"id": "CON-014", "path": "constraintValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": {"in": [{"literal": {"value": "OPEN"}}, {"literal": {"value": "O'Brien"}}, {"literal": {"value": "x' OR '1'='1"}}, {"literal": {"value": "a\\b"}}, {"literal": {"value": "a :b"}}]}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O''Brien', 'x'' OR ''1''=''1', 'a\\\\b', 'a \\:b')"}, "failureImpact": "An in list from a shape runs as the service account, so one unescaped member is an injection with its rights.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["status"]}, +{"id": "CON-015", "path": "constraintValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": {"minInclusive": {"value": "0"}}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A bound must render as a number, not as text compared with a number.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["amount"]}, +{"id": "CON-016", "path": "constraintValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": {"in": [{"literal": {"value": "OPEN"}}, {"literal": {"value": "O'Brien"}}, {"literal": {"value": "x' OR '1'='1"}}, {"literal": {"value": "a\\b"}}, {"literal": {"value": "a :b"}}]}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "('OPEN', 'O\\'Brien', 'x\\' OR \\'1\\'=\\'1', 'a\\\\b', 'a \\:b')"}, "failureImpact": "An in list from a shape runs as the service account, so one unescaped member is an injection with its rights.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["status"]}, +{"id": "CON-017", "path": "constraintValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": {"minInclusive": {"value": "0"}}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "rendered", "text": "0"}, "failureImpact": "A bound must render as a number, not as text compared with a number.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["amount"]}, +{"id": "CON-018", "path": "constraintValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": {"in": [{"literal": {"value": "OPEN"}}, {"literal": {"value": "O'Brien"}}, {"literal": {"value": "x' OR '1'='1"}}, {"literal": {"value": "a\\b"}}, {"literal": {"value": "a :b"}}]}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "(N'OPEN', N'O''Brien', N'x'' OR ''1''=''1', N'a\\b', N'a \\:b')"}, "failureImpact": "An in list from a shape runs as the service account, so one unescaped member is an injection with its rights.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["status"]}, +{"id": "CON-019", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"minInclusive": {"value": "0 OR 1=1"}}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "A bound with trailing SQL runs as the service account.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["amount"]}, +{"id": "CON-020", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"maxInclusive": {"value": "2024-13-01"}}, "columnType": "DATE", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "An impossible date fails every run instead of failing the compile.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["created_on"]}, +{"id": "CON-021", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"minInclusive": {"value": "5", "datatypeIri": "http://www.w3.org/2001/XMLSchema#string"}}, "columnType": "INT", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "A string bound on a number column compares as text on some engines.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"]}, +{"id": "CON-022", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"in": [{"iri": "https://example.org/onto#Open"}]}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "An IRI has no literal form in a column test.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["status"]}, +{"id": "CON-023", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"in": [{"literal": {"value": "0"}}, {"literal": {"value": "1"}}, {"literal": {"value": "2"}}, {"literal": {"value": "3"}}, {"literal": {"value": "4"}}, {"literal": {"value": "5"}}, {"literal": {"value": "6"}}, {"literal": {"value": "7"}}, {"literal": {"value": "8"}}, {"literal": {"value": "9"}}, {"literal": {"value": "10"}}, {"literal": {"value": "11"}}, {"literal": {"value": "12"}}, {"literal": {"value": "13"}}, {"literal": {"value": "14"}}, {"literal": {"value": "15"}}, {"literal": {"value": "16"}}, {"literal": {"value": "17"}}, {"literal": {"value": "18"}}, {"literal": {"value": "19"}}, {"literal": {"value": "20"}}, {"literal": {"value": "21"}}, {"literal": {"value": "22"}}, {"literal": {"value": "23"}}, {"literal": {"value": "24"}}, {"literal": {"value": "25"}}, {"literal": {"value": "26"}}, {"literal": {"value": "27"}}, {"literal": {"value": "28"}}, {"literal": {"value": "29"}}, {"literal": {"value": "30"}}, {"literal": {"value": "31"}}, {"literal": {"value": "32"}}, {"literal": {"value": "33"}}, {"literal": {"value": "34"}}, {"literal": {"value": "35"}}, {"literal": {"value": "36"}}, {"literal": {"value": "37"}}, {"literal": {"value": "38"}}, {"literal": {"value": "39"}}, {"literal": {"value": "40"}}, {"literal": {"value": "41"}}, {"literal": {"value": "42"}}, {"literal": {"value": "43"}}, {"literal": {"value": "44"}}, {"literal": {"value": "45"}}, {"literal": {"value": "46"}}, {"literal": {"value": "47"}}, {"literal": {"value": "48"}}, {"literal": {"value": "49"}}, {"literal": {"value": "50"}}, {"literal": {"value": "51"}}, {"literal": {"value": "52"}}, {"literal": {"value": "53"}}, {"literal": {"value": "54"}}, {"literal": {"value": "55"}}, {"literal": {"value": "56"}}, {"literal": {"value": "57"}}, {"literal": {"value": "58"}}, {"literal": {"value": "59"}}, {"literal": {"value": "60"}}, {"literal": {"value": "61"}}, {"literal": {"value": "62"}}, {"literal": {"value": "63"}}, {"literal": {"value": "64"}}, {"literal": {"value": "65"}}, {"literal": {"value": "66"}}, {"literal": {"value": "67"}}, {"literal": {"value": "68"}}, {"literal": {"value": "69"}}, {"literal": {"value": "70"}}, {"literal": {"value": "71"}}, {"literal": {"value": "72"}}, {"literal": {"value": "73"}}, {"literal": {"value": "74"}}, {"literal": {"value": "75"}}, {"literal": {"value": "76"}}, {"literal": {"value": "77"}}, {"literal": {"value": "78"}}, {"literal": {"value": "79"}}, {"literal": {"value": "80"}}, {"literal": {"value": "81"}}, {"literal": {"value": "82"}}, {"literal": {"value": "83"}}, {"literal": {"value": "84"}}, {"literal": {"value": "85"}}, {"literal": {"value": "86"}}, {"literal": {"value": "87"}}, {"literal": {"value": "88"}}, {"literal": {"value": "89"}}, {"literal": {"value": "90"}}, {"literal": {"value": "91"}}, {"literal": {"value": "92"}}, {"literal": {"value": "93"}}, {"literal": {"value": "94"}}, {"literal": {"value": "95"}}, {"literal": {"value": "96"}}, {"literal": {"value": "97"}}, {"literal": {"value": "98"}}, {"literal": {"value": "99"}}, {"literal": {"value": "100"}}]}, "columnType": "INT", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "An unbounded in list builds a test of any size.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"]}, +{"id": "CON-024", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"in": [{"literal": {"value": "a\nb"}}]}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "A control character reaches the stored test SQL.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["status"]}, +{"id": "CON-025", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"pattern": "^(a+)+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "Nested quantifiers backtrack exponentially on Java, Spark and Trino regular expressions, so each run burns warehouse time.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["code"]}, +{"id": "CON-026", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"pattern": "^(x+x+)+y$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "Nested quantifiers backtrack exponentially on backtracking engines.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["code"]}, +{"id": "CON-027", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"pattern": "^(\\w+)\\1$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "A backreference has no linear-time implementation and is not supported by RE2 engines.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["code"]}, +{"id": "CON-028", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"pattern": "(?=a)a"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "Lookaround is not supported by POSIX or RE2 engines and backtracks on the others.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["code"]}, +{"id": "CON-029", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"pattern": "((((a{1,200}){1,200}){1,200}){1,200})"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "Nested bounded repeats exhaust the regular-expression compiler; Postgres refuses it as too complex.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["code"]}, +{"id": "CON-030", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"pattern": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "An over-long pattern is expensive to compile on every run.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["code"]}, +{"id": "CON-031", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"pattern": "^[A-Z]{2}$"}, "columnType": "INT", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "A pattern on a non-text column is cast differently per engine.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"]}, +{"id": "CON-032", "path": "constraintValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": {"pattern": "^[A-Z]{2}-[0-9]{4}$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^[A-Z]{2}-[0-9]{4}$'"}, "failureImpact": "A plain pattern must reach the regular-expression function unchanged.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-033", "path": "constraintValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": {"pattern": "^[A-Z]{2}-[0-9]{4}$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^[A-Z]{2}-[0-9]{4}$'"}, "failureImpact": "A plain pattern must reach the regular-expression function unchanged.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-034", "path": "constraintValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": {"pattern": "^[A-Z]{2}-[0-9]{4}$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^[A-Z]{2}-[0-9]{4}$'"}, "failureImpact": "A plain pattern must reach the regular-expression function unchanged.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-035", "path": "constraintValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": {"pattern": "^[A-Z]{2}-[0-9]{4}$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^[A-Z]{2}-[0-9]{4}$'"}, "failureImpact": "A plain pattern must reach the regular-expression function unchanged.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-036", "path": "constraintValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": {"pattern": "^[A-Z]{2}-[0-9]{4}$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^[A-Z]{2}-[0-9]{4}$'"}, "failureImpact": "A plain pattern must reach the regular-expression function unchanged.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-037", "path": "constraintValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": {"pattern": "^[A-Z]{2}-[0-9]{4}$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^[A-Z]{2}-[0-9]{4}$'"}, "failureImpact": "A plain pattern must reach the regular-expression function unchanged.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-038", "path": "constraintValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": {"pattern": "^[A-Z]{2}-[0-9]{4}$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^[A-Z]{2}-[0-9]{4}$'"}, "failureImpact": "A plain pattern must reach the regular-expression function unchanged.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-039", "path": "constraintValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": {"pattern": "^[A-Z]{2}-[0-9]{4}$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^[A-Z]{2}-[0-9]{4}$'"}, "failureImpact": "A plain pattern must reach the regular-expression function unchanged.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-040", "path": "constraintValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": {"pattern": "^[A-Z]{2}-[0-9]{4}$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "A plain pattern must reach the regular-expression function unchanged.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["code"], "note": "SQL Server before 2025 has no regular-expression function, so a pattern is not enforceable on the T-SQL family."}, +{"id": "CON-041", "path": "constraintValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": {"pattern": "^\\d{3}\\.\\d+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "E'^\\\\d{3}\\\\.\\\\d+$'"}, "failureImpact": "Pattern backslashes must survive the string literal so the engine sees \\d, not d.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-042", "path": "constraintValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": {"pattern": "^\\d{3}\\.\\d+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^\\\\d{3}\\\\.\\\\d+$'"}, "failureImpact": "Pattern backslashes must survive the string literal so the engine sees \\d, not d.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-043", "path": "constraintValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": {"pattern": "^\\d{3}\\.\\d+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^\\d{3}\\.\\d+$'"}, "failureImpact": "Pattern backslashes must survive the string literal so the engine sees \\d, not d.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-044", "path": "constraintValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": {"pattern": "^\\d{3}\\.\\d+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^\\\\d{3}\\\\.\\\\d+$'"}, "failureImpact": "Pattern backslashes must survive the string literal so the engine sees \\d, not d.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-045", "path": "constraintValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": {"pattern": "^\\d{3}\\.\\d+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^\\\\d{3}\\\\.\\\\d+$'"}, "failureImpact": "Pattern backslashes must survive the string literal so the engine sees \\d, not d.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-046", "path": "constraintValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": {"pattern": "^\\d{3}\\.\\d+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^\\\\d{3}\\\\.\\\\d+$'"}, "failureImpact": "Pattern backslashes must survive the string literal so the engine sees \\d, not d.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-047", "path": "constraintValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": {"pattern": "^\\d{3}\\.\\d+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^\\\\d{3}\\\\.\\\\d+$'"}, "failureImpact": "Pattern backslashes must survive the string literal so the engine sees \\d, not d.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-048", "path": "constraintValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": {"pattern": "^\\d{3}\\.\\d+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^\\\\d{3}\\\\.\\\\d+$'"}, "failureImpact": "Pattern backslashes must survive the string literal so the engine sees \\d, not d.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-049", "path": "constraintValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": {"pattern": "^\\d{3}\\.\\d+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "Pattern backslashes must survive the string literal so the engine sees \\d, not d.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["code"], "note": "SQL Server before 2025 has no regular-expression function, so a pattern is not enforceable on the T-SQL family."}, +{"id": "CON-050", "path": "constraintValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": {"pattern": "^O'[A-Z]+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^O''[A-Z]+$'"}, "failureImpact": "A quote inside a pattern ends the literal unless doubled or escaped.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-051", "path": "constraintValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": {"pattern": "^O'[A-Z]+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^O''[A-Z]+$'"}, "failureImpact": "A quote inside a pattern ends the literal unless doubled or escaped.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-052", "path": "constraintValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": {"pattern": "^O'[A-Z]+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^O''[A-Z]+$'"}, "failureImpact": "A quote inside a pattern ends the literal unless doubled or escaped.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-053", "path": "constraintValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": {"pattern": "^O'[A-Z]+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^O''[A-Z]+$'"}, "failureImpact": "A quote inside a pattern ends the literal unless doubled or escaped.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-054", "path": "constraintValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": {"pattern": "^O'[A-Z]+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^O''[A-Z]+$'"}, "failureImpact": "A quote inside a pattern ends the literal unless doubled or escaped.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-055", "path": "constraintValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": {"pattern": "^O'[A-Z]+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^O\\'[A-Z]+$'"}, "failureImpact": "A quote inside a pattern ends the literal unless doubled or escaped.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-056", "path": "constraintValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": {"pattern": "^O'[A-Z]+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^O''[A-Z]+$'"}, "failureImpact": "A quote inside a pattern ends the literal unless doubled or escaped.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-057", "path": "constraintValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": {"pattern": "^O'[A-Z]+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^O\\'[A-Z]+$'"}, "failureImpact": "A quote inside a pattern ends the literal unless doubled or escaped.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-058", "path": "constraintValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": {"pattern": "^O'[A-Z]+$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "A quote inside a pattern ends the literal unless doubled or escaped.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["code"], "note": "SQL Server before 2025 has no regular-expression function, so a pattern is not enforceable on the T-SQL family."}, +{"id": "CON-059", "path": "constraintValue", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": {"pattern": "^key :value$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^key \\:value$'"}, "failureImpact": "SQLAlchemy text() reads :value as a bind parameter.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-060", "path": "constraintValue", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": {"pattern": "^key :value$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^key \\:value$'"}, "failureImpact": "SQLAlchemy text() reads :value as a bind parameter.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-061", "path": "constraintValue", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": {"pattern": "^key :value$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^key \\:value$'"}, "failureImpact": "SQLAlchemy text() reads :value as a bind parameter.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-062", "path": "constraintValue", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": {"pattern": "^key :value$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^key \\:value$'"}, "failureImpact": "SQLAlchemy text() reads :value as a bind parameter.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-063", "path": "constraintValue", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": {"pattern": "^key :value$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^key \\:value$'"}, "failureImpact": "SQLAlchemy text() reads :value as a bind parameter.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-064", "path": "constraintValue", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": {"pattern": "^key :value$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^key \\:value$'"}, "failureImpact": "SQLAlchemy text() reads :value as a bind parameter.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-065", "path": "constraintValue", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": {"pattern": "^key :value$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^key \\:value$'"}, "failureImpact": "SQLAlchemy text() reads :value as a bind parameter.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-066", "path": "constraintValue", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": {"pattern": "^key :value$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "rendered", "text": "'^key \\:value$'"}, "failureImpact": "SQLAlchemy text() reads :value as a bind parameter.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"], "column": ["code"], "note": "Only the pattern literal is fixed here; the function that applies it is the compiler's choice per engine."}, +{"id": "CON-067", "path": "constraintValue", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": {"pattern": "^key :value$"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["not enforceable"]}, "failureImpact": "SQLAlchemy text() reads :value as a bind parameter.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"], "column": ["code"], "note": "SQL Server before 2025 has no regular-expression function, so a pattern is not enforceable on the T-SQL family."}, +{"id": "IDN-001", "path": "identifier", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "order", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"order\""}, "failureImpact": "A reserved word left unquoted is read as a keyword.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"]}, +{"id": "IDN-002", "path": "identifier", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "order", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"order\""}, "failureImpact": "A reserved word left unquoted is read as a keyword.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"]}, +{"id": "IDN-003", "path": "identifier", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "order", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"order\""}, "failureImpact": "A reserved word left unquoted is read as a keyword.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"]}, +{"id": "IDN-004", "path": "identifier", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "order", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`order`"}, "failureImpact": "A reserved word left unquoted is read as a keyword.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"]}, +{"id": "IDN-005", "path": "identifier", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "order", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`order`"}, "failureImpact": "A reserved word left unquoted is read as a keyword.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"]}, +{"id": "IDN-006", "path": "identifier", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "order", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`order`"}, "failureImpact": "A reserved word left unquoted is read as a keyword.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"]}, +{"id": "IDN-007", "path": "identifier", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "order", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"order\""}, "failureImpact": "A reserved word left unquoted is read as a keyword.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"]}, +{"id": "IDN-008", "path": "identifier", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "order", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`order`"}, "failureImpact": "A reserved word left unquoted is read as a keyword.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"]}, +{"id": "IDN-009", "path": "identifier", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "order", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "[order]"}, "failureImpact": "A reserved word left unquoted is read as a keyword.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"]}, +{"id": "IDN-010", "path": "identifier", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "Customer Name", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"Customer Name\""}, "failureImpact": "A space or upper case left unquoted splits or folds the name.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"]}, +{"id": "IDN-011", "path": "identifier", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "Customer Name", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"Customer Name\""}, "failureImpact": "A space or upper case left unquoted splits or folds the name.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"]}, +{"id": "IDN-012", "path": "identifier", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "Customer Name", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"Customer Name\""}, "failureImpact": "A space or upper case left unquoted splits or folds the name.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"]}, +{"id": "IDN-013", "path": "identifier", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "Customer Name", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`Customer Name`"}, "failureImpact": "A space or upper case left unquoted splits or folds the name.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"]}, +{"id": "IDN-014", "path": "identifier", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "Customer Name", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`Customer Name`"}, "failureImpact": "A space or upper case left unquoted splits or folds the name.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"]}, +{"id": "IDN-015", "path": "identifier", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "Customer Name", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`Customer Name`"}, "failureImpact": "A space or upper case left unquoted splits or folds the name.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"]}, +{"id": "IDN-016", "path": "identifier", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "Customer Name", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"Customer Name\""}, "failureImpact": "A space or upper case left unquoted splits or folds the name.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"]}, +{"id": "IDN-017", "path": "identifier", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "Customer Name", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`Customer Name`"}, "failureImpact": "A space or upper case left unquoted splits or folds the name.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"]}, +{"id": "IDN-018", "path": "identifier", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "Customer Name", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "[Customer Name]"}, "failureImpact": "A space or upper case left unquoted splits or folds the name.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"]}, +{"id": "IDN-019", "path": "identifier", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a\"b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a\"\"b\""}, "failureImpact": "A double quote inside a double-quoted name ends it early.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"]}, +{"id": "IDN-020", "path": "identifier", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a\"b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a\"\"b\""}, "failureImpact": "A double quote inside a double-quoted name ends it early.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"]}, +{"id": "IDN-021", "path": "identifier", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a\"b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a\"\"b\""}, "failureImpact": "A double quote inside a double-quoted name ends it early.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"]}, +{"id": "IDN-022", "path": "identifier", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a\"b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a\"b`"}, "failureImpact": "A double quote inside a double-quoted name ends it early.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"]}, +{"id": "IDN-023", "path": "identifier", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a\"b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a\"b`"}, "failureImpact": "A double quote inside a double-quoted name ends it early.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"]}, +{"id": "IDN-024", "path": "identifier", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a\"b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a\"b`"}, "failureImpact": "A double quote inside a double-quoted name ends it early.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"]}, +{"id": "IDN-025", "path": "identifier", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a\"b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a\"\"b\""}, "failureImpact": "A double quote inside a double-quoted name ends it early.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"]}, +{"id": "IDN-026", "path": "identifier", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a\"b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a\"b`"}, "failureImpact": "A double quote inside a double-quoted name ends it early.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"]}, +{"id": "IDN-027", "path": "identifier", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a\"b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "[a\"b]"}, "failureImpact": "A double quote inside a double-quoted name ends it early.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"]}, +{"id": "IDN-028", "path": "identifier", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a`b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a`b\""}, "failureImpact": "A backtick inside a backticked name ends it early.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"]}, +{"id": "IDN-029", "path": "identifier", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a`b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a`b\""}, "failureImpact": "A backtick inside a backticked name ends it early.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"]}, +{"id": "IDN-030", "path": "identifier", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a`b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a`b\""}, "failureImpact": "A backtick inside a backticked name ends it early.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"]}, +{"id": "IDN-031", "path": "identifier", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a`b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a``b`"}, "failureImpact": "A backtick inside a backticked name ends it early.", "proof": "liveEngineRequired", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"]}, +{"id": "IDN-032", "path": "identifier", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a`b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a\\`b`"}, "failureImpact": "A backtick inside a backticked name ends it early.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"]}, +{"id": "IDN-033", "path": "identifier", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a`b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a\\`b`"}, "failureImpact": "A backtick inside a backticked name ends it early.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"]}, +{"id": "IDN-034", "path": "identifier", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a`b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a`b\""}, "failureImpact": "A backtick inside a backticked name ends it early.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"]}, +{"id": "IDN-035", "path": "identifier", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a`b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a``b`"}, "failureImpact": "A backtick inside a backticked name ends it early.", "proof": "liveEngineRequired", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"]}, +{"id": "IDN-036", "path": "identifier", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a`b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "[a`b]"}, "failureImpact": "A backtick inside a backticked name ends it early.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"]}, +{"id": "IDN-037", "path": "identifier", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a]b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a]b\""}, "failureImpact": "A closing bracket inside a bracketed name ends it early.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"]}, +{"id": "IDN-038", "path": "identifier", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a]b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a]b\""}, "failureImpact": "A closing bracket inside a bracketed name ends it early.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"]}, +{"id": "IDN-039", "path": "identifier", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a]b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a]b\""}, "failureImpact": "A closing bracket inside a bracketed name ends it early.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"]}, +{"id": "IDN-040", "path": "identifier", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a]b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a]b`"}, "failureImpact": "A closing bracket inside a bracketed name ends it early.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"]}, +{"id": "IDN-041", "path": "identifier", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a]b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a]b`"}, "failureImpact": "A closing bracket inside a bracketed name ends it early.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"]}, +{"id": "IDN-042", "path": "identifier", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a]b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a]b`"}, "failureImpact": "A closing bracket inside a bracketed name ends it early.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"]}, +{"id": "IDN-043", "path": "identifier", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a]b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a]b\""}, "failureImpact": "A closing bracket inside a bracketed name ends it early.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"]}, +{"id": "IDN-044", "path": "identifier", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a]b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a]b`"}, "failureImpact": "A closing bracket inside a bracketed name ends it early.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"]}, +{"id": "IDN-045", "path": "identifier", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a]b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "[a]]b]"}, "failureImpact": "A closing bracket inside a bracketed name ends it early.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"]}, +{"id": "IDN-046", "path": "identifier", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "x\\", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"x\\\""}, "failureImpact": "ClickHouse and BigQuery read a backslash in a quoted name as an escape, so a trailing backslash escapes the closing quote.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"]}, +{"id": "IDN-047", "path": "identifier", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "x\\", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"x\\\""}, "failureImpact": "ClickHouse and BigQuery read a backslash in a quoted name as an escape, so a trailing backslash escapes the closing quote.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"]}, +{"id": "IDN-048", "path": "identifier", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "x\\", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"x\\\""}, "failureImpact": "ClickHouse and BigQuery read a backslash in a quoted name as an escape, so a trailing backslash escapes the closing quote.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"]}, +{"id": "IDN-049", "path": "identifier", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "x\\", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`x\\`"}, "failureImpact": "ClickHouse and BigQuery read a backslash in a quoted name as an escape, so a trailing backslash escapes the closing quote.", "proof": "liveEngineRequired", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"]}, +{"id": "IDN-050", "path": "identifier", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "x\\", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`x\\\\`"}, "failureImpact": "ClickHouse and BigQuery read a backslash in a quoted name as an escape, so a trailing backslash escapes the closing quote.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"]}, +{"id": "IDN-051", "path": "identifier", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "x\\", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`x\\\\`"}, "failureImpact": "ClickHouse and BigQuery read a backslash in a quoted name as an escape, so a trailing backslash escapes the closing quote.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"]}, +{"id": "IDN-052", "path": "identifier", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "x\\", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"x\\\""}, "failureImpact": "ClickHouse and BigQuery read a backslash in a quoted name as an escape, so a trailing backslash escapes the closing quote.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"]}, +{"id": "IDN-053", "path": "identifier", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "x\\", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`x\\`"}, "failureImpact": "ClickHouse and BigQuery read a backslash in a quoted name as an escape, so a trailing backslash escapes the closing quote.", "proof": "liveEngineRequired", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"]}, +{"id": "IDN-054", "path": "identifier", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "x\\", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "[x\\]"}, "failureImpact": "ClickHouse and BigQuery read a backslash in a quoted name as an escape, so a trailing backslash escapes the closing quote.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"]}, +{"id": "IDN-055", "path": "identifier", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a.b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a.b\""}, "failureImpact": "A dot inside a name is read as a qualifier unless the name is quoted.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"]}, +{"id": "IDN-056", "path": "identifier", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a.b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a.b\""}, "failureImpact": "A dot inside a name is read as a qualifier unless the name is quoted.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"]}, +{"id": "IDN-057", "path": "identifier", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a.b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a.b\""}, "failureImpact": "A dot inside a name is read as a qualifier unless the name is quoted.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"]}, +{"id": "IDN-058", "path": "identifier", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a.b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a.b`"}, "failureImpact": "A dot inside a name is read as a qualifier unless the name is quoted.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"]}, +{"id": "IDN-059", "path": "identifier", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a.b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a.b`"}, "failureImpact": "A dot inside a name is read as a qualifier unless the name is quoted.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"]}, +{"id": "IDN-060", "path": "identifier", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a.b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a.b`"}, "failureImpact": "A dot inside a name is read as a qualifier unless the name is quoted.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"]}, +{"id": "IDN-061", "path": "identifier", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a.b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a.b\""}, "failureImpact": "A dot inside a name is read as a qualifier unless the name is quoted.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"]}, +{"id": "IDN-062", "path": "identifier", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a.b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a.b`"}, "failureImpact": "A dot inside a name is read as a qualifier unless the name is quoted.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"]}, +{"id": "IDN-063", "path": "identifier", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a.b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "[a.b]"}, "failureImpact": "A dot inside a name is read as a qualifier unless the name is quoted.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"]}, +{"id": "IDN-064", "path": "identifier", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a :p0", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a \\:p0\""}, "failureImpact": "SQLAlchemy text() reads :p0 inside a quoted name as a bind parameter; with a bound value the driver writes that value into the name.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"]}, +{"id": "IDN-065", "path": "identifier", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a :p0", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a \\:p0\""}, "failureImpact": "SQLAlchemy text() reads :p0 inside a quoted name as a bind parameter; with a bound value the driver writes that value into the name.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"]}, +{"id": "IDN-066", "path": "identifier", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a :p0", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a \\:p0\""}, "failureImpact": "SQLAlchemy text() reads :p0 inside a quoted name as a bind parameter; with a bound value the driver writes that value into the name.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"]}, +{"id": "IDN-067", "path": "identifier", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a :p0", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a \\:p0`"}, "failureImpact": "SQLAlchemy text() reads :p0 inside a quoted name as a bind parameter; with a bound value the driver writes that value into the name.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"]}, +{"id": "IDN-068", "path": "identifier", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a :p0", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a \\:p0`"}, "failureImpact": "SQLAlchemy text() reads :p0 inside a quoted name as a bind parameter; with a bound value the driver writes that value into the name.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"]}, +{"id": "IDN-069", "path": "identifier", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a :p0", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a \\:p0`"}, "failureImpact": "SQLAlchemy text() reads :p0 inside a quoted name as a bind parameter; with a bound value the driver writes that value into the name.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"]}, +{"id": "IDN-070", "path": "identifier", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a :p0", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a \\:p0\""}, "failureImpact": "SQLAlchemy text() reads :p0 inside a quoted name as a bind parameter; with a bound value the driver writes that value into the name.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"]}, +{"id": "IDN-071", "path": "identifier", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a :p0", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a \\:p0`"}, "failureImpact": "SQLAlchemy text() reads :p0 inside a quoted name as a bind parameter; with a bound value the driver writes that value into the name.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"]}, +{"id": "IDN-072", "path": "identifier", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a :p0", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "[a \\:p0]"}, "failureImpact": "SQLAlchemy text() reads :p0 inside a quoted name as a bind parameter; with a bound value the driver writes that value into the name.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"]}, +{"id": "IDN-073", "path": "identifier", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a--b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a--b\""}, "failureImpact": "Comment text inside a quoted name must stay inside the quotes.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"]}, +{"id": "IDN-074", "path": "identifier", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a--b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a--b\""}, "failureImpact": "Comment text inside a quoted name must stay inside the quotes.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"]}, +{"id": "IDN-075", "path": "identifier", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a--b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a--b\""}, "failureImpact": "Comment text inside a quoted name must stay inside the quotes.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"]}, +{"id": "IDN-076", "path": "identifier", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a--b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a--b`"}, "failureImpact": "Comment text inside a quoted name must stay inside the quotes.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"]}, +{"id": "IDN-077", "path": "identifier", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a--b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a--b`"}, "failureImpact": "Comment text inside a quoted name must stay inside the quotes.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"]}, +{"id": "IDN-078", "path": "identifier", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a--b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a--b`"}, "failureImpact": "Comment text inside a quoted name must stay inside the quotes.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"]}, +{"id": "IDN-079", "path": "identifier", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a--b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a--b\""}, "failureImpact": "Comment text inside a quoted name must stay inside the quotes.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"]}, +{"id": "IDN-080", "path": "identifier", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a--b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a--b`"}, "failureImpact": "Comment text inside a quoted name must stay inside the quotes.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"]}, +{"id": "IDN-081", "path": "identifier", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a--b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "[a--b]"}, "failureImpact": "Comment text inside a quoted name must stay inside the quotes.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"]}, +{"id": "IDN-082", "path": "identifier", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a;DROP TABLE t", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a;DROP TABLE t\""}, "failureImpact": "A separator inside a quoted name must stay inside the quotes.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"]}, +{"id": "IDN-083", "path": "identifier", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a;DROP TABLE t", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a;DROP TABLE t\""}, "failureImpact": "A separator inside a quoted name must stay inside the quotes.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"]}, +{"id": "IDN-084", "path": "identifier", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a;DROP TABLE t", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a;DROP TABLE t\""}, "failureImpact": "A separator inside a quoted name must stay inside the quotes.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"]}, +{"id": "IDN-085", "path": "identifier", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a;DROP TABLE t", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a;DROP TABLE t`"}, "failureImpact": "A separator inside a quoted name must stay inside the quotes.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"]}, +{"id": "IDN-086", "path": "identifier", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a;DROP TABLE t", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a;DROP TABLE t`"}, "failureImpact": "A separator inside a quoted name must stay inside the quotes.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"]}, +{"id": "IDN-087", "path": "identifier", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a;DROP TABLE t", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a;DROP TABLE t`"}, "failureImpact": "A separator inside a quoted name must stay inside the quotes.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"]}, +{"id": "IDN-088", "path": "identifier", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a;DROP TABLE t", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a;DROP TABLE t\""}, "failureImpact": "A separator inside a quoted name must stay inside the quotes.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"]}, +{"id": "IDN-089", "path": "identifier", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a;DROP TABLE t", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a;DROP TABLE t`"}, "failureImpact": "A separator inside a quoted name must stay inside the quotes.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"]}, +{"id": "IDN-090", "path": "identifier", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a;DROP TABLE t", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "[a;DROP TABLE t]"}, "failureImpact": "A separator inside a quoted name must stay inside the quotes.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"]}, +{"id": "IDN-091", "path": "identifier", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a\uff02b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a\uff02b\""}, "failureImpact": "A full-width quote is a plain character and must not be read as a quote.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"]}, +{"id": "IDN-092", "path": "identifier", "engineFamily": "redshift", "serviceTypes": ["Redshift"], "input": "a\uff02b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a\uff02b\""}, "failureImpact": "A full-width quote is a plain character and must not be read as a quote.", "proof": "liveEngineRequired", "references": ["https://docs.aws.amazon.com/redshift/latest/dg/r_QUOTE_LITERAL.html", "https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html"]}, +{"id": "IDN-093", "path": "identifier", "engineFamily": "trino", "serviceTypes": ["Trino", "Presto", "Athena"], "input": "a\uff02b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a\uff02b\""}, "failureImpact": "A full-width quote is a plain character and must not be read as a quote.", "proof": "docs", "references": ["https://trino.io/docs/current/language/types.html", "https://trino.io/docs/current/functions/comparison.html"]}, +{"id": "IDN-094", "path": "identifier", "engineFamily": "mysql", "serviceTypes": ["Mysql", "MariaDB", "SingleStore", "Doris", "StarRocks"], "input": "a\uff02b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a\uff02b`"}, "failureImpact": "A full-width quote is a plain character and must not be read as a quote.", "proof": "live", "references": ["https://dev.mysql.com/doc/refman/8.4/en/string-literals.html", "https://dev.mysql.com/doc/refman/8.4/en/identifiers.html", "https://doris.apache.org/docs/sql-manual/basic-element/literal/string-literal"]}, +{"id": "IDN-095", "path": "identifier", "engineFamily": "clickhouse", "serviceTypes": ["Clickhouse"], "input": "a\uff02b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a\uff02b`"}, "failureImpact": "A full-width quote is a plain character and must not be read as a quote.", "proof": "liveEngineRequired", "references": ["https://clickhouse.com/docs/sql-reference/syntax", "https://clickhouse.com/docs/sql-reference/functions/string-search-functions"]}, +{"id": "IDN-096", "path": "identifier", "engineFamily": "bigquery", "serviceTypes": ["BigQuery"], "input": "a\uff02b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a\uff02b`"}, "failureImpact": "A full-width quote is a plain character and must not be read as a quote.", "proof": "docs", "references": ["https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/lexical", "https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/operators"]}, +{"id": "IDN-097", "path": "identifier", "engineFamily": "snowflake", "serviceTypes": ["Snowflake"], "input": "a\uff02b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "\"a\uff02b\""}, "failureImpact": "A full-width quote is a plain character and must not be read as a quote.", "proof": "docs", "references": ["https://docs.snowflake.com/en/sql-reference/data-types-text", "https://docs.snowflake.com/en/sql-reference/functions/like"]}, +{"id": "IDN-098", "path": "identifier", "engineFamily": "spark", "serviceTypes": ["Databricks", "UnityCatalog", "Hive", "Impala", "Iomete"], "input": "a\uff02b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "`a\uff02b`"}, "failureImpact": "A full-width quote is a plain character and must not be read as a quote.", "proof": "docs", "references": ["https://docs.databricks.com/aws/en/sql/language-manual/data-types/string-type", "https://spark.apache.org/docs/latest/sql-ref-literals.html", "https://impala.apache.org/docs/build/html/topics/impala_literals.html"]}, +{"id": "IDN-099", "path": "identifier", "engineFamily": "tsql", "serviceTypes": ["Mssql", "AzureSQL", "Synapse", "MicrosoftFabric"], "input": "a\uff02b", "columnType": "name", "expectedOutcome": {"kind": "rendered", "text": "[a\uff02b]"}, "failureImpact": "A full-width quote is a plain character and must not be read as a quote.", "proof": "docs", "references": ["https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-backslash", "https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql"]}, +{"id": "IDN-100", "path": "identifier", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "a\nb", "columnType": "name", "expectedOutcome": {"kind": "refusedAtBuild", "messageContains": ["control character"]}, "failureImpact": "A newline in a table name reaches the statement text.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"]}, +{"id": "CMT-001", "path": "commentText", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "x */ OR 1=1 /*", "columnType": "label", "expectedOutcome": {"kind": "rendered", "statementMustNotContain": ["OR 1=1", "--", "/*"]}, "failureImpact": "sqlglot turns a -- comment into /* */ when it rewrites a statement, so a label holding */ becomes live SQL; :note becomes a bind parameter.", "proof": "sqlglotRewrite", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "note": "Applies to every statement that carries a hop or relation label."}, +{"id": "CMT-002", "path": "commentText", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "see :note", "columnType": "label", "expectedOutcome": {"kind": "rendered", "statementMustNotContain": [":note", "--", "/*"]}, "failureImpact": "sqlglot turns a -- comment into /* */ when it rewrites a statement, so a label holding */ becomes live SQL; :note becomes a bind parameter.", "proof": "sqlglotRewrite", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "note": "Applies to every statement that carries a hop or relation label."}, +{"id": "CMT-003", "path": "commentText", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "x\nOR 1=1", "columnType": "label", "expectedOutcome": {"kind": "rendered", "statementMustNotContain": ["1=1", "--", "/*"]}, "failureImpact": "sqlglot turns a -- comment into /* */ when it rewrites a statement, so a label holding */ becomes live SQL; :note becomes a bind parameter.", "proof": "sqlglotRewrite", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "note": "Applies to every statement that carries a hop or relation label."}, +{"id": "PRB-001", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"column": ["salary"], "operator": "greaterThan", "value": 100000}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "refusedAtSave", "status": 403, "messageContains": ["ViewSampleData"]}, "failureImpact": "An editor with EditAll but not ViewSampleData sets a filter on a guessed value and reads the answer from the class count.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"]}, +{"id": "PRB-002", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"column": ["salary"], "operator": "greaterThan", "value": 150000}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "refusedAtSave", "status": 403, "messageContains": ["ViewSampleData"]}, "failureImpact": "Changing an existing filter's value is the binary search step of the probe.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"]}, +{"id": "PRB-003", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"column": ["ssn"], "operator": "in", "value": ["123-45-6789", "987-65-4321"]}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtSave", "status": 403, "messageContains": ["ViewSampleData"]}, "failureImpact": "An in list tests up to 100 guesses in one count.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"]}, +{"id": "PRB-004", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"column": ["ssn"], "operator": "isNotNull"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "refusedAtSave", "status": 403, "messageContains": ["ViewSampleData"]}, "failureImpact": "A null test with no value still reveals how many rows hold the column.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"]}, +{"id": "PRB-005", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"column": ["salary"], "operator": "greaterThan", "value": 100000, "via": "changeSet"}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "refusedAtSave", "status": 403, "messageContains": ["ViewSampleData"]}, "failureImpact": "A proposed change applied by a person without ViewSampleData must be held to that person's rights.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"]}, +{"id": "PRB-006", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"column": ["salary"], "operator": "greaterThan", "value": 100000, "viewer": "noViewDataProfile"}, "columnType": "DECIMAL", "expectedOutcome": {"kind": "countWithheld"}, "failureImpact": "A stored count for a filtered class shown to a viewer without ViewDataProfile on every table it read leaks the probe's answer.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"]}, +{"id": "PRB-007", "path": "constraintValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": {"pattern": "^4111", "author": "noViewSampleData"}, "columnType": "VARCHAR", "expectedOutcome": {"kind": "proposedNotRun"}, "failureImpact": "A shape's pattern on a column its author cannot read turns failing-row counts into a probe unless the test waits for a person with CreateTests.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"]}, +{"id": "SNP-001", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "x' OR '1'='1", "columnType": "VARCHAR", "expectedOutcome": {"kind": "bound", "parameters": ["x' OR '1'='1"], "textMustNotContain": ["x' OR '1'='1"]}, "failureImpact": "A value written into the job's text instead of bound runs with the service account's rights.", "proof": "live", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["status"], "operator": "equals"}, +{"id": "SNP-002", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "a :b", "columnType": "VARCHAR", "expectedOutcome": {"kind": "bound", "parameters": ["a :b"], "textMustNotContain": ["a :b"]}, "failureImpact": "A value written into the job's text instead of bound runs with the service account's rights.", "proof": "live", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["status"], "operator": "equals"}, +{"id": "SNP-003", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "50%", "columnType": "VARCHAR", "expectedOutcome": {"kind": "bound", "parameters": ["50%"], "textMustNotContain": ["50%"]}, "failureImpact": "A value written into the job's text instead of bound runs with the service account's rights.", "proof": "live", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["status"], "operator": "equals"}, +{"id": "SNP-004", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "\\' OR 1=1 -- ", "columnType": "VARCHAR", "expectedOutcome": {"kind": "bound", "parameters": ["\\' OR 1=1 -- "], "textMustNotContain": ["\\' OR 1=1 -- "]}, "failureImpact": "A value written into the job's text instead of bound runs with the service account's rights.", "proof": "live", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["status"], "operator": "equals"}, +{"id": "SNP-005", "path": "rowFilterValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": 42, "columnType": "INT", "expectedOutcome": {"kind": "bound", "parameters": [42], "textMustNotContain": []}, "failureImpact": "A value written into the job's text instead of bound runs with the service account's rights.", "proof": "live", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "column": ["qty"], "operator": "equals"}, +{"id": "SNP-006", "path": "identifier", "engineFamily": "postgres", "serviceTypes": ["Postgres", "Timescale"], "input": "a :p0", "columnType": "name", "expectedOutcome": {"kind": "bound", "parameters": ["x\" , 1 AS y FROM t --"], "text": "SELECT COUNT(*) FROM t WHERE \"a \\:p0\" = :p0", "bindParameterCount": 1}, "failureImpact": "Proven on Postgres 15 with psycopg2: an unescaped :p0 inside a quoted column name takes the bound value, which closes the name and runs the rest as SQL.", "proof": "live", "references": ["https://www.postgresql.org/docs/15/sql-syntax-lexical.html", "https://www.postgresql.org/docs/15/functions-matching.html"]}, +{"id": "SNP-007", "path": "keyValue", "engineFamily": "any", "serviceTypes": ["Athena", "AzureSQL", "BigQuery", "Clickhouse", "Databricks", "Doris", "Hive", "Impala", "Iomete", "MariaDB", "MicrosoftFabric", "Mssql", "Mysql", "Postgres", "Presto", "Redshift", "SingleStore", "Snowflake", "StarRocks", "Synapse", "Timescale", "Trino", "UnityCatalog"], "input": "result row values", "columnType": "name", "expectedOutcome": {"kind": "bound", "textMustNotContain": ["values read from an earlier result"]}, "failureImpact": "A key read from one result and written into a later statement lets a source row inject into the service account's next query.", "proof": "engineIndependent", "references": ["https://docs.sqlalchemy.org/en/20/core/sqlelement.html#sqlalchemy.sql.expression.text"], "note": "Every statement the job sends carries only binding values as parameters; names come through a join in the same statement."} +] diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-aggregate-forward.sql new file mode 100644 index 000000000000..575c6b453741 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-aggregate-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, COUNT(*) AS records +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +GROUP BY t0.`id` +ORDER BY records DESC, t0.`id` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-aggregate-inverse.sql new file mode 100644 index 000000000000..1c31d9e43c75 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-aggregate-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t0.`name`, COUNT(*) AS records +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +GROUP BY t0.`id`, t0.`name` +ORDER BY records DESC, t0.`id` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-count.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-count.sql new file mode 100644 index 000000000000..94c9e63443b1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..c54b5c312081 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id`, t1.`name` +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` = 31 + AND t1.`id` IS NOT NULL + AND t1.`id` > 1 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward.sql new file mode 100644 index 000000000000..5e1d8c892191 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-forward.sql @@ -0,0 +1,7 @@ +SELECT t0.`id`, t1.`id`, t1.`name` +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` = 31 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..0abba77b0eb1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`id` IS NOT NULL + AND t1.`id` > 25 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-page.sql new file mode 100644 index 000000000000..bdabd0ec2133 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse-page.sql @@ -0,0 +1,7 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse.sql new file mode 100644 index 000000000000..ca50f9cb0c4f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-expand-inverse.sql @@ -0,0 +1,7 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 2 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-find.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-find.sql new file mode 100644 index 000000000000..063d74b1de7c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`total` +FROM `shop`.`orders` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-open.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-open.sql new file mode 100644 index 000000000000..115763f085c0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/columnRelation-open.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`total` +FROM `shop`.`orders` t0 +WHERE t0.`id` = 31 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/compositeKey-count.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/compositeKey-count.sql new file mode 100644 index 000000000000..fe2d3aa2a703 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/compositeKey-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1 + FROM `shop`.`crm_customers` t0 + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/compositeKey-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/compositeKey-find-match.sql new file mode 100644 index 000000000000..6798e339b55b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/compositeKey-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name` +FROM `shop`.`crm_customers` t0 +WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND LOWER(t0.`name`) LIKE '%north%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/compositeKey-find.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/compositeKey-find.sql new file mode 100644 index 000000000000..496bcc7efaf0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/compositeKey-find.sql @@ -0,0 +1,5 @@ +SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name` +FROM `shop`.`crm_customers` t0 +WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/compositeKey-open.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/compositeKey-open.sql new file mode 100644 index 000000000000..4bb33faebf6d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/compositeKey-open.sql @@ -0,0 +1,6 @@ +SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name`, t1.`tier` +FROM `shop`.`crm_customers` t0 +LEFT JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` +WHERE t0.`tenant_id` = 'eu' + AND t0.`customer_id` = 42 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-organization-count.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-organization-count.sql new file mode 100644 index 000000000000..07e01b603a32 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-organization-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-organization-find.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-organization-find.sql new file mode 100644 index 000000000000..b7dfb7362fbb --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-organization-find.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-person-count.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-person-count.sql new file mode 100644 index 000000000000..7abd28fcbba2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-person-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-person-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-person-find-match.sql new file mode 100644 index 000000000000..95867683b269 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-person-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND LOWER(t0.`name`) LIKE '%ada%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-person-find.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-person-find.sql new file mode 100644 index 000000000000..b62d5e6b799a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-person-find.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-person-open.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-person-open.sql new file mode 100644 index 000000000000..6a37131ac406 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/filteredIdentity-person-open.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` = 3 + AND t0.`kind` = 'person' +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-forward.sql new file mode 100644 index 000000000000..13a17d79a77b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS r0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..cd6c832f55c4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..faef582e1560 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`tenant` AS r0, t0.`branch` AS r1 + FROM `shop`.`employees` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`tenant` IS NOT NULL + AND t0.`branch` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..43ef1a73aab6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`branch_id` AS k1, t1.`id` AS r0 + FROM `shop`.`branches` t0 + JOIN `shop`.`employees` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`branch` = t0.`branch_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`branch_id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..3e260b770043 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant` AS k0, t0.`order_no` AS k1, t1.`sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_lines` t1 ON t1.`tenant` = t0.`tenant` AND t1.`order_no` = t0.`order_no` + WHERE t0.`tenant` IS NOT NULL + AND t0.`order_no` IS NOT NULL + AND t1.`sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..32a510750339 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t2.`tenant` AS r0, t2.`order_no` AS r1 + FROM `shop`.`products` t0 + JOIN `shop`.`order_lines` t1 ON t1.`sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`tenant` = t1.`tenant` AND t2.`order_no` = t1.`order_no` + WHERE t0.`sku` IS NOT NULL + AND t2.`tenant` IS NOT NULL + AND t2.`order_no` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..2ccc475cdf3c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`customer_id` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_details` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`customer_id` IS NOT NULL + AND t1.`region` = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..ab9f9b5d58f5 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t2.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`order_details` t1 ON t1.`customer_id` = t0.`id` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`id` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t1.`region` = 'eu' + AND t2.`channel` = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..fb0ce7737a0c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..9da24a70a942 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`sku` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t2.`channel` = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..e7735bb0ef52 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`employer_id` AS r0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`employer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..b90722e8b0de --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkFilteredStart-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`parties` t0 + JOIN `shop`.`parties` t1 ON t1.`employer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' + AND t1.`id` IS NOT NULL + AND t1.`kind` = 'person' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..b24465e4fb7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..bf793e25aa17 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`sku` IS NOT NULL + AND t2.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-aggregate-forward.sql new file mode 100644 index 000000000000..22559137daff --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-aggregate-forward.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, COUNT(*) AS records +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` IS NOT NULL + AND t2.`sku` IS NOT NULL +GROUP BY t0.`id` +ORDER BY records DESC, t0.`id` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-aggregate-inverse.sql new file mode 100644 index 000000000000..1d569c2e2560 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-aggregate-inverse.sql @@ -0,0 +1,9 @@ +SELECT t0.`sku`, t0.`title`, COUNT(*) AS records +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` IS NOT NULL + AND t2.`id` IS NOT NULL +GROUP BY t0.`sku`, t0.`title` +ORDER BY records DESC, t0.`sku` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-count.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-count.sql new file mode 100644 index 000000000000..25fb5ffd6b3b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`sku` AS k0 + FROM `shop`.`products` t0 + WHERE t0.`sku` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..3a8fd8d10aab --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t2.`sku`, t2.`title` +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` = 1 + AND t2.`sku` IS NOT NULL + AND t2.`sku` > 'A-1' +ORDER BY t2.`sku` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward.sql new file mode 100644 index 000000000000..620ea42e8d81 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t2.`sku`, t2.`title` +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` = 1 + AND t2.`sku` IS NOT NULL +ORDER BY t2.`sku` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..ed49360a060c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`sku`, t2.`id` +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` = 'A-1' + AND t2.`id` IS NOT NULL + AND t2.`id` > 1 +ORDER BY t2.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse.sql new file mode 100644 index 000000000000..0e3d88801bc8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`sku`, t2.`id` +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` = 'A-1' + AND t2.`id` IS NOT NULL +ORDER BY t2.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-find.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-find.sql new file mode 100644 index 000000000000..51fee8f21343 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`channel` +FROM `shop`.`orders` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-open.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-open.sql new file mode 100644 index 000000000000..63450be89c31 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/linkTable-open.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`channel`, t1.`quantity` +FROM `shop`.`orders` t0 +LEFT JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +WHERE t0.`id` = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..caa609645aaa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL + AND t1.`id` > 0 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..ef10a2e91c16 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..258579d76366 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL + AND (t1.`ledger` > 'a' OR (t1.`ledger` = 'a' AND t1.`seq` > 25)) +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..df8f3e169168 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/repeatedContribution-count.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/repeatedContribution-count.sql new file mode 100644 index 000000000000..9df47e6a1f71 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/repeatedContribution-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/repeatedContribution-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/repeatedContribution-find-match.sql new file mode 100644 index 000000000000..999be1f469c6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/repeatedContribution-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL + AND LOWER(t0.`name`) LIKE '%grace%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/repeatedContribution-find.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/repeatedContribution-find.sql new file mode 100644 index 000000000000..fb0313523a74 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/repeatedContribution-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/repeatedContribution-open.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/repeatedContribution-open.sql new file mode 100644 index 000000000000..09d6177dfd88 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/repeatedContribution-open.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name`, t1.`city`, t1.`country` +FROM `shop`.`customers` t0 +LEFT JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/unfilteredIdentity-count.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/unfilteredIdentity-count.sql new file mode 100644 index 000000000000..9df47e6a1f71 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/unfilteredIdentity-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/unfilteredIdentity-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/unfilteredIdentity-find-match.sql new file mode 100644 index 000000000000..a16a35cca424 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/unfilteredIdentity-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name`, t0.`email` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL + AND LOWER(t0.`name`) LIKE '%hopper%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/unfilteredIdentity-find.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/unfilteredIdentity-find.sql new file mode 100644 index 000000000000..feb9d03d9ca8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/unfilteredIdentity-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`name`, t0.`email` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/bigquery/unfilteredIdentity-open.sql b/openmetadata-service/src/test/resources/ontology/statements/bigquery/unfilteredIdentity-open.sql new file mode 100644 index 000000000000..6fc3bc31386f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/bigquery/unfilteredIdentity-open.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`name`, t0.`email` +FROM `shop`.`customers` t0 +WHERE t0.`id` = 2 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-aggregate-forward.sql new file mode 100644 index 000000000000..575c6b453741 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-aggregate-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, COUNT(*) AS records +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +GROUP BY t0.`id` +ORDER BY records DESC, t0.`id` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-aggregate-inverse.sql new file mode 100644 index 000000000000..1c31d9e43c75 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-aggregate-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t0.`name`, COUNT(*) AS records +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +GROUP BY t0.`id`, t0.`name` +ORDER BY records DESC, t0.`id` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-count.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-count.sql new file mode 100644 index 000000000000..94c9e63443b1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..c54b5c312081 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id`, t1.`name` +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` = 31 + AND t1.`id` IS NOT NULL + AND t1.`id` > 1 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward.sql new file mode 100644 index 000000000000..5e1d8c892191 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-forward.sql @@ -0,0 +1,7 @@ +SELECT t0.`id`, t1.`id`, t1.`name` +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` = 31 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..0abba77b0eb1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`id` IS NOT NULL + AND t1.`id` > 25 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-page.sql new file mode 100644 index 000000000000..bdabd0ec2133 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse-page.sql @@ -0,0 +1,7 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse.sql new file mode 100644 index 000000000000..ca50f9cb0c4f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-expand-inverse.sql @@ -0,0 +1,7 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 2 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-find.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-find.sql new file mode 100644 index 000000000000..063d74b1de7c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`total` +FROM `shop`.`orders` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-open.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-open.sql new file mode 100644 index 000000000000..115763f085c0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/columnRelation-open.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`total` +FROM `shop`.`orders` t0 +WHERE t0.`id` = 31 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/compositeKey-count.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/compositeKey-count.sql new file mode 100644 index 000000000000..fe2d3aa2a703 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/compositeKey-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1 + FROM `shop`.`crm_customers` t0 + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/compositeKey-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/compositeKey-find-match.sql new file mode 100644 index 000000000000..6798e339b55b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/compositeKey-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name` +FROM `shop`.`crm_customers` t0 +WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND LOWER(t0.`name`) LIKE '%north%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/compositeKey-find.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/compositeKey-find.sql new file mode 100644 index 000000000000..496bcc7efaf0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/compositeKey-find.sql @@ -0,0 +1,5 @@ +SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name` +FROM `shop`.`crm_customers` t0 +WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/compositeKey-open.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/compositeKey-open.sql new file mode 100644 index 000000000000..4bb33faebf6d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/compositeKey-open.sql @@ -0,0 +1,6 @@ +SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name`, t1.`tier` +FROM `shop`.`crm_customers` t0 +LEFT JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` +WHERE t0.`tenant_id` = 'eu' + AND t0.`customer_id` = 42 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-organization-count.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-organization-count.sql new file mode 100644 index 000000000000..07e01b603a32 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-organization-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-organization-find.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-organization-find.sql new file mode 100644 index 000000000000..b7dfb7362fbb --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-organization-find.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-person-count.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-person-count.sql new file mode 100644 index 000000000000..7abd28fcbba2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-person-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-person-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-person-find-match.sql new file mode 100644 index 000000000000..95867683b269 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-person-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND LOWER(t0.`name`) LIKE '%ada%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-person-find.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-person-find.sql new file mode 100644 index 000000000000..b62d5e6b799a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-person-find.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-person-open.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-person-open.sql new file mode 100644 index 000000000000..6a37131ac406 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/filteredIdentity-person-open.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` = 3 + AND t0.`kind` = 'person' +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-forward.sql new file mode 100644 index 000000000000..13a17d79a77b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS r0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..cd6c832f55c4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..faef582e1560 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`tenant` AS r0, t0.`branch` AS r1 + FROM `shop`.`employees` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`tenant` IS NOT NULL + AND t0.`branch` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..43ef1a73aab6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`branch_id` AS k1, t1.`id` AS r0 + FROM `shop`.`branches` t0 + JOIN `shop`.`employees` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`branch` = t0.`branch_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`branch_id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..3e260b770043 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant` AS k0, t0.`order_no` AS k1, t1.`sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_lines` t1 ON t1.`tenant` = t0.`tenant` AND t1.`order_no` = t0.`order_no` + WHERE t0.`tenant` IS NOT NULL + AND t0.`order_no` IS NOT NULL + AND t1.`sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..32a510750339 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t2.`tenant` AS r0, t2.`order_no` AS r1 + FROM `shop`.`products` t0 + JOIN `shop`.`order_lines` t1 ON t1.`sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`tenant` = t1.`tenant` AND t2.`order_no` = t1.`order_no` + WHERE t0.`sku` IS NOT NULL + AND t2.`tenant` IS NOT NULL + AND t2.`order_no` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..2ccc475cdf3c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`customer_id` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_details` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`customer_id` IS NOT NULL + AND t1.`region` = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..ab9f9b5d58f5 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t2.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`order_details` t1 ON t1.`customer_id` = t0.`id` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`id` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t1.`region` = 'eu' + AND t2.`channel` = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..fb0ce7737a0c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..9da24a70a942 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`sku` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t2.`channel` = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..e7735bb0ef52 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`employer_id` AS r0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`employer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..b90722e8b0de --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkFilteredStart-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`parties` t0 + JOIN `shop`.`parties` t1 ON t1.`employer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' + AND t1.`id` IS NOT NULL + AND t1.`kind` = 'person' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..b24465e4fb7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..bf793e25aa17 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`sku` IS NOT NULL + AND t2.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-aggregate-forward.sql new file mode 100644 index 000000000000..22559137daff --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-aggregate-forward.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, COUNT(*) AS records +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` IS NOT NULL + AND t2.`sku` IS NOT NULL +GROUP BY t0.`id` +ORDER BY records DESC, t0.`id` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-aggregate-inverse.sql new file mode 100644 index 000000000000..1d569c2e2560 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-aggregate-inverse.sql @@ -0,0 +1,9 @@ +SELECT t0.`sku`, t0.`title`, COUNT(*) AS records +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` IS NOT NULL + AND t2.`id` IS NOT NULL +GROUP BY t0.`sku`, t0.`title` +ORDER BY records DESC, t0.`sku` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-count.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-count.sql new file mode 100644 index 000000000000..25fb5ffd6b3b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`sku` AS k0 + FROM `shop`.`products` t0 + WHERE t0.`sku` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..3a8fd8d10aab --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t2.`sku`, t2.`title` +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` = 1 + AND t2.`sku` IS NOT NULL + AND t2.`sku` > 'A-1' +ORDER BY t2.`sku` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward.sql new file mode 100644 index 000000000000..620ea42e8d81 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t2.`sku`, t2.`title` +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` = 1 + AND t2.`sku` IS NOT NULL +ORDER BY t2.`sku` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..ed49360a060c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`sku`, t2.`id` +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` = 'A-1' + AND t2.`id` IS NOT NULL + AND t2.`id` > 1 +ORDER BY t2.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse.sql new file mode 100644 index 000000000000..0e3d88801bc8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`sku`, t2.`id` +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` = 'A-1' + AND t2.`id` IS NOT NULL +ORDER BY t2.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-find.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-find.sql new file mode 100644 index 000000000000..51fee8f21343 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`channel` +FROM `shop`.`orders` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-open.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-open.sql new file mode 100644 index 000000000000..63450be89c31 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/linkTable-open.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`channel`, t1.`quantity` +FROM `shop`.`orders` t0 +LEFT JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +WHERE t0.`id` = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..caa609645aaa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL + AND t1.`id` > 0 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..ef10a2e91c16 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..258579d76366 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL + AND (t1.`ledger` > 'a' OR (t1.`ledger` = 'a' AND t1.`seq` > 25)) +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..df8f3e169168 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/repeatedContribution-count.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/repeatedContribution-count.sql new file mode 100644 index 000000000000..9df47e6a1f71 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/repeatedContribution-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/repeatedContribution-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/repeatedContribution-find-match.sql new file mode 100644 index 000000000000..999be1f469c6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/repeatedContribution-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL + AND LOWER(t0.`name`) LIKE '%grace%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/repeatedContribution-find.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/repeatedContribution-find.sql new file mode 100644 index 000000000000..fb0313523a74 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/repeatedContribution-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/repeatedContribution-open.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/repeatedContribution-open.sql new file mode 100644 index 000000000000..09d6177dfd88 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/repeatedContribution-open.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name`, t1.`city`, t1.`country` +FROM `shop`.`customers` t0 +LEFT JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/unfilteredIdentity-count.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/unfilteredIdentity-count.sql new file mode 100644 index 000000000000..9df47e6a1f71 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/unfilteredIdentity-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/unfilteredIdentity-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/unfilteredIdentity-find-match.sql new file mode 100644 index 000000000000..a16a35cca424 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/unfilteredIdentity-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name`, t0.`email` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL + AND LOWER(t0.`name`) LIKE '%hopper%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/unfilteredIdentity-find.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/unfilteredIdentity-find.sql new file mode 100644 index 000000000000..feb9d03d9ca8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/unfilteredIdentity-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`name`, t0.`email` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/clickhouse/unfilteredIdentity-open.sql b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/unfilteredIdentity-open.sql new file mode 100644 index 000000000000..6fc3bc31386f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/clickhouse/unfilteredIdentity-open.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`name`, t0.`email` +FROM `shop`.`customers` t0 +WHERE t0.`id` = 2 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-aggregate-forward.sql new file mode 100644 index 000000000000..575c6b453741 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-aggregate-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, COUNT(*) AS records +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +GROUP BY t0.`id` +ORDER BY records DESC, t0.`id` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-aggregate-inverse.sql new file mode 100644 index 000000000000..1c31d9e43c75 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-aggregate-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t0.`name`, COUNT(*) AS records +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +GROUP BY t0.`id`, t0.`name` +ORDER BY records DESC, t0.`id` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-count.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-count.sql new file mode 100644 index 000000000000..94c9e63443b1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..c54b5c312081 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id`, t1.`name` +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` = 31 + AND t1.`id` IS NOT NULL + AND t1.`id` > 1 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward.sql new file mode 100644 index 000000000000..5e1d8c892191 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-forward.sql @@ -0,0 +1,7 @@ +SELECT t0.`id`, t1.`id`, t1.`name` +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` = 31 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..0abba77b0eb1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`id` IS NOT NULL + AND t1.`id` > 25 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-page.sql new file mode 100644 index 000000000000..bdabd0ec2133 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse-page.sql @@ -0,0 +1,7 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse.sql new file mode 100644 index 000000000000..ca50f9cb0c4f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-expand-inverse.sql @@ -0,0 +1,7 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 2 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-find.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-find.sql new file mode 100644 index 000000000000..063d74b1de7c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`total` +FROM `shop`.`orders` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-open.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-open.sql new file mode 100644 index 000000000000..115763f085c0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/columnRelation-open.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`total` +FROM `shop`.`orders` t0 +WHERE t0.`id` = 31 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/compositeKey-count.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/compositeKey-count.sql new file mode 100644 index 000000000000..fe2d3aa2a703 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/compositeKey-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1 + FROM `shop`.`crm_customers` t0 + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/compositeKey-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/compositeKey-find-match.sql new file mode 100644 index 000000000000..6798e339b55b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/compositeKey-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name` +FROM `shop`.`crm_customers` t0 +WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND LOWER(t0.`name`) LIKE '%north%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/compositeKey-find.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/compositeKey-find.sql new file mode 100644 index 000000000000..496bcc7efaf0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/compositeKey-find.sql @@ -0,0 +1,5 @@ +SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name` +FROM `shop`.`crm_customers` t0 +WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/compositeKey-open.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/compositeKey-open.sql new file mode 100644 index 000000000000..4bb33faebf6d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/compositeKey-open.sql @@ -0,0 +1,6 @@ +SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name`, t1.`tier` +FROM `shop`.`crm_customers` t0 +LEFT JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` +WHERE t0.`tenant_id` = 'eu' + AND t0.`customer_id` = 42 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-organization-count.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-organization-count.sql new file mode 100644 index 000000000000..07e01b603a32 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-organization-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-organization-find.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-organization-find.sql new file mode 100644 index 000000000000..b7dfb7362fbb --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-organization-find.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-person-count.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-person-count.sql new file mode 100644 index 000000000000..7abd28fcbba2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-person-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-person-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-person-find-match.sql new file mode 100644 index 000000000000..95867683b269 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-person-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND LOWER(t0.`name`) LIKE '%ada%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-person-find.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-person-find.sql new file mode 100644 index 000000000000..b62d5e6b799a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-person-find.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-person-open.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-person-open.sql new file mode 100644 index 000000000000..6a37131ac406 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/filteredIdentity-person-open.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` = 3 + AND t0.`kind` = 'person' +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-forward.sql new file mode 100644 index 000000000000..13a17d79a77b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS r0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..cd6c832f55c4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..faef582e1560 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`tenant` AS r0, t0.`branch` AS r1 + FROM `shop`.`employees` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`tenant` IS NOT NULL + AND t0.`branch` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..43ef1a73aab6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`branch_id` AS k1, t1.`id` AS r0 + FROM `shop`.`branches` t0 + JOIN `shop`.`employees` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`branch` = t0.`branch_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`branch_id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..3e260b770043 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant` AS k0, t0.`order_no` AS k1, t1.`sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_lines` t1 ON t1.`tenant` = t0.`tenant` AND t1.`order_no` = t0.`order_no` + WHERE t0.`tenant` IS NOT NULL + AND t0.`order_no` IS NOT NULL + AND t1.`sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..32a510750339 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t2.`tenant` AS r0, t2.`order_no` AS r1 + FROM `shop`.`products` t0 + JOIN `shop`.`order_lines` t1 ON t1.`sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`tenant` = t1.`tenant` AND t2.`order_no` = t1.`order_no` + WHERE t0.`sku` IS NOT NULL + AND t2.`tenant` IS NOT NULL + AND t2.`order_no` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..2ccc475cdf3c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`customer_id` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_details` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`customer_id` IS NOT NULL + AND t1.`region` = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..ab9f9b5d58f5 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t2.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`order_details` t1 ON t1.`customer_id` = t0.`id` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`id` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t1.`region` = 'eu' + AND t2.`channel` = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..fb0ce7737a0c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..9da24a70a942 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`sku` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t2.`channel` = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..e7735bb0ef52 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`employer_id` AS r0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`employer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..b90722e8b0de --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkFilteredStart-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`parties` t0 + JOIN `shop`.`parties` t1 ON t1.`employer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' + AND t1.`id` IS NOT NULL + AND t1.`kind` = 'person' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..b24465e4fb7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..bf793e25aa17 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`sku` IS NOT NULL + AND t2.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-aggregate-forward.sql new file mode 100644 index 000000000000..22559137daff --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-aggregate-forward.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, COUNT(*) AS records +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` IS NOT NULL + AND t2.`sku` IS NOT NULL +GROUP BY t0.`id` +ORDER BY records DESC, t0.`id` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-aggregate-inverse.sql new file mode 100644 index 000000000000..1d569c2e2560 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-aggregate-inverse.sql @@ -0,0 +1,9 @@ +SELECT t0.`sku`, t0.`title`, COUNT(*) AS records +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` IS NOT NULL + AND t2.`id` IS NOT NULL +GROUP BY t0.`sku`, t0.`title` +ORDER BY records DESC, t0.`sku` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-count.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-count.sql new file mode 100644 index 000000000000..25fb5ffd6b3b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`sku` AS k0 + FROM `shop`.`products` t0 + WHERE t0.`sku` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..3a8fd8d10aab --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t2.`sku`, t2.`title` +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` = 1 + AND t2.`sku` IS NOT NULL + AND t2.`sku` > 'A-1' +ORDER BY t2.`sku` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward.sql new file mode 100644 index 000000000000..620ea42e8d81 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t2.`sku`, t2.`title` +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` = 1 + AND t2.`sku` IS NOT NULL +ORDER BY t2.`sku` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..ed49360a060c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`sku`, t2.`id` +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` = 'A-1' + AND t2.`id` IS NOT NULL + AND t2.`id` > 1 +ORDER BY t2.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse.sql new file mode 100644 index 000000000000..0e3d88801bc8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`sku`, t2.`id` +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` = 'A-1' + AND t2.`id` IS NOT NULL +ORDER BY t2.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-find.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-find.sql new file mode 100644 index 000000000000..51fee8f21343 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`channel` +FROM `shop`.`orders` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-open.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-open.sql new file mode 100644 index 000000000000..63450be89c31 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/linkTable-open.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`channel`, t1.`quantity` +FROM `shop`.`orders` t0 +LEFT JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +WHERE t0.`id` = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..caa609645aaa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL + AND t1.`id` > 0 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..ef10a2e91c16 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..258579d76366 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL + AND (t1.`ledger` > 'a' OR (t1.`ledger` = 'a' AND t1.`seq` > 25)) +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..df8f3e169168 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/repeatedContribution-count.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/repeatedContribution-count.sql new file mode 100644 index 000000000000..9df47e6a1f71 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/repeatedContribution-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/repeatedContribution-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/repeatedContribution-find-match.sql new file mode 100644 index 000000000000..999be1f469c6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/repeatedContribution-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL + AND LOWER(t0.`name`) LIKE '%grace%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/repeatedContribution-find.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/repeatedContribution-find.sql new file mode 100644 index 000000000000..fb0313523a74 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/repeatedContribution-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/repeatedContribution-open.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/repeatedContribution-open.sql new file mode 100644 index 000000000000..09d6177dfd88 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/repeatedContribution-open.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name`, t1.`city`, t1.`country` +FROM `shop`.`customers` t0 +LEFT JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/unfilteredIdentity-count.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/unfilteredIdentity-count.sql new file mode 100644 index 000000000000..9df47e6a1f71 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/unfilteredIdentity-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/unfilteredIdentity-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/unfilteredIdentity-find-match.sql new file mode 100644 index 000000000000..a16a35cca424 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/unfilteredIdentity-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name`, t0.`email` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL + AND LOWER(t0.`name`) LIKE '%hopper%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/unfilteredIdentity-find.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/unfilteredIdentity-find.sql new file mode 100644 index 000000000000..feb9d03d9ca8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/unfilteredIdentity-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`name`, t0.`email` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/mysql/unfilteredIdentity-open.sql b/openmetadata-service/src/test/resources/ontology/statements/mysql/unfilteredIdentity-open.sql new file mode 100644 index 000000000000..6fc3bc31386f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/mysql/unfilteredIdentity-open.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`name`, t0.`email` +FROM `shop`.`customers` t0 +WHERE t0.`id` = 2 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-aggregate-forward.sql new file mode 100644 index 000000000000..d842942dd7ea --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-aggregate-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.id, COUNT(*) AS records +FROM shop.orders t0 +JOIN shop.customers t1 ON t1.id = t0.customer_id +WHERE t0.id IS NOT NULL + AND t1.id IS NOT NULL +GROUP BY t0.id +ORDER BY records DESC, t0.id +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-aggregate-inverse.sql new file mode 100644 index 000000000000..950b35c90e09 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-aggregate-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t0.name, COUNT(*) AS records +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id IS NOT NULL + AND t1.id IS NOT NULL +GROUP BY t0.id, t0.name +ORDER BY records DESC, t0.id +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-count.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-count.sql new file mode 100644 index 000000000000..83741c2a370f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..2b445527e07d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.id, t1.name +FROM shop.orders t0 +JOIN shop.customers t1 ON t1.id = t0.customer_id +WHERE t0.id = 31 + AND t1.id IS NOT NULL + AND t1.id > 1 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward.sql new file mode 100644 index 000000000000..61c984e2a008 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-forward.sql @@ -0,0 +1,7 @@ +SELECT t0.id, t1.id, t1.name +FROM shop.orders t0 +JOIN shop.customers t1 ON t1.id = t0.customer_id +WHERE t0.id = 31 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..8c77c2edcb81 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.id +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id = 1 + AND t1.id IS NOT NULL + AND t1.id > 25 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-page.sql new file mode 100644 index 000000000000..a89cb7cb88b7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse-page.sql @@ -0,0 +1,7 @@ +SELECT t0.id, t1.id +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id = 1 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse.sql new file mode 100644 index 000000000000..2c19999be46d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-expand-inverse.sql @@ -0,0 +1,7 @@ +SELECT t0.id, t1.id +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id = 2 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-find.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-find.sql new file mode 100644 index 000000000000..9a3411cc1376 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-find.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.total +FROM shop.orders t0 +WHERE t0.id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-open.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-open.sql new file mode 100644 index 000000000000..c27b7a390234 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/columnRelation-open.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.total +FROM shop.orders t0 +WHERE t0.id = 31 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/compositeKey-count.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/compositeKey-count.sql new file mode 100644 index 000000000000..da03c284296e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/compositeKey-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/compositeKey-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/compositeKey-find-match.sql new file mode 100644 index 000000000000..323b1071dcaa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/compositeKey-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.tenant_id, t0.customer_id, t0.name +FROM shop.crm_customers t0 +WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND LOWER(t0.name) LIKE '%north%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/compositeKey-find.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/compositeKey-find.sql new file mode 100644 index 000000000000..68d2185d0b35 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/compositeKey-find.sql @@ -0,0 +1,5 @@ +SELECT t0.tenant_id, t0.customer_id, t0.name +FROM shop.crm_customers t0 +WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/compositeKey-open.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/compositeKey-open.sql new file mode 100644 index 000000000000..6d2f87d800e7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/compositeKey-open.sql @@ -0,0 +1,6 @@ +SELECT t0.tenant_id, t0.customer_id, t0.name, t1.tier +FROM shop.crm_customers t0 +LEFT JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id +WHERE t0.tenant_id = 'eu' + AND t0.customer_id = 42 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-organization-count.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-organization-count.sql new file mode 100644 index 000000000000..50bc2e503d6b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-organization-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'organization' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-organization-find.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-organization-find.sql new file mode 100644 index 000000000000..994c187eba42 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-organization-find.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name +FROM shop.parties t0 +WHERE t0.id IS NOT NULL + AND t0.kind = 'organization' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-person-count.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-person-count.sql new file mode 100644 index 000000000000..c8693d700612 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-person-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-person-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-person-find-match.sql new file mode 100644 index 000000000000..fc1b8ac510ed --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-person-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.id, t0.name +FROM shop.parties t0 +WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND LOWER(t0.name) LIKE '%ada%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-person-find.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-person-find.sql new file mode 100644 index 000000000000..792dd8ead52e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-person-find.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name +FROM shop.parties t0 +WHERE t0.id IS NOT NULL + AND t0.kind = 'person' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-person-open.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-person-open.sql new file mode 100644 index 000000000000..686e14bcd4d9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/filteredIdentity-person-open.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name +FROM shop.parties t0 +WHERE t0.id = 3 + AND t0.kind = 'person' +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-forward.sql new file mode 100644 index 000000000000..18badcb9bec0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS r0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..95a1714b7024 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.id AS r0 + FROM shop.customers t0 + JOIN shop.orders t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..eda40abc3f8d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.tenant AS r0, t0.branch AS r1 + FROM shop.employees t0 + WHERE t0.id IS NOT NULL + AND t0.tenant IS NOT NULL + AND t0.branch IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..c623bc9cb3dc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.branch_id AS k1, t1.id AS r0 + FROM shop.branches t0 + JOIN shop.employees t1 ON t1.tenant = t0.tenant_id AND t1.branch = t0.branch_id + WHERE t0.tenant_id IS NOT NULL + AND t0.branch_id IS NOT NULL + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..395b8fd7390e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.tenant AS k0, t0.order_no AS k1, t1.sku AS r0 + FROM shop.orders t0 + JOIN shop.order_lines t1 ON t1.tenant = t0.tenant AND t1.order_no = t0.order_no + WHERE t0.tenant IS NOT NULL + AND t0.order_no IS NOT NULL + AND t1.sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..144625529daa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t2.tenant AS r0, t2.order_no AS r1 + FROM shop.products t0 + JOIN shop.order_lines t1 ON t1.sku = t0.sku + JOIN shop.orders t2 ON t2.tenant = t1.tenant AND t2.order_no = t1.order_no + WHERE t0.sku IS NOT NULL + AND t2.tenant IS NOT NULL + AND t2.order_no IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..a41f5e5db0be --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.customer_id AS r0 + FROM shop.orders t0 + JOIN shop.order_details t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.channel = 'web' + AND t1.customer_id IS NOT NULL + AND t1.region = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..76152b181633 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t2.id AS r0 + FROM shop.customers t0 + JOIN shop.order_details t1 ON t1.customer_id = t0.id + JOIN shop.orders t2 ON t2.id = t1.order_id + WHERE t0.id IS NOT NULL + AND t2.id IS NOT NULL + AND t1.region = 'eu' + AND t2.channel = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..3bbdf68b2348 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.channel = 'web' + AND t1.product_sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..bcfdb0e8b82c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t2.id AS r0 + FROM shop.products t0 + JOIN shop.order_items t1 ON t1.product_sku = t0.sku + JOIN shop.orders t2 ON t2.id = t1.order_id + WHERE t0.sku IS NOT NULL + AND t2.id IS NOT NULL + AND t2.channel = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..c7195344bb2e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.employer_id AS r0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.employer_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..4ec96ff96e16 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkFilteredStart-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.id AS r0 + FROM shop.parties t0 + JOIN shop.parties t1 ON t1.employer_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.kind = 'organization' + AND t1.id IS NOT NULL + AND t1.kind = 'person' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..afefbe446c11 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..05a4b13d3306 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t2.id AS r0 + FROM shop.products t0 + JOIN shop.order_items t1 ON t1.product_sku = t0.sku + JOIN shop.orders t2 ON t2.id = t1.order_id + WHERE t0.sku IS NOT NULL + AND t2.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-aggregate-forward.sql new file mode 100644 index 000000000000..e7a28c70ead7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-aggregate-forward.sql @@ -0,0 +1,9 @@ +SELECT t0.id, COUNT(*) AS records +FROM shop.orders t0 +JOIN shop.order_items t1 ON t1.order_id = t0.id +JOIN shop.products t2 ON t2.sku = t1.product_sku +WHERE t0.id IS NOT NULL + AND t2.sku IS NOT NULL +GROUP BY t0.id +ORDER BY records DESC, t0.id +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-aggregate-inverse.sql new file mode 100644 index 000000000000..315b54f9c1f1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-aggregate-inverse.sql @@ -0,0 +1,9 @@ +SELECT t0.sku, t0.title, COUNT(*) AS records +FROM shop.products t0 +JOIN shop.order_items t1 ON t1.product_sku = t0.sku +JOIN shop.orders t2 ON t2.id = t1.order_id +WHERE t0.sku IS NOT NULL + AND t2.id IS NOT NULL +GROUP BY t0.sku, t0.title +ORDER BY records DESC, t0.sku +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-count.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-count.sql new file mode 100644 index 000000000000..85a0316db527 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.sku AS k0 + FROM shop.products t0 + WHERE t0.sku IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..f7d5dd202dad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.id, t2.sku, t2.title +FROM shop.orders t0 +JOIN shop.order_items t1 ON t1.order_id = t0.id +JOIN shop.products t2 ON t2.sku = t1.product_sku +WHERE t0.id = 1 + AND t2.sku IS NOT NULL + AND t2.sku > 'A-1' +ORDER BY t2.sku +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward.sql new file mode 100644 index 000000000000..b14c19c82e04 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t2.sku, t2.title +FROM shop.orders t0 +JOIN shop.order_items t1 ON t1.order_id = t0.id +JOIN shop.products t2 ON t2.sku = t1.product_sku +WHERE t0.id = 1 + AND t2.sku IS NOT NULL +ORDER BY t2.sku +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..31db3cf3687b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.sku, t2.id +FROM shop.products t0 +JOIN shop.order_items t1 ON t1.product_sku = t0.sku +JOIN shop.orders t2 ON t2.id = t1.order_id +WHERE t0.sku = 'A-1' + AND t2.id IS NOT NULL + AND t2.id > 1 +ORDER BY t2.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse.sql new file mode 100644 index 000000000000..9e5493c904e4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.sku, t2.id +FROM shop.products t0 +JOIN shop.order_items t1 ON t1.product_sku = t0.sku +JOIN shop.orders t2 ON t2.id = t1.order_id +WHERE t0.sku = 'A-1' + AND t2.id IS NOT NULL +ORDER BY t2.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-find.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-find.sql new file mode 100644 index 000000000000..df0a34a86e04 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-find.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.channel +FROM shop.orders t0 +WHERE t0.id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-open.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-open.sql new file mode 100644 index 000000000000..34dd90e044f1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/linkTable-open.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.channel, t1.quantity +FROM shop.orders t0 +LEFT JOIN shop.order_items t1 ON t1.order_id = t0.id +WHERE t0.id = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..477618a62c9c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.ledger, t0.seq, t1.id, t1.name +FROM shop.entries t0 +JOIN shop.accounts t1 ON t1.id = t0.account_id +WHERE t0.ledger = 'b' + AND t0.seq = 7 + AND t1.id IS NOT NULL + AND t1.id > 0 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..53c8af0352a6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.ledger, t0.seq, t1.id, t1.name +FROM shop.entries t0 +JOIN shop.accounts t1 ON t1.id = t0.account_id +WHERE t0.ledger = 'b' + AND t0.seq = 7 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..e70d76fc94d0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.id, t1.ledger, t1.seq +FROM shop.accounts t0 +JOIN shop.entries t1 ON t1.account_id = t0.id +WHERE t0.id = 1 + AND t1.ledger IS NOT NULL + AND t1.seq IS NOT NULL + AND (t1.ledger > 'a' OR (t1.ledger = 'a' AND t1.seq > 25)) +ORDER BY t1.ledger, t1.seq +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..57fd96c978bc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.ledger, t1.seq +FROM shop.accounts t0 +JOIN shop.entries t1 ON t1.account_id = t0.id +WHERE t0.id = 1 + AND t1.ledger IS NOT NULL + AND t1.seq IS NOT NULL +ORDER BY t1.ledger, t1.seq +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/repeatedContribution-count.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/repeatedContribution-count.sql new file mode 100644 index 000000000000..d9e3abbd242b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/repeatedContribution-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/repeatedContribution-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/repeatedContribution-find-match.sql new file mode 100644 index 000000000000..9b1c7fd6e8df --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/repeatedContribution-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name +FROM shop.customers t0 +WHERE t0.id IS NOT NULL + AND LOWER(t0.name) LIKE '%grace%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/repeatedContribution-find.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/repeatedContribution-find.sql new file mode 100644 index 000000000000..98769f319568 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/repeatedContribution-find.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.name +FROM shop.customers t0 +WHERE t0.id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/repeatedContribution-open.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/repeatedContribution-open.sql new file mode 100644 index 000000000000..09c976b6b1ed --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/repeatedContribution-open.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name, t1.city, t1.country +FROM shop.customers t0 +LEFT JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id +WHERE t0.id = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/unfilteredIdentity-count.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/unfilteredIdentity-count.sql new file mode 100644 index 000000000000..d9e3abbd242b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/unfilteredIdentity-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/unfilteredIdentity-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/unfilteredIdentity-find-match.sql new file mode 100644 index 000000000000..be09f98e3168 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/unfilteredIdentity-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name, t0.email +FROM shop.customers t0 +WHERE t0.id IS NOT NULL + AND LOWER(t0.name) LIKE '%hopper%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/unfilteredIdentity-find.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/unfilteredIdentity-find.sql new file mode 100644 index 000000000000..946d50c7c7ee --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/unfilteredIdentity-find.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.name, t0.email +FROM shop.customers t0 +WHERE t0.id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/postgres/unfilteredIdentity-open.sql b/openmetadata-service/src/test/resources/ontology/statements/postgres/unfilteredIdentity-open.sql new file mode 100644 index 000000000000..cc3ba0a3efcd --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/postgres/unfilteredIdentity-open.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.name, t0.email +FROM shop.customers t0 +WHERE t0.id = 2 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-aggregate-forward.sql new file mode 100644 index 000000000000..d842942dd7ea --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-aggregate-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.id, COUNT(*) AS records +FROM shop.orders t0 +JOIN shop.customers t1 ON t1.id = t0.customer_id +WHERE t0.id IS NOT NULL + AND t1.id IS NOT NULL +GROUP BY t0.id +ORDER BY records DESC, t0.id +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-aggregate-inverse.sql new file mode 100644 index 000000000000..950b35c90e09 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-aggregate-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t0.name, COUNT(*) AS records +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id IS NOT NULL + AND t1.id IS NOT NULL +GROUP BY t0.id, t0.name +ORDER BY records DESC, t0.id +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-count.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-count.sql new file mode 100644 index 000000000000..83741c2a370f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..2b445527e07d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.id, t1.name +FROM shop.orders t0 +JOIN shop.customers t1 ON t1.id = t0.customer_id +WHERE t0.id = 31 + AND t1.id IS NOT NULL + AND t1.id > 1 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward.sql new file mode 100644 index 000000000000..61c984e2a008 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-forward.sql @@ -0,0 +1,7 @@ +SELECT t0.id, t1.id, t1.name +FROM shop.orders t0 +JOIN shop.customers t1 ON t1.id = t0.customer_id +WHERE t0.id = 31 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..8c77c2edcb81 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.id +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id = 1 + AND t1.id IS NOT NULL + AND t1.id > 25 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-page.sql new file mode 100644 index 000000000000..a89cb7cb88b7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse-page.sql @@ -0,0 +1,7 @@ +SELECT t0.id, t1.id +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id = 1 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse.sql new file mode 100644 index 000000000000..2c19999be46d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-expand-inverse.sql @@ -0,0 +1,7 @@ +SELECT t0.id, t1.id +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id = 2 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-find.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-find.sql new file mode 100644 index 000000000000..9a3411cc1376 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-find.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.total +FROM shop.orders t0 +WHERE t0.id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-open.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-open.sql new file mode 100644 index 000000000000..c27b7a390234 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/columnRelation-open.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.total +FROM shop.orders t0 +WHERE t0.id = 31 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/compositeKey-count.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/compositeKey-count.sql new file mode 100644 index 000000000000..da03c284296e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/compositeKey-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/compositeKey-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/compositeKey-find-match.sql new file mode 100644 index 000000000000..323b1071dcaa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/compositeKey-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.tenant_id, t0.customer_id, t0.name +FROM shop.crm_customers t0 +WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND LOWER(t0.name) LIKE '%north%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/compositeKey-find.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/compositeKey-find.sql new file mode 100644 index 000000000000..68d2185d0b35 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/compositeKey-find.sql @@ -0,0 +1,5 @@ +SELECT t0.tenant_id, t0.customer_id, t0.name +FROM shop.crm_customers t0 +WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/compositeKey-open.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/compositeKey-open.sql new file mode 100644 index 000000000000..6d2f87d800e7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/compositeKey-open.sql @@ -0,0 +1,6 @@ +SELECT t0.tenant_id, t0.customer_id, t0.name, t1.tier +FROM shop.crm_customers t0 +LEFT JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id +WHERE t0.tenant_id = 'eu' + AND t0.customer_id = 42 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-organization-count.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-organization-count.sql new file mode 100644 index 000000000000..50bc2e503d6b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-organization-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'organization' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-organization-find.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-organization-find.sql new file mode 100644 index 000000000000..994c187eba42 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-organization-find.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name +FROM shop.parties t0 +WHERE t0.id IS NOT NULL + AND t0.kind = 'organization' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-person-count.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-person-count.sql new file mode 100644 index 000000000000..c8693d700612 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-person-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-person-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-person-find-match.sql new file mode 100644 index 000000000000..fc1b8ac510ed --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-person-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.id, t0.name +FROM shop.parties t0 +WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND LOWER(t0.name) LIKE '%ada%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-person-find.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-person-find.sql new file mode 100644 index 000000000000..792dd8ead52e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-person-find.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name +FROM shop.parties t0 +WHERE t0.id IS NOT NULL + AND t0.kind = 'person' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-person-open.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-person-open.sql new file mode 100644 index 000000000000..686e14bcd4d9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/filteredIdentity-person-open.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name +FROM shop.parties t0 +WHERE t0.id = 3 + AND t0.kind = 'person' +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-forward.sql new file mode 100644 index 000000000000..18badcb9bec0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS r0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..95a1714b7024 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.id AS r0 + FROM shop.customers t0 + JOIN shop.orders t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..eda40abc3f8d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.tenant AS r0, t0.branch AS r1 + FROM shop.employees t0 + WHERE t0.id IS NOT NULL + AND t0.tenant IS NOT NULL + AND t0.branch IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..c623bc9cb3dc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.branch_id AS k1, t1.id AS r0 + FROM shop.branches t0 + JOIN shop.employees t1 ON t1.tenant = t0.tenant_id AND t1.branch = t0.branch_id + WHERE t0.tenant_id IS NOT NULL + AND t0.branch_id IS NOT NULL + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..395b8fd7390e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.tenant AS k0, t0.order_no AS k1, t1.sku AS r0 + FROM shop.orders t0 + JOIN shop.order_lines t1 ON t1.tenant = t0.tenant AND t1.order_no = t0.order_no + WHERE t0.tenant IS NOT NULL + AND t0.order_no IS NOT NULL + AND t1.sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..144625529daa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t2.tenant AS r0, t2.order_no AS r1 + FROM shop.products t0 + JOIN shop.order_lines t1 ON t1.sku = t0.sku + JOIN shop.orders t2 ON t2.tenant = t1.tenant AND t2.order_no = t1.order_no + WHERE t0.sku IS NOT NULL + AND t2.tenant IS NOT NULL + AND t2.order_no IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..a41f5e5db0be --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.customer_id AS r0 + FROM shop.orders t0 + JOIN shop.order_details t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.channel = 'web' + AND t1.customer_id IS NOT NULL + AND t1.region = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..76152b181633 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t2.id AS r0 + FROM shop.customers t0 + JOIN shop.order_details t1 ON t1.customer_id = t0.id + JOIN shop.orders t2 ON t2.id = t1.order_id + WHERE t0.id IS NOT NULL + AND t2.id IS NOT NULL + AND t1.region = 'eu' + AND t2.channel = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..3bbdf68b2348 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.channel = 'web' + AND t1.product_sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..bcfdb0e8b82c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t2.id AS r0 + FROM shop.products t0 + JOIN shop.order_items t1 ON t1.product_sku = t0.sku + JOIN shop.orders t2 ON t2.id = t1.order_id + WHERE t0.sku IS NOT NULL + AND t2.id IS NOT NULL + AND t2.channel = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..c7195344bb2e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.employer_id AS r0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.employer_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..4ec96ff96e16 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkFilteredStart-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.id AS r0 + FROM shop.parties t0 + JOIN shop.parties t1 ON t1.employer_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.kind = 'organization' + AND t1.id IS NOT NULL + AND t1.kind = 'person' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..afefbe446c11 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..05a4b13d3306 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t2.id AS r0 + FROM shop.products t0 + JOIN shop.order_items t1 ON t1.product_sku = t0.sku + JOIN shop.orders t2 ON t2.id = t1.order_id + WHERE t0.sku IS NOT NULL + AND t2.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-aggregate-forward.sql new file mode 100644 index 000000000000..e7a28c70ead7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-aggregate-forward.sql @@ -0,0 +1,9 @@ +SELECT t0.id, COUNT(*) AS records +FROM shop.orders t0 +JOIN shop.order_items t1 ON t1.order_id = t0.id +JOIN shop.products t2 ON t2.sku = t1.product_sku +WHERE t0.id IS NOT NULL + AND t2.sku IS NOT NULL +GROUP BY t0.id +ORDER BY records DESC, t0.id +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-aggregate-inverse.sql new file mode 100644 index 000000000000..315b54f9c1f1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-aggregate-inverse.sql @@ -0,0 +1,9 @@ +SELECT t0.sku, t0.title, COUNT(*) AS records +FROM shop.products t0 +JOIN shop.order_items t1 ON t1.product_sku = t0.sku +JOIN shop.orders t2 ON t2.id = t1.order_id +WHERE t0.sku IS NOT NULL + AND t2.id IS NOT NULL +GROUP BY t0.sku, t0.title +ORDER BY records DESC, t0.sku +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-count.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-count.sql new file mode 100644 index 000000000000..85a0316db527 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.sku AS k0 + FROM shop.products t0 + WHERE t0.sku IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..f7d5dd202dad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.id, t2.sku, t2.title +FROM shop.orders t0 +JOIN shop.order_items t1 ON t1.order_id = t0.id +JOIN shop.products t2 ON t2.sku = t1.product_sku +WHERE t0.id = 1 + AND t2.sku IS NOT NULL + AND t2.sku > 'A-1' +ORDER BY t2.sku +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward.sql new file mode 100644 index 000000000000..b14c19c82e04 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t2.sku, t2.title +FROM shop.orders t0 +JOIN shop.order_items t1 ON t1.order_id = t0.id +JOIN shop.products t2 ON t2.sku = t1.product_sku +WHERE t0.id = 1 + AND t2.sku IS NOT NULL +ORDER BY t2.sku +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..31db3cf3687b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.sku, t2.id +FROM shop.products t0 +JOIN shop.order_items t1 ON t1.product_sku = t0.sku +JOIN shop.orders t2 ON t2.id = t1.order_id +WHERE t0.sku = 'A-1' + AND t2.id IS NOT NULL + AND t2.id > 1 +ORDER BY t2.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse.sql new file mode 100644 index 000000000000..9e5493c904e4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.sku, t2.id +FROM shop.products t0 +JOIN shop.order_items t1 ON t1.product_sku = t0.sku +JOIN shop.orders t2 ON t2.id = t1.order_id +WHERE t0.sku = 'A-1' + AND t2.id IS NOT NULL +ORDER BY t2.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-find.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-find.sql new file mode 100644 index 000000000000..df0a34a86e04 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-find.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.channel +FROM shop.orders t0 +WHERE t0.id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-open.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-open.sql new file mode 100644 index 000000000000..34dd90e044f1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/linkTable-open.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.channel, t1.quantity +FROM shop.orders t0 +LEFT JOIN shop.order_items t1 ON t1.order_id = t0.id +WHERE t0.id = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..477618a62c9c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.ledger, t0.seq, t1.id, t1.name +FROM shop.entries t0 +JOIN shop.accounts t1 ON t1.id = t0.account_id +WHERE t0.ledger = 'b' + AND t0.seq = 7 + AND t1.id IS NOT NULL + AND t1.id > 0 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..53c8af0352a6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.ledger, t0.seq, t1.id, t1.name +FROM shop.entries t0 +JOIN shop.accounts t1 ON t1.id = t0.account_id +WHERE t0.ledger = 'b' + AND t0.seq = 7 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..e70d76fc94d0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.id, t1.ledger, t1.seq +FROM shop.accounts t0 +JOIN shop.entries t1 ON t1.account_id = t0.id +WHERE t0.id = 1 + AND t1.ledger IS NOT NULL + AND t1.seq IS NOT NULL + AND (t1.ledger > 'a' OR (t1.ledger = 'a' AND t1.seq > 25)) +ORDER BY t1.ledger, t1.seq +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..57fd96c978bc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.ledger, t1.seq +FROM shop.accounts t0 +JOIN shop.entries t1 ON t1.account_id = t0.id +WHERE t0.id = 1 + AND t1.ledger IS NOT NULL + AND t1.seq IS NOT NULL +ORDER BY t1.ledger, t1.seq +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/repeatedContribution-count.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/repeatedContribution-count.sql new file mode 100644 index 000000000000..d9e3abbd242b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/repeatedContribution-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/repeatedContribution-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/repeatedContribution-find-match.sql new file mode 100644 index 000000000000..9b1c7fd6e8df --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/repeatedContribution-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name +FROM shop.customers t0 +WHERE t0.id IS NOT NULL + AND LOWER(t0.name) LIKE '%grace%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/repeatedContribution-find.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/repeatedContribution-find.sql new file mode 100644 index 000000000000..98769f319568 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/repeatedContribution-find.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.name +FROM shop.customers t0 +WHERE t0.id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/repeatedContribution-open.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/repeatedContribution-open.sql new file mode 100644 index 000000000000..09c976b6b1ed --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/repeatedContribution-open.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name, t1.city, t1.country +FROM shop.customers t0 +LEFT JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id +WHERE t0.id = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/unfilteredIdentity-count.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/unfilteredIdentity-count.sql new file mode 100644 index 000000000000..d9e3abbd242b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/unfilteredIdentity-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/unfilteredIdentity-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/unfilteredIdentity-find-match.sql new file mode 100644 index 000000000000..be09f98e3168 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/unfilteredIdentity-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name, t0.email +FROM shop.customers t0 +WHERE t0.id IS NOT NULL + AND LOWER(t0.name) LIKE '%hopper%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/unfilteredIdentity-find.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/unfilteredIdentity-find.sql new file mode 100644 index 000000000000..946d50c7c7ee --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/unfilteredIdentity-find.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.name, t0.email +FROM shop.customers t0 +WHERE t0.id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/redshift/unfilteredIdentity-open.sql b/openmetadata-service/src/test/resources/ontology/statements/redshift/unfilteredIdentity-open.sql new file mode 100644 index 000000000000..cc3ba0a3efcd --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/redshift/unfilteredIdentity-open.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.name, t0.email +FROM shop.customers t0 +WHERE t0.id = 2 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-aggregate-forward.sql new file mode 100644 index 000000000000..236eaa6d2908 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-aggregate-forward.sql @@ -0,0 +1,8 @@ +SELECT t0."id", COUNT(*) AS records +FROM "shop"."orders" t0 +JOIN "shop"."customers" t1 ON t1."id" = t0."customer_id" +WHERE t0."id" IS NOT NULL + AND t1."id" IS NOT NULL +GROUP BY t0."id" +ORDER BY records DESC, t0."id" +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-aggregate-inverse.sql new file mode 100644 index 000000000000..429459073f34 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-aggregate-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0."id", t0."name", COUNT(*) AS records +FROM "shop"."customers" t0 +JOIN "shop"."orders" t1 ON t1."customer_id" = t0."id" +WHERE t0."id" IS NOT NULL + AND t1."id" IS NOT NULL +GROUP BY t0."id", t0."name" +ORDER BY records DESC, t0."id" +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-count.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-count.sql new file mode 100644 index 000000000000..825c6740ce76 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."orders" t0 + WHERE t0."id" IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..44ebc1759a54 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0."id", t1."id", t1."name" +FROM "shop"."orders" t0 +JOIN "shop"."customers" t1 ON t1."id" = t0."customer_id" +WHERE t0."id" = 31 + AND t1."id" IS NOT NULL + AND t1."id" > 1 +ORDER BY t1."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward.sql new file mode 100644 index 000000000000..e4cd7efefbd6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-forward.sql @@ -0,0 +1,7 @@ +SELECT t0."id", t1."id", t1."name" +FROM "shop"."orders" t0 +JOIN "shop"."customers" t1 ON t1."id" = t0."customer_id" +WHERE t0."id" = 31 + AND t1."id" IS NOT NULL +ORDER BY t1."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..854872594cc3 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0."id", t1."id" +FROM "shop"."customers" t0 +JOIN "shop"."orders" t1 ON t1."customer_id" = t0."id" +WHERE t0."id" = 1 + AND t1."id" IS NOT NULL + AND t1."id" > 25 +ORDER BY t1."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-page.sql new file mode 100644 index 000000000000..e1d4c121fff8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse-page.sql @@ -0,0 +1,7 @@ +SELECT t0."id", t1."id" +FROM "shop"."customers" t0 +JOIN "shop"."orders" t1 ON t1."customer_id" = t0."id" +WHERE t0."id" = 1 + AND t1."id" IS NOT NULL +ORDER BY t1."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse.sql new file mode 100644 index 000000000000..1c48dab6b659 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-expand-inverse.sql @@ -0,0 +1,7 @@ +SELECT t0."id", t1."id" +FROM "shop"."customers" t0 +JOIN "shop"."orders" t1 ON t1."customer_id" = t0."id" +WHERE t0."id" = 2 + AND t1."id" IS NOT NULL +ORDER BY t1."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-find.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-find.sql new file mode 100644 index 000000000000..67de5dfefde4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-find.sql @@ -0,0 +1,4 @@ +SELECT t0."id", t0."total" +FROM "shop"."orders" t0 +WHERE t0."id" IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-open.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-open.sql new file mode 100644 index 000000000000..4999c237c425 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/columnRelation-open.sql @@ -0,0 +1,4 @@ +SELECT t0."id", t0."total" +FROM "shop"."orders" t0 +WHERE t0."id" = 31 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/compositeKey-count.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/compositeKey-count.sql new file mode 100644 index 000000000000..15575712e87e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/compositeKey-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0."tenant_id" AS k0, t0."customer_id" AS k1 + FROM "shop"."crm_customers" t0 + WHERE t0."tenant_id" IS NOT NULL + AND t0."customer_id" IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/compositeKey-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/compositeKey-find-match.sql new file mode 100644 index 000000000000..6cf326025c17 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/compositeKey-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0."tenant_id", t0."customer_id", t0."name" +FROM "shop"."crm_customers" t0 +WHERE t0."tenant_id" IS NOT NULL + AND t0."customer_id" IS NOT NULL + AND LOWER(t0."name") LIKE '%north%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/compositeKey-find.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/compositeKey-find.sql new file mode 100644 index 000000000000..dc320c0a26fd --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/compositeKey-find.sql @@ -0,0 +1,5 @@ +SELECT t0."tenant_id", t0."customer_id", t0."name" +FROM "shop"."crm_customers" t0 +WHERE t0."tenant_id" IS NOT NULL + AND t0."customer_id" IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/compositeKey-open.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/compositeKey-open.sql new file mode 100644 index 000000000000..90fcfca477a4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/compositeKey-open.sql @@ -0,0 +1,6 @@ +SELECT t0."tenant_id", t0."customer_id", t0."name", t1."tier" +FROM "shop"."crm_customers" t0 +LEFT JOIN "shop"."crm_customer_profile" t1 ON t1."tenant" = t0."tenant_id" AND t1."customer" = t0."customer_id" +WHERE t0."tenant_id" = 'eu' + AND t0."customer_id" = 42 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-organization-count.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-organization-count.sql new file mode 100644 index 000000000000..71c603a04760 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-organization-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."parties" t0 + WHERE t0."id" IS NOT NULL + AND t0."kind" = 'organization' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-organization-find.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-organization-find.sql new file mode 100644 index 000000000000..5a838488f7c7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-organization-find.sql @@ -0,0 +1,5 @@ +SELECT t0."id", t0."name" +FROM "shop"."parties" t0 +WHERE t0."id" IS NOT NULL + AND t0."kind" = 'organization' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-person-count.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-person-count.sql new file mode 100644 index 000000000000..f43deb378c33 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-person-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."parties" t0 + WHERE t0."id" IS NOT NULL + AND t0."kind" = 'person' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-person-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-person-find-match.sql new file mode 100644 index 000000000000..c67487397f46 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-person-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0."id", t0."name" +FROM "shop"."parties" t0 +WHERE t0."id" IS NOT NULL + AND t0."kind" = 'person' + AND LOWER(t0."name") LIKE '%ada%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-person-find.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-person-find.sql new file mode 100644 index 000000000000..dad3a4d0fd49 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-person-find.sql @@ -0,0 +1,5 @@ +SELECT t0."id", t0."name" +FROM "shop"."parties" t0 +WHERE t0."id" IS NOT NULL + AND t0."kind" = 'person' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-person-open.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-person-open.sql new file mode 100644 index 000000000000..46d2d03d2a08 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/filteredIdentity-person-open.sql @@ -0,0 +1,5 @@ +SELECT t0."id", t0."name" +FROM "shop"."parties" t0 +WHERE t0."id" = 3 + AND t0."kind" = 'person' +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-forward.sql new file mode 100644 index 000000000000..0dd502d3c1d6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t0."customer_id" AS r0 + FROM "shop"."orders" t0 + WHERE t0."id" IS NOT NULL + AND t0."customer_id" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..a7b3a037a5ef --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t1."id" AS r0 + FROM "shop"."customers" t0 + JOIN "shop"."orders" t1 ON t1."customer_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t1."id" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..643758cb531d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t0."tenant" AS r0, t0."branch" AS r1 + FROM "shop"."employees" t0 + WHERE t0."id" IS NOT NULL + AND t0."tenant" IS NOT NULL + AND t0."branch" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..aaa7063ff81d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."tenant_id" AS k0, t0."branch_id" AS k1, t1."id" AS r0 + FROM "shop"."branches" t0 + JOIN "shop"."employees" t1 ON t1."tenant" = t0."tenant_id" AND t1."branch" = t0."branch_id" + WHERE t0."tenant_id" IS NOT NULL + AND t0."branch_id" IS NOT NULL + AND t1."id" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..7326af5b863d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."tenant" AS k0, t0."order_no" AS k1, t1."sku" AS r0 + FROM "shop"."orders" t0 + JOIN "shop"."order_lines" t1 ON t1."tenant" = t0."tenant" AND t1."order_no" = t0."order_no" + WHERE t0."tenant" IS NOT NULL + AND t0."order_no" IS NOT NULL + AND t1."sku" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..77dbb5c3f8f1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."sku" AS k0, t2."tenant" AS r0, t2."order_no" AS r1 + FROM "shop"."products" t0 + JOIN "shop"."order_lines" t1 ON t1."sku" = t0."sku" + JOIN "shop"."orders" t2 ON t2."tenant" = t1."tenant" AND t2."order_no" = t1."order_no" + WHERE t0."sku" IS NOT NULL + AND t2."tenant" IS NOT NULL + AND t2."order_no" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..3dff3943ff49 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t1."customer_id" AS r0 + FROM "shop"."orders" t0 + JOIN "shop"."order_details" t1 ON t1."order_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t0."channel" = 'web' + AND t1."customer_id" IS NOT NULL + AND t1."region" = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..e4d45a965974 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t2."id" AS r0 + FROM "shop"."customers" t0 + JOIN "shop"."order_details" t1 ON t1."customer_id" = t0."id" + JOIN "shop"."orders" t2 ON t2."id" = t1."order_id" + WHERE t0."id" IS NOT NULL + AND t2."id" IS NOT NULL + AND t1."region" = 'eu' + AND t2."channel" = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..c9c816141b6e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t1."product_sku" AS r0 + FROM "shop"."orders" t0 + JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t0."channel" = 'web' + AND t1."product_sku" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..86070ee987fb --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."sku" AS k0, t2."id" AS r0 + FROM "shop"."products" t0 + JOIN "shop"."order_items" t1 ON t1."product_sku" = t0."sku" + JOIN "shop"."orders" t2 ON t2."id" = t1."order_id" + WHERE t0."sku" IS NOT NULL + AND t2."id" IS NOT NULL + AND t2."channel" = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..55f8de72484b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t0."employer_id" AS r0 + FROM "shop"."parties" t0 + WHERE t0."id" IS NOT NULL + AND t0."kind" = 'person' + AND t0."employer_id" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..46cde6f2cf8a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkFilteredStart-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t1."id" AS r0 + FROM "shop"."parties" t0 + JOIN "shop"."parties" t1 ON t1."employer_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t0."kind" = 'organization' + AND t1."id" IS NOT NULL + AND t1."kind" = 'person' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..8c8356037a43 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."id" AS k0, t1."product_sku" AS r0 + FROM "shop"."orders" t0 + JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" + WHERE t0."id" IS NOT NULL + AND t1."product_sku" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..0e5a88e96cc3 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0."sku" AS k0, t2."id" AS r0 + FROM "shop"."products" t0 + JOIN "shop"."order_items" t1 ON t1."product_sku" = t0."sku" + JOIN "shop"."orders" t2 ON t2."id" = t1."order_id" + WHERE t0."sku" IS NOT NULL + AND t2."id" IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-aggregate-forward.sql new file mode 100644 index 000000000000..5701d972d64b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-aggregate-forward.sql @@ -0,0 +1,9 @@ +SELECT t0."id", COUNT(*) AS records +FROM "shop"."orders" t0 +JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" +JOIN "shop"."products" t2 ON t2."sku" = t1."product_sku" +WHERE t0."id" IS NOT NULL + AND t2."sku" IS NOT NULL +GROUP BY t0."id" +ORDER BY records DESC, t0."id" +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-aggregate-inverse.sql new file mode 100644 index 000000000000..cac6543f2ba7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-aggregate-inverse.sql @@ -0,0 +1,9 @@ +SELECT t0."sku", t0."title", COUNT(*) AS records +FROM "shop"."products" t0 +JOIN "shop"."order_items" t1 ON t1."product_sku" = t0."sku" +JOIN "shop"."orders" t2 ON t2."id" = t1."order_id" +WHERE t0."sku" IS NOT NULL + AND t2."id" IS NOT NULL +GROUP BY t0."sku", t0."title" +ORDER BY records DESC, t0."sku" +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-count.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-count.sql new file mode 100644 index 000000000000..fc4b698f1b31 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0."sku" AS k0 + FROM "shop"."products" t0 + WHERE t0."sku" IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..541e45516669 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0."id", t2."sku", t2."title" +FROM "shop"."orders" t0 +JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" +JOIN "shop"."products" t2 ON t2."sku" = t1."product_sku" +WHERE t0."id" = 1 + AND t2."sku" IS NOT NULL + AND t2."sku" > 'A-1' +ORDER BY t2."sku" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward.sql new file mode 100644 index 000000000000..15e52ec06a0c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0."id", t2."sku", t2."title" +FROM "shop"."orders" t0 +JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" +JOIN "shop"."products" t2 ON t2."sku" = t1."product_sku" +WHERE t0."id" = 1 + AND t2."sku" IS NOT NULL +ORDER BY t2."sku" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..f142d63f5425 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0."sku", t2."id" +FROM "shop"."products" t0 +JOIN "shop"."order_items" t1 ON t1."product_sku" = t0."sku" +JOIN "shop"."orders" t2 ON t2."id" = t1."order_id" +WHERE t0."sku" = 'A-1' + AND t2."id" IS NOT NULL + AND t2."id" > 1 +ORDER BY t2."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse.sql new file mode 100644 index 000000000000..3ba39b2ed7b1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0."sku", t2."id" +FROM "shop"."products" t0 +JOIN "shop"."order_items" t1 ON t1."product_sku" = t0."sku" +JOIN "shop"."orders" t2 ON t2."id" = t1."order_id" +WHERE t0."sku" = 'A-1' + AND t2."id" IS NOT NULL +ORDER BY t2."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-find.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-find.sql new file mode 100644 index 000000000000..aa490c7d33c8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-find.sql @@ -0,0 +1,4 @@ +SELECT t0."id", t0."channel" +FROM "shop"."orders" t0 +WHERE t0."id" IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-open.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-open.sql new file mode 100644 index 000000000000..39d791f9cff8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/linkTable-open.sql @@ -0,0 +1,5 @@ +SELECT t0."id", t0."channel", t1."quantity" +FROM "shop"."orders" t0 +LEFT JOIN "shop"."order_items" t1 ON t1."order_id" = t0."id" +WHERE t0."id" = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..b41322735235 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0."ledger", t0."seq", t1."id", t1."name" +FROM "shop"."entries" t0 +JOIN "shop"."accounts" t1 ON t1."id" = t0."account_id" +WHERE t0."ledger" = 'b' + AND t0."seq" = 7 + AND t1."id" IS NOT NULL + AND t1."id" > 0 +ORDER BY t1."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..25d42fa073c6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0."ledger", t0."seq", t1."id", t1."name" +FROM "shop"."entries" t0 +JOIN "shop"."accounts" t1 ON t1."id" = t0."account_id" +WHERE t0."ledger" = 'b' + AND t0."seq" = 7 + AND t1."id" IS NOT NULL +ORDER BY t1."id" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..778b5cc285e1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0."id", t1."ledger", t1."seq" +FROM "shop"."accounts" t0 +JOIN "shop"."entries" t1 ON t1."account_id" = t0."id" +WHERE t0."id" = 1 + AND t1."ledger" IS NOT NULL + AND t1."seq" IS NOT NULL + AND (t1."ledger" > 'a' OR (t1."ledger" = 'a' AND t1."seq" > 25)) +ORDER BY t1."ledger", t1."seq" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..5dc8e4357ac9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0."id", t1."ledger", t1."seq" +FROM "shop"."accounts" t0 +JOIN "shop"."entries" t1 ON t1."account_id" = t0."id" +WHERE t0."id" = 1 + AND t1."ledger" IS NOT NULL + AND t1."seq" IS NOT NULL +ORDER BY t1."ledger", t1."seq" +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/repeatedContribution-count.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/repeatedContribution-count.sql new file mode 100644 index 000000000000..71352184439d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/repeatedContribution-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."customers" t0 + WHERE t0."id" IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/repeatedContribution-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/repeatedContribution-find-match.sql new file mode 100644 index 000000000000..ff2fe2a3ab92 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/repeatedContribution-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0."id", t0."name" +FROM "shop"."customers" t0 +WHERE t0."id" IS NOT NULL + AND LOWER(t0."name") LIKE '%grace%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/repeatedContribution-find.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/repeatedContribution-find.sql new file mode 100644 index 000000000000..2b37aedf3395 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/repeatedContribution-find.sql @@ -0,0 +1,4 @@ +SELECT t0."id", t0."name" +FROM "shop"."customers" t0 +WHERE t0."id" IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/repeatedContribution-open.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/repeatedContribution-open.sql new file mode 100644 index 000000000000..e300e5b1f110 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/repeatedContribution-open.sql @@ -0,0 +1,5 @@ +SELECT t0."id", t0."name", t1."city", t1."country" +FROM "shop"."customers" t0 +LEFT JOIN "shop"."customer_addresses" t1 ON t1."customer_id" = t0."id" +WHERE t0."id" = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/unfilteredIdentity-count.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/unfilteredIdentity-count.sql new file mode 100644 index 000000000000..71352184439d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/unfilteredIdentity-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0."id" AS k0 + FROM "shop"."customers" t0 + WHERE t0."id" IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/unfilteredIdentity-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/unfilteredIdentity-find-match.sql new file mode 100644 index 000000000000..b3da2f0f3e2e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/unfilteredIdentity-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0."id", t0."name", t0."email" +FROM "shop"."customers" t0 +WHERE t0."id" IS NOT NULL + AND LOWER(t0."name") LIKE '%hopper%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/unfilteredIdentity-find.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/unfilteredIdentity-find.sql new file mode 100644 index 000000000000..c2469c65bb7d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/unfilteredIdentity-find.sql @@ -0,0 +1,4 @@ +SELECT t0."id", t0."name", t0."email" +FROM "shop"."customers" t0 +WHERE t0."id" IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/snowflake/unfilteredIdentity-open.sql b/openmetadata-service/src/test/resources/ontology/statements/snowflake/unfilteredIdentity-open.sql new file mode 100644 index 000000000000..58e59698d2e9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/snowflake/unfilteredIdentity-open.sql @@ -0,0 +1,4 @@ +SELECT t0."id", t0."name", t0."email" +FROM "shop"."customers" t0 +WHERE t0."id" = 2 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-aggregate-forward.sql new file mode 100644 index 000000000000..575c6b453741 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-aggregate-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, COUNT(*) AS records +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +GROUP BY t0.`id` +ORDER BY records DESC, t0.`id` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-aggregate-inverse.sql new file mode 100644 index 000000000000..1c31d9e43c75 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-aggregate-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t0.`name`, COUNT(*) AS records +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +GROUP BY t0.`id`, t0.`name` +ORDER BY records DESC, t0.`id` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-count.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-count.sql new file mode 100644 index 000000000000..94c9e63443b1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..c54b5c312081 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id`, t1.`name` +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` = 31 + AND t1.`id` IS NOT NULL + AND t1.`id` > 1 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward.sql new file mode 100644 index 000000000000..5e1d8c892191 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-forward.sql @@ -0,0 +1,7 @@ +SELECT t0.`id`, t1.`id`, t1.`name` +FROM `shop`.`orders` t0 +JOIN `shop`.`customers` t1 ON t1.`id` = t0.`customer_id` +WHERE t0.`id` = 31 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..0abba77b0eb1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`id` IS NOT NULL + AND t1.`id` > 25 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-page.sql new file mode 100644 index 000000000000..bdabd0ec2133 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse-page.sql @@ -0,0 +1,7 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse.sql new file mode 100644 index 000000000000..ca50f9cb0c4f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-expand-inverse.sql @@ -0,0 +1,7 @@ +SELECT t0.`id`, t1.`id` +FROM `shop`.`customers` t0 +JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 2 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-find.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-find.sql new file mode 100644 index 000000000000..063d74b1de7c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`total` +FROM `shop`.`orders` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-open.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-open.sql new file mode 100644 index 000000000000..115763f085c0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/columnRelation-open.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`total` +FROM `shop`.`orders` t0 +WHERE t0.`id` = 31 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/compositeKey-count.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/compositeKey-count.sql new file mode 100644 index 000000000000..fe2d3aa2a703 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/compositeKey-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`customer_id` AS k1 + FROM `shop`.`crm_customers` t0 + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/compositeKey-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/compositeKey-find-match.sql new file mode 100644 index 000000000000..6798e339b55b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/compositeKey-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name` +FROM `shop`.`crm_customers` t0 +WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL + AND LOWER(t0.`name`) LIKE '%north%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/compositeKey-find.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/compositeKey-find.sql new file mode 100644 index 000000000000..496bcc7efaf0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/compositeKey-find.sql @@ -0,0 +1,5 @@ +SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name` +FROM `shop`.`crm_customers` t0 +WHERE t0.`tenant_id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/compositeKey-open.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/compositeKey-open.sql new file mode 100644 index 000000000000..4bb33faebf6d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/compositeKey-open.sql @@ -0,0 +1,6 @@ +SELECT t0.`tenant_id`, t0.`customer_id`, t0.`name`, t1.`tier` +FROM `shop`.`crm_customers` t0 +LEFT JOIN `shop`.`crm_customer_profile` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`customer` = t0.`customer_id` +WHERE t0.`tenant_id` = 'eu' + AND t0.`customer_id` = 42 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-organization-count.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-organization-count.sql new file mode 100644 index 000000000000..07e01b603a32 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-organization-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-organization-find.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-organization-find.sql new file mode 100644 index 000000000000..b7dfb7362fbb --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-organization-find.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-person-count.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-person-count.sql new file mode 100644 index 000000000000..7abd28fcbba2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-person-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-person-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-person-find-match.sql new file mode 100644 index 000000000000..95867683b269 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-person-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND LOWER(t0.`name`) LIKE '%ada%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-person-find.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-person-find.sql new file mode 100644 index 000000000000..b62d5e6b799a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-person-find.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-person-open.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-person-open.sql new file mode 100644 index 000000000000..6a37131ac406 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/filteredIdentity-person-open.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`parties` t0 +WHERE t0.`id` = 3 + AND t0.`kind` = 'person' +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-forward.sql new file mode 100644 index 000000000000..13a17d79a77b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`customer_id` AS r0 + FROM `shop`.`orders` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`customer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..cd6c832f55c4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`orders` t1 ON t1.`customer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..faef582e1560 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`tenant` AS r0, t0.`branch` AS r1 + FROM `shop`.`employees` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`tenant` IS NOT NULL + AND t0.`branch` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..43ef1a73aab6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant_id` AS k0, t0.`branch_id` AS k1, t1.`id` AS r0 + FROM `shop`.`branches` t0 + JOIN `shop`.`employees` t1 ON t1.`tenant` = t0.`tenant_id` AND t1.`branch` = t0.`branch_id` + WHERE t0.`tenant_id` IS NOT NULL + AND t0.`branch_id` IS NOT NULL + AND t1.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..3e260b770043 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`tenant` AS k0, t0.`order_no` AS k1, t1.`sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_lines` t1 ON t1.`tenant` = t0.`tenant` AND t1.`order_no` = t0.`order_no` + WHERE t0.`tenant` IS NOT NULL + AND t0.`order_no` IS NOT NULL + AND t1.`sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..32a510750339 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t2.`tenant` AS r0, t2.`order_no` AS r1 + FROM `shop`.`products` t0 + JOIN `shop`.`order_lines` t1 ON t1.`sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`tenant` = t1.`tenant` AND t2.`order_no` = t1.`order_no` + WHERE t0.`sku` IS NOT NULL + AND t2.`tenant` IS NOT NULL + AND t2.`order_no` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..2ccc475cdf3c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`customer_id` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_details` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`customer_id` IS NOT NULL + AND t1.`region` = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..ab9f9b5d58f5 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t2.`id` AS r0 + FROM `shop`.`customers` t0 + JOIN `shop`.`order_details` t1 ON t1.`customer_id` = t0.`id` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`id` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t1.`region` = 'eu' + AND t2.`channel` = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..fb0ce7737a0c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`channel` = 'web' + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..9da24a70a942 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`sku` IS NOT NULL + AND t2.`id` IS NOT NULL + AND t2.`channel` = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..e7735bb0ef52 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t0.`employer_id` AS r0 + FROM `shop`.`parties` t0 + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'person' + AND t0.`employer_id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..b90722e8b0de --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkFilteredStart-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`id` AS r0 + FROM `shop`.`parties` t0 + JOIN `shop`.`parties` t1 ON t1.`employer_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t0.`kind` = 'organization' + AND t1.`id` IS NOT NULL + AND t1.`kind` = 'person' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..b24465e4fb7f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`id` AS k0, t1.`product_sku` AS r0 + FROM `shop`.`orders` t0 + JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` + WHERE t0.`id` IS NOT NULL + AND t1.`product_sku` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..bf793e25aa17 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.`sku` AS k0, t2.`id` AS r0 + FROM `shop`.`products` t0 + JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` + JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` + WHERE t0.`sku` IS NOT NULL + AND t2.`id` IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-aggregate-forward.sql new file mode 100644 index 000000000000..22559137daff --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-aggregate-forward.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, COUNT(*) AS records +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` IS NOT NULL + AND t2.`sku` IS NOT NULL +GROUP BY t0.`id` +ORDER BY records DESC, t0.`id` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-aggregate-inverse.sql new file mode 100644 index 000000000000..1d569c2e2560 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-aggregate-inverse.sql @@ -0,0 +1,9 @@ +SELECT t0.`sku`, t0.`title`, COUNT(*) AS records +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` IS NOT NULL + AND t2.`id` IS NOT NULL +GROUP BY t0.`sku`, t0.`title` +ORDER BY records DESC, t0.`sku` +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-count.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-count.sql new file mode 100644 index 000000000000..25fb5ffd6b3b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`sku` AS k0 + FROM `shop`.`products` t0 + WHERE t0.`sku` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..3a8fd8d10aab --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t2.`sku`, t2.`title` +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` = 1 + AND t2.`sku` IS NOT NULL + AND t2.`sku` > 'A-1' +ORDER BY t2.`sku` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward.sql new file mode 100644 index 000000000000..620ea42e8d81 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t2.`sku`, t2.`title` +FROM `shop`.`orders` t0 +JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +JOIN `shop`.`products` t2 ON t2.`sku` = t1.`product_sku` +WHERE t0.`id` = 1 + AND t2.`sku` IS NOT NULL +ORDER BY t2.`sku` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..ed49360a060c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`sku`, t2.`id` +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` = 'A-1' + AND t2.`id` IS NOT NULL + AND t2.`id` > 1 +ORDER BY t2.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse.sql new file mode 100644 index 000000000000..0e3d88801bc8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`sku`, t2.`id` +FROM `shop`.`products` t0 +JOIN `shop`.`order_items` t1 ON t1.`product_sku` = t0.`sku` +JOIN `shop`.`orders` t2 ON t2.`id` = t1.`order_id` +WHERE t0.`sku` = 'A-1' + AND t2.`id` IS NOT NULL +ORDER BY t2.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-find.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-find.sql new file mode 100644 index 000000000000..51fee8f21343 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`channel` +FROM `shop`.`orders` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-open.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-open.sql new file mode 100644 index 000000000000..63450be89c31 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/linkTable-open.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`channel`, t1.`quantity` +FROM `shop`.`orders` t0 +LEFT JOIN `shop`.`order_items` t1 ON t1.`order_id` = t0.`id` +WHERE t0.`id` = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..caa609645aaa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL + AND t1.`id` > 0 +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..ef10a2e91c16 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.`ledger`, t0.`seq`, t1.`id`, t1.`name` +FROM `shop`.`entries` t0 +JOIN `shop`.`accounts` t1 ON t1.`id` = t0.`account_id` +WHERE t0.`ledger` = 'b' + AND t0.`seq` = 7 + AND t1.`id` IS NOT NULL +ORDER BY t1.`id` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..258579d76366 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL + AND (t1.`ledger` > 'a' OR (t1.`ledger` = 'a' AND t1.`seq` > 25)) +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..df8f3e169168 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.`id`, t1.`ledger`, t1.`seq` +FROM `shop`.`accounts` t0 +JOIN `shop`.`entries` t1 ON t1.`account_id` = t0.`id` +WHERE t0.`id` = 1 + AND t1.`ledger` IS NOT NULL + AND t1.`seq` IS NOT NULL +ORDER BY t1.`ledger`, t1.`seq` +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/repeatedContribution-count.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/repeatedContribution-count.sql new file mode 100644 index 000000000000..9df47e6a1f71 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/repeatedContribution-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/repeatedContribution-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/repeatedContribution-find-match.sql new file mode 100644 index 000000000000..999be1f469c6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/repeatedContribution-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL + AND LOWER(t0.`name`) LIKE '%grace%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/repeatedContribution-find.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/repeatedContribution-find.sql new file mode 100644 index 000000000000..fb0313523a74 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/repeatedContribution-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`name` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/repeatedContribution-open.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/repeatedContribution-open.sql new file mode 100644 index 000000000000..09d6177dfd88 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/repeatedContribution-open.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name`, t1.`city`, t1.`country` +FROM `shop`.`customers` t0 +LEFT JOIN `shop`.`customer_addresses` t1 ON t1.`customer_id` = t0.`id` +WHERE t0.`id` = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/unfilteredIdentity-count.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/unfilteredIdentity-count.sql new file mode 100644 index 000000000000..9df47e6a1f71 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/unfilteredIdentity-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.`id` AS k0 + FROM `shop`.`customers` t0 + WHERE t0.`id` IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/unfilteredIdentity-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/unfilteredIdentity-find-match.sql new file mode 100644 index 000000000000..a16a35cca424 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/unfilteredIdentity-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.`id`, t0.`name`, t0.`email` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL + AND LOWER(t0.`name`) LIKE '%hopper%' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/unfilteredIdentity-find.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/unfilteredIdentity-find.sql new file mode 100644 index 000000000000..feb9d03d9ca8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/unfilteredIdentity-find.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`name`, t0.`email` +FROM `shop`.`customers` t0 +WHERE t0.`id` IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/spark/unfilteredIdentity-open.sql b/openmetadata-service/src/test/resources/ontology/statements/spark/unfilteredIdentity-open.sql new file mode 100644 index 000000000000..6fc3bc31386f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/spark/unfilteredIdentity-open.sql @@ -0,0 +1,4 @@ +SELECT t0.`id`, t0.`name`, t0.`email` +FROM `shop`.`customers` t0 +WHERE t0.`id` = 2 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-aggregate-forward.sql new file mode 100644 index 000000000000..d842942dd7ea --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-aggregate-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.id, COUNT(*) AS records +FROM shop.orders t0 +JOIN shop.customers t1 ON t1.id = t0.customer_id +WHERE t0.id IS NOT NULL + AND t1.id IS NOT NULL +GROUP BY t0.id +ORDER BY records DESC, t0.id +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-aggregate-inverse.sql new file mode 100644 index 000000000000..950b35c90e09 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-aggregate-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t0.name, COUNT(*) AS records +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id IS NOT NULL + AND t1.id IS NOT NULL +GROUP BY t0.id, t0.name +ORDER BY records DESC, t0.id +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-count.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-count.sql new file mode 100644 index 000000000000..83741c2a370f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..2b445527e07d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.id, t1.name +FROM shop.orders t0 +JOIN shop.customers t1 ON t1.id = t0.customer_id +WHERE t0.id = 31 + AND t1.id IS NOT NULL + AND t1.id > 1 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward.sql new file mode 100644 index 000000000000..61c984e2a008 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-forward.sql @@ -0,0 +1,7 @@ +SELECT t0.id, t1.id, t1.name +FROM shop.orders t0 +JOIN shop.customers t1 ON t1.id = t0.customer_id +WHERE t0.id = 31 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..8c77c2edcb81 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.id +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id = 1 + AND t1.id IS NOT NULL + AND t1.id > 25 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-page.sql new file mode 100644 index 000000000000..a89cb7cb88b7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse-page.sql @@ -0,0 +1,7 @@ +SELECT t0.id, t1.id +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id = 1 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse.sql new file mode 100644 index 000000000000..2c19999be46d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-expand-inverse.sql @@ -0,0 +1,7 @@ +SELECT t0.id, t1.id +FROM shop.customers t0 +JOIN shop.orders t1 ON t1.customer_id = t0.id +WHERE t0.id = 2 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-find.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-find.sql new file mode 100644 index 000000000000..9a3411cc1376 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-find.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.total +FROM shop.orders t0 +WHERE t0.id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-open.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-open.sql new file mode 100644 index 000000000000..c27b7a390234 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/columnRelation-open.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.total +FROM shop.orders t0 +WHERE t0.id = 31 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/compositeKey-count.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/compositeKey-count.sql new file mode 100644 index 000000000000..da03c284296e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/compositeKey-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.customer_id AS k1 + FROM shop.crm_customers t0 + WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/compositeKey-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/compositeKey-find-match.sql new file mode 100644 index 000000000000..323b1071dcaa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/compositeKey-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.tenant_id, t0.customer_id, t0.name +FROM shop.crm_customers t0 +WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL + AND LOWER(t0.name) LIKE '%north%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/compositeKey-find.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/compositeKey-find.sql new file mode 100644 index 000000000000..68d2185d0b35 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/compositeKey-find.sql @@ -0,0 +1,5 @@ +SELECT t0.tenant_id, t0.customer_id, t0.name +FROM shop.crm_customers t0 +WHERE t0.tenant_id IS NOT NULL + AND t0.customer_id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/compositeKey-open.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/compositeKey-open.sql new file mode 100644 index 000000000000..6d2f87d800e7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/compositeKey-open.sql @@ -0,0 +1,6 @@ +SELECT t0.tenant_id, t0.customer_id, t0.name, t1.tier +FROM shop.crm_customers t0 +LEFT JOIN shop.crm_customer_profile t1 ON t1.tenant = t0.tenant_id AND t1.customer = t0.customer_id +WHERE t0.tenant_id = 'eu' + AND t0.customer_id = 42 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-organization-count.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-organization-count.sql new file mode 100644 index 000000000000..50bc2e503d6b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-organization-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'organization' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-organization-find.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-organization-find.sql new file mode 100644 index 000000000000..994c187eba42 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-organization-find.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name +FROM shop.parties t0 +WHERE t0.id IS NOT NULL + AND t0.kind = 'organization' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-person-count.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-person-count.sql new file mode 100644 index 000000000000..c8693d700612 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-person-count.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-person-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-person-find-match.sql new file mode 100644 index 000000000000..fc1b8ac510ed --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-person-find-match.sql @@ -0,0 +1,6 @@ +SELECT t0.id, t0.name +FROM shop.parties t0 +WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND LOWER(t0.name) LIKE '%ada%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-person-find.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-person-find.sql new file mode 100644 index 000000000000..792dd8ead52e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-person-find.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name +FROM shop.parties t0 +WHERE t0.id IS NOT NULL + AND t0.kind = 'person' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-person-open.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-person-open.sql new file mode 100644 index 000000000000..686e14bcd4d9 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/filteredIdentity-person-open.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name +FROM shop.parties t0 +WHERE t0.id = 3 + AND t0.kind = 'person' +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-forward.sql new file mode 100644 index 000000000000..18badcb9bec0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.customer_id AS r0 + FROM shop.orders t0 + WHERE t0.id IS NOT NULL + AND t0.customer_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..95a1714b7024 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.id AS r0 + FROM shop.customers t0 + JOIN shop.orders t1 ON t1.customer_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..eda40abc3f8d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.tenant AS r0, t0.branch AS r1 + FROM shop.employees t0 + WHERE t0.id IS NOT NULL + AND t0.tenant IS NOT NULL + AND t0.branch IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..c623bc9cb3dc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.tenant_id AS k0, t0.branch_id AS k1, t1.id AS r0 + FROM shop.branches t0 + JOIN shop.employees t1 ON t1.tenant = t0.tenant_id AND t1.branch = t0.branch_id + WHERE t0.tenant_id IS NOT NULL + AND t0.branch_id IS NOT NULL + AND t1.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..395b8fd7390e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.tenant AS k0, t0.order_no AS k1, t1.sku AS r0 + FROM shop.orders t0 + JOIN shop.order_lines t1 ON t1.tenant = t0.tenant AND t1.order_no = t0.order_no + WHERE t0.tenant IS NOT NULL + AND t0.order_no IS NOT NULL + AND t1.sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..144625529daa --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t2.tenant AS r0, t2.order_no AS r1 + FROM shop.products t0 + JOIN shop.order_lines t1 ON t1.sku = t0.sku + JOIN shop.orders t2 ON t2.tenant = t1.tenant AND t2.order_no = t1.order_no + WHERE t0.sku IS NOT NULL + AND t2.tenant IS NOT NULL + AND t2.order_no IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..a41f5e5db0be --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.customer_id AS r0 + FROM shop.orders t0 + JOIN shop.order_details t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.channel = 'web' + AND t1.customer_id IS NOT NULL + AND t1.region = 'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..76152b181633 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t2.id AS r0 + FROM shop.customers t0 + JOIN shop.order_details t1 ON t1.customer_id = t0.id + JOIN shop.orders t2 ON t2.id = t1.order_id + WHERE t0.id IS NOT NULL + AND t2.id IS NOT NULL + AND t1.region = 'eu' + AND t2.channel = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..3bbdf68b2348 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.channel = 'web' + AND t1.product_sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..bcfdb0e8b82c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t2.id AS r0 + FROM shop.products t0 + JOIN shop.order_items t1 ON t1.product_sku = t0.sku + JOIN shop.orders t2 ON t2.id = t1.order_id + WHERE t0.sku IS NOT NULL + AND t2.id IS NOT NULL + AND t2.channel = 'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..c7195344bb2e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t0.employer_id AS r0 + FROM shop.parties t0 + WHERE t0.id IS NOT NULL + AND t0.kind = 'person' + AND t0.employer_id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..4ec96ff96e16 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkFilteredStart-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.id AS r0 + FROM shop.parties t0 + JOIN shop.parties t1 ON t1.employer_id = t0.id + WHERE t0.id IS NOT NULL + AND t0.kind = 'organization' + AND t1.id IS NOT NULL + AND t1.kind = 'person' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..afefbe446c11 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.id AS k0, t1.product_sku AS r0 + FROM shop.orders t0 + JOIN shop.order_items t1 ON t1.order_id = t0.id + WHERE t0.id IS NOT NULL + AND t1.product_sku IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..05a4b13d3306 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.sku AS k0, t2.id AS r0 + FROM shop.products t0 + JOIN shop.order_items t1 ON t1.product_sku = t0.sku + JOIN shop.orders t2 ON t2.id = t1.order_id + WHERE t0.sku IS NOT NULL + AND t2.id IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-aggregate-forward.sql new file mode 100644 index 000000000000..e7a28c70ead7 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-aggregate-forward.sql @@ -0,0 +1,9 @@ +SELECT t0.id, COUNT(*) AS records +FROM shop.orders t0 +JOIN shop.order_items t1 ON t1.order_id = t0.id +JOIN shop.products t2 ON t2.sku = t1.product_sku +WHERE t0.id IS NOT NULL + AND t2.sku IS NOT NULL +GROUP BY t0.id +ORDER BY records DESC, t0.id +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-aggregate-inverse.sql new file mode 100644 index 000000000000..315b54f9c1f1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-aggregate-inverse.sql @@ -0,0 +1,9 @@ +SELECT t0.sku, t0.title, COUNT(*) AS records +FROM shop.products t0 +JOIN shop.order_items t1 ON t1.product_sku = t0.sku +JOIN shop.orders t2 ON t2.id = t1.order_id +WHERE t0.sku IS NOT NULL + AND t2.id IS NOT NULL +GROUP BY t0.sku, t0.title +ORDER BY records DESC, t0.sku +LIMIT 8 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-count.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-count.sql new file mode 100644 index 000000000000..85a0316db527 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.sku AS k0 + FROM shop.products t0 + WHERE t0.sku IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..f7d5dd202dad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.id, t2.sku, t2.title +FROM shop.orders t0 +JOIN shop.order_items t1 ON t1.order_id = t0.id +JOIN shop.products t2 ON t2.sku = t1.product_sku +WHERE t0.id = 1 + AND t2.sku IS NOT NULL + AND t2.sku > 'A-1' +ORDER BY t2.sku +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward.sql new file mode 100644 index 000000000000..b14c19c82e04 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t2.sku, t2.title +FROM shop.orders t0 +JOIN shop.order_items t1 ON t1.order_id = t0.id +JOIN shop.products t2 ON t2.sku = t1.product_sku +WHERE t0.id = 1 + AND t2.sku IS NOT NULL +ORDER BY t2.sku +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..31db3cf3687b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.sku, t2.id +FROM shop.products t0 +JOIN shop.order_items t1 ON t1.product_sku = t0.sku +JOIN shop.orders t2 ON t2.id = t1.order_id +WHERE t0.sku = 'A-1' + AND t2.id IS NOT NULL + AND t2.id > 1 +ORDER BY t2.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse.sql new file mode 100644 index 000000000000..9e5493c904e4 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.sku, t2.id +FROM shop.products t0 +JOIN shop.order_items t1 ON t1.product_sku = t0.sku +JOIN shop.orders t2 ON t2.id = t1.order_id +WHERE t0.sku = 'A-1' + AND t2.id IS NOT NULL +ORDER BY t2.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-find.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-find.sql new file mode 100644 index 000000000000..df0a34a86e04 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-find.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.channel +FROM shop.orders t0 +WHERE t0.id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-open.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-open.sql new file mode 100644 index 000000000000..34dd90e044f1 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/linkTable-open.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.channel, t1.quantity +FROM shop.orders t0 +LEFT JOIN shop.order_items t1 ON t1.order_id = t0.id +WHERE t0.id = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..477618a62c9c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,9 @@ +SELECT t0.ledger, t0.seq, t1.id, t1.name +FROM shop.entries t0 +JOIN shop.accounts t1 ON t1.id = t0.account_id +WHERE t0.ledger = 'b' + AND t0.seq = 7 + AND t1.id IS NOT NULL + AND t1.id > 0 +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..53c8af0352a6 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,8 @@ +SELECT t0.ledger, t0.seq, t1.id, t1.name +FROM shop.entries t0 +JOIN shop.accounts t1 ON t1.id = t0.account_id +WHERE t0.ledger = 'b' + AND t0.seq = 7 + AND t1.id IS NOT NULL +ORDER BY t1.id +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..e70d76fc94d0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,9 @@ +SELECT t0.id, t1.ledger, t1.seq +FROM shop.accounts t0 +JOIN shop.entries t1 ON t1.account_id = t0.id +WHERE t0.id = 1 + AND t1.ledger IS NOT NULL + AND t1.seq IS NOT NULL + AND (t1.ledger > 'a' OR (t1.ledger = 'a' AND t1.seq > 25)) +ORDER BY t1.ledger, t1.seq +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..57fd96c978bc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,8 @@ +SELECT t0.id, t1.ledger, t1.seq +FROM shop.accounts t0 +JOIN shop.entries t1 ON t1.account_id = t0.id +WHERE t0.id = 1 + AND t1.ledger IS NOT NULL + AND t1.seq IS NOT NULL +ORDER BY t1.ledger, t1.seq +LIMIT 26 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/repeatedContribution-count.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/repeatedContribution-count.sql new file mode 100644 index 000000000000..d9e3abbd242b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/repeatedContribution-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/repeatedContribution-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/repeatedContribution-find-match.sql new file mode 100644 index 000000000000..9b1c7fd6e8df --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/repeatedContribution-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name +FROM shop.customers t0 +WHERE t0.id IS NOT NULL + AND LOWER(t0.name) LIKE '%grace%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/repeatedContribution-find.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/repeatedContribution-find.sql new file mode 100644 index 000000000000..98769f319568 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/repeatedContribution-find.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.name +FROM shop.customers t0 +WHERE t0.id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/repeatedContribution-open.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/repeatedContribution-open.sql new file mode 100644 index 000000000000..09c976b6b1ed --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/repeatedContribution-open.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name, t1.city, t1.country +FROM shop.customers t0 +LEFT JOIN shop.customer_addresses t1 ON t1.customer_id = t0.id +WHERE t0.id = 1 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/unfilteredIdentity-count.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/unfilteredIdentity-count.sql new file mode 100644 index 000000000000..d9e3abbd242b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/unfilteredIdentity-count.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.id AS k0 + FROM shop.customers t0 + WHERE t0.id IS NOT NULL +) k +LIMIT 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/unfilteredIdentity-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/unfilteredIdentity-find-match.sql new file mode 100644 index 000000000000..be09f98e3168 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/unfilteredIdentity-find-match.sql @@ -0,0 +1,5 @@ +SELECT t0.id, t0.name, t0.email +FROM shop.customers t0 +WHERE t0.id IS NOT NULL + AND LOWER(t0.name) LIKE '%hopper%' ESCAPE '!' +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/unfilteredIdentity-find.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/unfilteredIdentity-find.sql new file mode 100644 index 000000000000..946d50c7c7ee --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/unfilteredIdentity-find.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.name, t0.email +FROM shop.customers t0 +WHERE t0.id IS NOT NULL +LIMIT 25 diff --git a/openmetadata-service/src/test/resources/ontology/statements/trino/unfilteredIdentity-open.sql b/openmetadata-service/src/test/resources/ontology/statements/trino/unfilteredIdentity-open.sql new file mode 100644 index 000000000000..cc3ba0a3efcd --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/trino/unfilteredIdentity-open.sql @@ -0,0 +1,4 @@ +SELECT t0.id, t0.name, t0.email +FROM shop.customers t0 +WHERE t0.id = 2 +LIMIT 101 diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-aggregate-forward.sql new file mode 100644 index 000000000000..aa0d1d4cb44f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-aggregate-forward.sql @@ -0,0 +1,7 @@ +SELECT TOP 8 t0.[id], COUNT(*) AS records +FROM [shop].[orders] t0 +JOIN [shop].[customers] t1 ON t1.[id] = t0.[customer_id] +WHERE t0.[id] IS NOT NULL + AND t1.[id] IS NOT NULL +GROUP BY t0.[id] +ORDER BY records DESC, t0.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-aggregate-inverse.sql new file mode 100644 index 000000000000..b514361e647b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-aggregate-inverse.sql @@ -0,0 +1,7 @@ +SELECT TOP 8 t0.[id], t0.[name], COUNT(*) AS records +FROM [shop].[customers] t0 +JOIN [shop].[orders] t1 ON t1.[customer_id] = t0.[id] +WHERE t0.[id] IS NOT NULL + AND t1.[id] IS NOT NULL +GROUP BY t0.[id], t0.[name] +ORDER BY records DESC, t0.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-count.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-count.sql new file mode 100644 index 000000000000..14cfa7898137 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-count.sql @@ -0,0 +1,6 @@ +SELECT TOP 1 COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward-after.sql new file mode 100644 index 000000000000..b78a4fdcad32 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward-after.sql @@ -0,0 +1,7 @@ +SELECT TOP 26 t0.[id], t1.[id], t1.[name] +FROM [shop].[orders] t0 +JOIN [shop].[customers] t1 ON t1.[id] = t0.[customer_id] +WHERE t0.[id] = 31 + AND t1.[id] IS NOT NULL + AND t1.[id] > 1 +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward.sql new file mode 100644 index 000000000000..d9bc14b1a7f5 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-forward.sql @@ -0,0 +1,6 @@ +SELECT TOP 26 t0.[id], t1.[id], t1.[name] +FROM [shop].[orders] t0 +JOIN [shop].[customers] t1 ON t1.[id] = t0.[customer_id] +WHERE t0.[id] = 31 + AND t1.[id] IS NOT NULL +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-after.sql new file mode 100644 index 000000000000..b528c56c000f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-after.sql @@ -0,0 +1,7 @@ +SELECT TOP 26 t0.[id], t1.[id] +FROM [shop].[customers] t0 +JOIN [shop].[orders] t1 ON t1.[customer_id] = t0.[id] +WHERE t0.[id] = 1 + AND t1.[id] IS NOT NULL + AND t1.[id] > 25 +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-page.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-page.sql new file mode 100644 index 000000000000..ddb6695eee5b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse-page.sql @@ -0,0 +1,6 @@ +SELECT TOP 26 t0.[id], t1.[id] +FROM [shop].[customers] t0 +JOIN [shop].[orders] t1 ON t1.[customer_id] = t0.[id] +WHERE t0.[id] = 1 + AND t1.[id] IS NOT NULL +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse.sql new file mode 100644 index 000000000000..8a6cc1d68193 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-expand-inverse.sql @@ -0,0 +1,6 @@ +SELECT TOP 26 t0.[id], t1.[id] +FROM [shop].[customers] t0 +JOIN [shop].[orders] t1 ON t1.[customer_id] = t0.[id] +WHERE t0.[id] = 2 + AND t1.[id] IS NOT NULL +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-find.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-find.sql new file mode 100644 index 000000000000..e4a102884a7d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-find.sql @@ -0,0 +1,3 @@ +SELECT TOP 25 t0.[id], t0.[total] +FROM [shop].[orders] t0 +WHERE t0.[id] IS NOT NULL diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-open.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-open.sql new file mode 100644 index 000000000000..0a8ace270dbe --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/columnRelation-open.sql @@ -0,0 +1,3 @@ +SELECT TOP 101 t0.[id], t0.[total] +FROM [shop].[orders] t0 +WHERE t0.[id] = 31 diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/compositeKey-count.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/compositeKey-count.sql new file mode 100644 index 000000000000..cbbee58d6122 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/compositeKey-count.sql @@ -0,0 +1,7 @@ +SELECT TOP 1 COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.[tenant_id] AS k0, t0.[customer_id] AS k1 + FROM [shop].[crm_customers] t0 + WHERE t0.[tenant_id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/compositeKey-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/compositeKey-find-match.sql new file mode 100644 index 000000000000..da84406dd16e --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/compositeKey-find-match.sql @@ -0,0 +1,5 @@ +SELECT TOP 25 t0.[tenant_id], t0.[customer_id], t0.[name] +FROM [shop].[crm_customers] t0 +WHERE t0.[tenant_id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL + AND LOWER(t0.[name]) LIKE N'%north%' ESCAPE '!' diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/compositeKey-find.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/compositeKey-find.sql new file mode 100644 index 000000000000..820e8d3c27fc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/compositeKey-find.sql @@ -0,0 +1,4 @@ +SELECT TOP 25 t0.[tenant_id], t0.[customer_id], t0.[name] +FROM [shop].[crm_customers] t0 +WHERE t0.[tenant_id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/compositeKey-open.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/compositeKey-open.sql new file mode 100644 index 000000000000..7278a68868df --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/compositeKey-open.sql @@ -0,0 +1,5 @@ +SELECT TOP 101 t0.[tenant_id], t0.[customer_id], t0.[name], t1.[tier] +FROM [shop].[crm_customers] t0 +LEFT JOIN [shop].[crm_customer_profile] t1 ON t1.[tenant] = t0.[tenant_id] AND t1.[customer] = t0.[customer_id] +WHERE t0.[tenant_id] = N'eu' + AND t0.[customer_id] = 42 diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-organization-count.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-organization-count.sql new file mode 100644 index 000000000000..1fc962c613b5 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-organization-count.sql @@ -0,0 +1,7 @@ +SELECT TOP 1 COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[parties] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'organization' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-organization-find.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-organization-find.sql new file mode 100644 index 000000000000..7b43b4f7af3a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-organization-find.sql @@ -0,0 +1,4 @@ +SELECT TOP 25 t0.[id], t0.[name] +FROM [shop].[parties] t0 +WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'organization' diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-person-count.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-person-count.sql new file mode 100644 index 000000000000..3e18a003dfad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-person-count.sql @@ -0,0 +1,7 @@ +SELECT TOP 1 COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[parties] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'person' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-person-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-person-find-match.sql new file mode 100644 index 000000000000..ed471868f465 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-person-find-match.sql @@ -0,0 +1,5 @@ +SELECT TOP 25 t0.[id], t0.[name] +FROM [shop].[parties] t0 +WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'person' + AND LOWER(t0.[name]) LIKE N'%ada%' ESCAPE '!' diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-person-find.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-person-find.sql new file mode 100644 index 000000000000..a6c19223f4d0 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-person-find.sql @@ -0,0 +1,4 @@ +SELECT TOP 25 t0.[id], t0.[name] +FROM [shop].[parties] t0 +WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'person' diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-person-open.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-person-open.sql new file mode 100644 index 000000000000..9743f26b9fb8 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/filteredIdentity-person-open.sql @@ -0,0 +1,4 @@ +SELECT TOP 101 t0.[id], t0.[name] +FROM [shop].[parties] t0 +WHERE t0.[id] = 3 + AND t0.[kind] = N'person' diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-forward.sql new file mode 100644 index 000000000000..8d31667a016a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-forward.sql @@ -0,0 +1,7 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[customer_id] AS r0 + FROM [shop].[orders] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[customer_id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-inverse.sql new file mode 100644 index 000000000000..1c0f0536d6bc --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkColumn-links-inverse.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[id] AS r0 + FROM [shop].[customers] t0 + JOIN [shop].[orders] t1 ON t1.[customer_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t1.[id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-forward.sql new file mode 100644 index 000000000000..18fe2a0ed957 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[tenant] AS r0, t0.[branch] AS r1 + FROM [shop].[employees] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[tenant] IS NOT NULL + AND t0.[branch] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-inverse.sql new file mode 100644 index 000000000000..b93d727e39ea --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeKey-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[tenant_id] AS k0, t0.[branch_id] AS k1, t1.[id] AS r0 + FROM [shop].[branches] t0 + JOIN [shop].[employees] t1 ON t1.[tenant] = t0.[tenant_id] AND t1.[branch] = t0.[branch_id] + WHERE t0.[tenant_id] IS NOT NULL + AND t0.[branch_id] IS NOT NULL + AND t1.[id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-forward.sql new file mode 100644 index 000000000000..3d668bdd932b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[tenant] AS k0, t0.[order_no] AS k1, t1.[sku] AS r0 + FROM [shop].[orders] t0 + JOIN [shop].[order_lines] t1 ON t1.[tenant] = t0.[tenant] AND t1.[order_no] = t0.[order_no] + WHERE t0.[tenant] IS NOT NULL + AND t0.[order_no] IS NOT NULL + AND t1.[sku] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-inverse.sql new file mode 100644 index 000000000000..288ff2be41cb --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkCompositeLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[sku] AS k0, t2.[tenant] AS r0, t2.[order_no] AS r1 + FROM [shop].[products] t0 + JOIN [shop].[order_lines] t1 ON t1.[sku] = t0.[sku] + JOIN [shop].[orders] t2 ON t2.[tenant] = t1.[tenant] AND t2.[order_no] = t1.[order_no] + WHERE t0.[sku] IS NOT NULL + AND t2.[tenant] IS NOT NULL + AND t2.[order_no] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-forward.sql new file mode 100644 index 000000000000..fa921333170c --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-forward.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[customer_id] AS r0 + FROM [shop].[orders] t0 + JOIN [shop].[order_details] t1 ON t1.[order_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t0.[channel] = N'web' + AND t1.[customer_id] IS NOT NULL + AND t1.[region] = N'eu' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-inverse.sql new file mode 100644 index 000000000000..fa9e69cec1b2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredContributing-links-inverse.sql @@ -0,0 +1,11 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t2.[id] AS r0 + FROM [shop].[customers] t0 + JOIN [shop].[order_details] t1 ON t1.[customer_id] = t0.[id] + JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id] + WHERE t0.[id] IS NOT NULL + AND t2.[id] IS NOT NULL + AND t1.[region] = N'eu' + AND t2.[channel] = N'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-forward.sql new file mode 100644 index 000000000000..68401480bfdf --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-forward.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[product_sku] AS r0 + FROM [shop].[orders] t0 + JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t0.[channel] = N'web' + AND t1.[product_sku] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-inverse.sql new file mode 100644 index 000000000000..3400531214c5 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredLinkTable-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[sku] AS k0, t2.[id] AS r0 + FROM [shop].[products] t0 + JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku] + JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id] + WHERE t0.[sku] IS NOT NULL + AND t2.[id] IS NOT NULL + AND t2.[channel] = N'web' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-forward.sql new file mode 100644 index 000000000000..7a9fb558617f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t0.[employer_id] AS r0 + FROM [shop].[parties] t0 + WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'person' + AND t0.[employer_id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-inverse.sql new file mode 100644 index 000000000000..55386e061958 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkFilteredStart-links-inverse.sql @@ -0,0 +1,10 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[id] AS r0 + FROM [shop].[parties] t0 + JOIN [shop].[parties] t1 ON t1.[employer_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t0.[kind] = N'organization' + AND t1.[id] IS NOT NULL + AND t1.[kind] = N'person' +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-forward.sql new file mode 100644 index 000000000000..0b3c2df4d9b2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-forward.sql @@ -0,0 +1,8 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[id] AS k0, t1.[product_sku] AS r0 + FROM [shop].[orders] t0 + JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] + WHERE t0.[id] IS NOT NULL + AND t1.[product_sku] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-inverse.sql new file mode 100644 index 000000000000..c8a2364eb54a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkLinkTable-links-inverse.sql @@ -0,0 +1,9 @@ +SELECT COUNT(*) AS links +FROM ( + SELECT DISTINCT t0.[sku] AS k0, t2.[id] AS r0 + FROM [shop].[products] t0 + JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku] + JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id] + WHERE t0.[sku] IS NOT NULL + AND t2.[id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-aggregate-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-aggregate-forward.sql new file mode 100644 index 000000000000..9df556c40a9b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-aggregate-forward.sql @@ -0,0 +1,8 @@ +SELECT TOP 8 t0.[id], COUNT(*) AS records +FROM [shop].[orders] t0 +JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] +JOIN [shop].[products] t2 ON t2.[sku] = t1.[product_sku] +WHERE t0.[id] IS NOT NULL + AND t2.[sku] IS NOT NULL +GROUP BY t0.[id] +ORDER BY records DESC, t0.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-aggregate-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-aggregate-inverse.sql new file mode 100644 index 000000000000..722dccb49127 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-aggregate-inverse.sql @@ -0,0 +1,8 @@ +SELECT TOP 8 t0.[sku], t0.[title], COUNT(*) AS records +FROM [shop].[products] t0 +JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku] +JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id] +WHERE t0.[sku] IS NOT NULL + AND t2.[id] IS NOT NULL +GROUP BY t0.[sku], t0.[title] +ORDER BY records DESC, t0.[sku] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-count.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-count.sql new file mode 100644 index 000000000000..e43ee73e7f17 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-count.sql @@ -0,0 +1,6 @@ +SELECT TOP 1 COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.[sku] AS k0 + FROM [shop].[products] t0 + WHERE t0.[sku] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward-after.sql new file mode 100644 index 000000000000..d846705f4dee --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT TOP 26 t0.[id], t2.[sku], t2.[title] +FROM [shop].[orders] t0 +JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] +JOIN [shop].[products] t2 ON t2.[sku] = t1.[product_sku] +WHERE t0.[id] = 1 + AND t2.[sku] IS NOT NULL + AND t2.[sku] > N'A-1' +ORDER BY t2.[sku] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward.sql new file mode 100644 index 000000000000..d0189a800cb2 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-forward.sql @@ -0,0 +1,7 @@ +SELECT TOP 26 t0.[id], t2.[sku], t2.[title] +FROM [shop].[orders] t0 +JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] +JOIN [shop].[products] t2 ON t2.[sku] = t1.[product_sku] +WHERE t0.[id] = 1 + AND t2.[sku] IS NOT NULL +ORDER BY t2.[sku] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse-after.sql new file mode 100644 index 000000000000..4385becac17d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT TOP 26 t0.[sku], t2.[id] +FROM [shop].[products] t0 +JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku] +JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id] +WHERE t0.[sku] = N'A-1' + AND t2.[id] IS NOT NULL + AND t2.[id] > 1 +ORDER BY t2.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse.sql new file mode 100644 index 000000000000..6cf735694cfd --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-expand-inverse.sql @@ -0,0 +1,7 @@ +SELECT TOP 26 t0.[sku], t2.[id] +FROM [shop].[products] t0 +JOIN [shop].[order_items] t1 ON t1.[product_sku] = t0.[sku] +JOIN [shop].[orders] t2 ON t2.[id] = t1.[order_id] +WHERE t0.[sku] = N'A-1' + AND t2.[id] IS NOT NULL +ORDER BY t2.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-find.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-find.sql new file mode 100644 index 000000000000..4c4139f25ece --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-find.sql @@ -0,0 +1,3 @@ +SELECT TOP 25 t0.[id], t0.[channel] +FROM [shop].[orders] t0 +WHERE t0.[id] IS NOT NULL diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-open.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-open.sql new file mode 100644 index 000000000000..c29a32371643 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/linkTable-open.sql @@ -0,0 +1,4 @@ +SELECT TOP 101 t0.[id], t0.[channel], t1.[quantity] +FROM [shop].[orders] t0 +LEFT JOIN [shop].[order_items] t1 ON t1.[order_id] = t0.[id] +WHERE t0.[id] = 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward-after.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward-after.sql new file mode 100644 index 000000000000..3b364a041ade --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward-after.sql @@ -0,0 +1,8 @@ +SELECT TOP 26 t0.[ledger], t0.[seq], t1.[id], t1.[name] +FROM [shop].[entries] t0 +JOIN [shop].[accounts] t1 ON t1.[id] = t0.[account_id] +WHERE t0.[ledger] = N'b' + AND t0.[seq] = 7 + AND t1.[id] IS NOT NULL + AND t1.[id] > 0 +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward.sql new file mode 100644 index 000000000000..7bb7c7f81a24 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-forward.sql @@ -0,0 +1,7 @@ +SELECT TOP 26 t0.[ledger], t0.[seq], t1.[id], t1.[name] +FROM [shop].[entries] t0 +JOIN [shop].[accounts] t1 ON t1.[id] = t0.[account_id] +WHERE t0.[ledger] = N'b' + AND t0.[seq] = 7 + AND t1.[id] IS NOT NULL +ORDER BY t1.[id] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse-after.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse-after.sql new file mode 100644 index 000000000000..acff38d0e351 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse-after.sql @@ -0,0 +1,8 @@ +SELECT TOP 26 t0.[id], t1.[ledger], t1.[seq] +FROM [shop].[accounts] t0 +JOIN [shop].[entries] t1 ON t1.[account_id] = t0.[id] +WHERE t0.[id] = 1 + AND t1.[ledger] IS NOT NULL + AND t1.[seq] IS NOT NULL + AND (t1.[ledger] > N'a' OR (t1.[ledger] = N'a' AND t1.[seq] > 25)) +ORDER BY t1.[ledger], t1.[seq] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse.sql new file mode 100644 index 000000000000..90a4477754ad --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/pagedCompositeRelatedKey-expand-inverse.sql @@ -0,0 +1,7 @@ +SELECT TOP 26 t0.[id], t1.[ledger], t1.[seq] +FROM [shop].[accounts] t0 +JOIN [shop].[entries] t1 ON t1.[account_id] = t0.[id] +WHERE t0.[id] = 1 + AND t1.[ledger] IS NOT NULL + AND t1.[seq] IS NOT NULL +ORDER BY t1.[ledger], t1.[seq] diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/repeatedContribution-count.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/repeatedContribution-count.sql new file mode 100644 index 000000000000..6b5520bbec2b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/repeatedContribution-count.sql @@ -0,0 +1,6 @@ +SELECT TOP 1 COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[customers] t0 + WHERE t0.[id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/repeatedContribution-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/repeatedContribution-find-match.sql new file mode 100644 index 000000000000..48c401199398 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/repeatedContribution-find-match.sql @@ -0,0 +1,4 @@ +SELECT TOP 25 t0.[id], t0.[name] +FROM [shop].[customers] t0 +WHERE t0.[id] IS NOT NULL + AND LOWER(t0.[name]) LIKE N'%grace%' ESCAPE '!' diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/repeatedContribution-find.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/repeatedContribution-find.sql new file mode 100644 index 000000000000..a833ed6e7f9a --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/repeatedContribution-find.sql @@ -0,0 +1,3 @@ +SELECT TOP 25 t0.[id], t0.[name] +FROM [shop].[customers] t0 +WHERE t0.[id] IS NOT NULL diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/repeatedContribution-open.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/repeatedContribution-open.sql new file mode 100644 index 000000000000..15e7e279d07f --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/repeatedContribution-open.sql @@ -0,0 +1,4 @@ +SELECT TOP 101 t0.[id], t0.[name], t1.[city], t1.[country] +FROM [shop].[customers] t0 +LEFT JOIN [shop].[customer_addresses] t1 ON t1.[customer_id] = t0.[id] +WHERE t0.[id] = 1 diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/unfilteredIdentity-count.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/unfilteredIdentity-count.sql new file mode 100644 index 000000000000..6b5520bbec2b --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/unfilteredIdentity-count.sql @@ -0,0 +1,6 @@ +SELECT TOP 1 COUNT(*) AS records +FROM ( + SELECT DISTINCT t0.[id] AS k0 + FROM [shop].[customers] t0 + WHERE t0.[id] IS NOT NULL +) k diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/unfilteredIdentity-find-match.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/unfilteredIdentity-find-match.sql new file mode 100644 index 000000000000..dbc5a6200c6d --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/unfilteredIdentity-find-match.sql @@ -0,0 +1,4 @@ +SELECT TOP 25 t0.[id], t0.[name], t0.[email] +FROM [shop].[customers] t0 +WHERE t0.[id] IS NOT NULL + AND LOWER(t0.[name]) LIKE N'%hopper%' ESCAPE '!' diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/unfilteredIdentity-find.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/unfilteredIdentity-find.sql new file mode 100644 index 000000000000..eabd260ab7bd --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/unfilteredIdentity-find.sql @@ -0,0 +1,3 @@ +SELECT TOP 25 t0.[id], t0.[name], t0.[email] +FROM [shop].[customers] t0 +WHERE t0.[id] IS NOT NULL diff --git a/openmetadata-service/src/test/resources/ontology/statements/tsql/unfilteredIdentity-open.sql b/openmetadata-service/src/test/resources/ontology/statements/tsql/unfilteredIdentity-open.sql new file mode 100644 index 000000000000..9e26b60dcc98 --- /dev/null +++ b/openmetadata-service/src/test/resources/ontology/statements/tsql/unfilteredIdentity-open.sql @@ -0,0 +1,3 @@ +SELECT TOP 101 t0.[id], t0.[name], t0.[email] +FROM [shop].[customers] t0 +WHERE t0.[id] = 2 diff --git a/openmetadata-spec/src/main/antlr4/org/openmetadata/schema/EntityLink.g4 b/openmetadata-spec/src/main/antlr4/org/openmetadata/schema/EntityLink.g4 index 699d9233e5a5..b567aebe5a72 100644 --- a/openmetadata-spec/src/main/antlr4/org/openmetadata/schema/EntityLink.g4 +++ b/openmetadata-spec/src/main/antlr4/org/openmetadata/schema/EntityLink.g4 @@ -45,6 +45,7 @@ ENTITY_TYPE | 'ontologyProperty' | 'ontologyRelease' | 'ontologyAxiom' + | 'ontologyShape' | 'ontologyChangeSet' | 'databaseService' | 'messagingService' diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/createOntology.json b/openmetadata-spec/src/main/resources/json/schema/api/data/createOntology.json index 0db39fb23a65..c1f82b340a2d 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/createOntology.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/createOntology.json @@ -41,6 +41,9 @@ }, "approvalRule": { "$ref": "../../entity/data/ontology.json#/properties/approvalRule" + }, + "mappingSource": { + "$ref": "../../entity/data/ontology.json#/properties/mappingSource" } }, "required": [ diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyProperty.json b/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyProperty.json index 7d9fb55a09da..28a75925e47a 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyProperty.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyProperty.json @@ -46,6 +46,9 @@ "isIdentifier": { "$ref": "../../entity/data/ontologyProperty.json#/properties/isIdentifier" }, + "isDisplayName": { + "$ref": "../../entity/data/ontologyProperty.json#/properties/isDisplayName" + }, "inverse": { "$ref": "../../entity/data/ontologyProperty.json#/properties/inverse" }, diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyShape.json b/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyShape.json new file mode 100644 index 000000000000..ccca851150dd --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/createOntologyShape.json @@ -0,0 +1,51 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/createOntologyShape.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "CreateOntologyShapeRequest", + "description": "Create or update an ontology shape.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.CreateOntologyShape", + "javaInterfaces": [ + "org.openmetadata.schema.CreateEntity" + ], + "properties": { + "name": { + "$ref": "../../type/basic.json#/definitions/entityName" + }, + "displayName": { + "type": "string" + }, + "description": { + "$ref": "../../type/basic.json#/definitions/markdown" + }, + "ontology": { + "$ref": "../../type/basic.json#/definitions/fullyQualifiedEntityName" + }, + "targetConcept": { + "$ref": "../../type/ontologyIri.json" + }, + "severity": { + "$ref": "../../entity/data/ontologyShape.json#/definitions/severity" + }, + "constraints": { + "type": "array", + "items": { + "$ref": "../../type/ontologyShapeConstraint.json" + } + }, + "owners": { + "$ref": "../../type/entityReferenceList.json" + }, + "provider": { + "$ref": "../../type/basic.json#/definitions/providerType" + } + }, + "required": [ + "name", + "displayName", + "description", + "ontology", + "targetConcept" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/declineOntologyDefinitions.json b/openmetadata-spec/src/main/resources/json/schema/api/data/declineOntologyDefinitions.json new file mode 100644 index 000000000000..f5c68b197b51 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/declineOntologyDefinitions.json @@ -0,0 +1,28 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/declineOntologyDefinitions.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "DeclineOntologyDefinitionsRequest", + "description": "Record that the definitions carried by some operations of one change set are declined. The server reads the stored operations and computes each digest.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.DeclineOntologyDefinitions", + "properties": { + "changeSetId": { + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "operationIds": { + "type": "array", + "items": { + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "uniqueItems": true, + "minItems": 1, + "maxItems": 1000 + }, + "reason": { + "type": "string", + "maxLength": 2000 + } + }, + "required": ["changeSetId", "operationIds"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/importOntologyShapes.json b/openmetadata-spec/src/main/resources/json/schema/api/data/importOntologyShapes.json new file mode 100644 index 000000000000..8d857908b481 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/importOntologyShapes.json @@ -0,0 +1,29 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/importOntologyShapes.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "ImportOntologyShapesRequest", + "description": "Import the SHACL node shapes of a Turtle document into an ontology's working draft.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.ImportOntologyShapes", + "properties": { + "ontology": { + "$ref": "../../type/basic.json#/definitions/fullyQualifiedEntityName" + }, + "content": { + "description": "The Turtle document.", + "type": "string", + "minLength": 1, + "maxLength": 8388608 + }, + "dryRun": { + "description": "Report what the import would write without writing it.", + "type": "boolean", + "default": false + } + }, + "required": [ + "ontology", + "content" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/matchOntologyDeclinedDefinitions.json b/openmetadata-spec/src/main/resources/json/schema/api/data/matchOntologyDeclinedDefinitions.json new file mode 100644 index 000000000000..bc0c3fef97f0 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/matchOntologyDeclinedDefinitions.json @@ -0,0 +1,19 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/matchOntologyDeclinedDefinitions.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "MatchOntologyDeclinedDefinitionsRequest", + "description": "Candidate operations, as they would be put in a new change set, to match against an ontology's declined definitions.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.MatchOntologyDeclinedDefinitions", + "properties": { + "candidates": { + "type": "array", + "items": { + "$ref": "../../type/ontologyChangeOperation.json" + }, + "maxItems": 1000 + } + }, + "required": ["candidates"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json index 2d4daa7e44b6..0868b78f3af3 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyAssetCluster.json @@ -21,6 +21,21 @@ "description": "Number of column paths bound on this asset.", "type": "integer", "minimum": 0 + }, + "rowCount": { + "description": "Row count of the asset's latest stored profile, always measured on the whole table. Present only for a table the caller may view the data profile of, whose latest profile records a row count.", + "type": "integer", + "existingJavaType": "java.lang.Long", + "format": "int64", + "minimum": 0 + }, + "profiledAt": { + "description": "Time the asset's latest stored profile was taken. Present only for a table the caller may view the data profile of that has a stored profile.", + "$ref": "../../type/basic.json#/definitions/timestamp" + }, + "sampled": { + "description": "True when that profile's column metrics were computed on a sample, as the profile itself records through its profileSample and profileSampleType. Nothing else is read, so a profile computed on a partition or a custom query reports false. Present exactly when profiledAt is.", + "type": "boolean" } }, "required": ["asset", "columnCount"], @@ -48,6 +63,10 @@ "after": { "description": "Cursor the concept's bindings endpoint accepts for the next page of viewable assets. Absent when this page holds every viewable asset.", "type": "string" + }, + "records": { + "description": "How many records the concept has, from the stored profiles of its identity table. Absent when the concept binds no table.", + "$ref": "nativeOntologyCount.json" } }, "required": ["concept", "assetCount", "assets"], diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyCount.json b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyCount.json new file mode 100644 index 000000000000..2983cda979e8 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyCount.json @@ -0,0 +1,37 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/nativeOntologyCount.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "NativeOntologyCount", + "description": "A count that the stored profiles of a table give exactly, or the reason they do not. A count is exact or it is absent: a profile's row count is never used, because the profiler may take it from the engine's catalog, which can be an estimate.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.NativeOntologyCount", + "properties": { + "state": { + "title": "RecordsState", + "description": "exact: the stored profiles give the number. noIdentityTable: the class binds tables and none is its identity table. identityTableHidden: the class has an identity table that the caller may not view, or that is deleted. noProfile: the caller may not view the data profile of the table, or the table has no stored profile. joinNotConfirmed: the relation has a join onto the identity table of the related class and it is not confirmed. noJoin: the relation has no join onto it. notDerivable: the stored profiles cannot give the exact number, and a query over the table could.", + "type": "string", + "enum": [ + "exact", + "noIdentityTable", + "identityTableHidden", + "noProfile", + "joinNotConfirmed", + "noJoin", + "notDerivable" + ] + }, + "value": { + "description": "The count. Present exactly when state is exact.", + "type": "integer", + "existingJavaType": "java.lang.Long", + "format": "int64", + "minimum": 0 + }, + "profiledAt": { + "description": "Time of the profile run whose metrics gave the count. Present exactly when state is exact.", + "$ref": "../../type/basic.json#/definitions/timestamp" + } + }, + "required": ["state"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyDataGraph.json b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyDataGraph.json index d0f070b992d3..dd68dd4ef0b1 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyDataGraph.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/nativeOntologyDataGraph.json @@ -29,6 +29,10 @@ "property": { "description": "The declared property, when this ontology declares one for the IRI and the caller may view it.", "$ref": "../../type/entityReference.json" + }, + "links": { + "description": "How many links the relation has from the records of the first concept, from the stored profiles of its identity table. Absent when the page does not hold the first concept.", + "$ref": "nativeOntologyCount.json" } }, "required": ["fromConceptId", "toConceptId", "propertyIri", "label"], diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json new file mode 100644 index 000000000000..7249fe36c327 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyAggregateStatementRequest.json @@ -0,0 +1,29 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/ontologyAggregateStatementRequest.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyAggregateStatementRequest", + "description": "Asks for a counting statement. Without a relation it counts the records of the class. With a relation and a direction it returns, by default, the 8 records of the class that relate to the most records along that relation, each with its count. Each record's number counts its joined rows, so a pair that two rows hold counts twice. In either direction the related record must exist, with a whole key, and pass the row filter of its class, which a forward link count does not ask. So the numbers need not add up to `linkCount`. With the measure `linkCount` it returns one number, the links of the relation. A link is a pair of a record of the class that binds the relation and an object key with no null part. The record passes the row filter of its class, and a row of a link table or another contributing table counts only when it passes that table's own row filter. Forward from the binding class the count is every link. The object need not be a record. Inverse from the other class it is the links whose object is a record of the class asked, and the row filter of the object class applies only when the count starts from it.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyAggregateStatementRequest", + "properties": { + "version": { + "$ref": "ontologyStatementPlan.json#/definitions/version" + }, + "relation": { + "description": "Id of the object property to follow.", + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "direction": { + "$ref": "ontologyStatementPlan.json#/definitions/direction" + }, + "measure": { + "description": "What to count along the relation. Only a request that names a relation and a direction takes one, and a request that names none counts `topRecords`.", + "$ref": "ontologyStatementPlan.json#/definitions/measure" + }, + "relatedClass": { + "description": "Id of the class at the far end of the relation. Leave it out when the relation names one class on that side, its range for `forward` and its domain for `inverse`.", + "$ref": "../../type/basic.json#/definitions/uuid" + } + }, + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyConceptQuery.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyConceptQuery.json index 0703642fca39..45a25bf5090d 100644 --- a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyConceptQuery.json +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyConceptQuery.json @@ -21,7 +21,7 @@ }, "direction": { "$ref": "#/definitions/direction" }, "label": { - "description": "Relation label written as the JOIN comment. Set by the server.", + "description": "Relation label of the hop. It is returned beside the SQL and is never part of it. Set by the server.", "type": "string" } }, @@ -50,7 +50,11 @@ "default": [] }, "sql": { - "description": "Generated SELECT with LIMIT 50. Set by the server.", + "description": "Generated SELECT limited to 50 rows, for a person to read. It starts from the only bound table of the concept, or from its identity table when the concept binds several tables, and applies the row filter of each table it reads. Every colon is written as a colon. Do not pass it to a library that reads `:name` as a bind parameter. Set by the server.", + "type": "string" + }, + "escapedSql": { + "description": "The same statement with every colon written as a backslash and a colon. It is the only form to run through a SQLAlchemy `text()` call, which reads `\\:` as a colon and would read a bare colon as the start of a bind parameter. Set by the server.", "type": "string" }, "dialect": { "$ref": "#/definitions/dialect" }, diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json new file mode 100644 index 000000000000..118e68d81e77 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyExpandStatementRequest.json @@ -0,0 +1,38 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/ontologyExpandStatementRequest.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyExpandStatementRequest", + "description": "Asks for the statement that lists the records one record relates to along one relation. The statement asks for 26 rows, and the 26th says only that more exist. It orders the related records by their key, so a client reads the next page by sending the key of the last related record it holds as `after`. The engine compares and orders with its own collation, so a client must not merge pages that came from two connections.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyExpandStatementRequest", + "properties": { + "version": { + "$ref": "ontologyStatementPlan.json#/definitions/version" + }, + "key": { + "$ref": "ontologyStatementPlan.json#/definitions/key" + }, + "relation": { + "description": "Id of the object property to follow.", + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "direction": { + "$ref": "ontologyStatementPlan.json#/definitions/direction" + }, + "after": { + "description": "The key of the last related record the client holds, in the key order of the related class, typed as `key` is: one value for each column of the related key, each parsed as the data type of its column. The statement then returns the related records whose key comes after it. Leave it out, or send an empty list, to start at the first related record. A value of the wrong type for its column, or a number of values other than the key has, is a 400. Two keys that the engine's collation holds equal compare as one key, such as `x` and `X` under MySQL's default collation, so a page that ends on one of them starts after both and the other is skipped.", + "type": "array", + "items": { "description": "A string, a number or a boolean." } + }, + "relatedClass": { + "description": "Id of the class at the far end of the relation. Leave it out when the relation names one class on that side, its range for `forward` and its domain for `inverse`.", + "$ref": "../../type/basic.json#/definitions/uuid" + } + }, + "required": [ + "key", + "relation", + "direction" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyFindStatementRequest.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyFindStatementRequest.json new file mode 100644 index 000000000000..35f5bf4aab51 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyFindStatementRequest.json @@ -0,0 +1,18 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/ontologyFindStatementRequest.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyFindStatementRequest", + "description": "Asks for the statement that lists records of a class: the key, the display name and the bound columns of its identity table, at most 25 rows.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyFindStatementRequest", + "properties": { + "version": { + "$ref": "ontologyStatementPlan.json#/definitions/version" + }, + "matchText": { + "description": "Text to look for in the display name. Empty text matches every record. Text with no uppercase letter matches without regard to case. Text with an uppercase letter is compared as the engine compares the column. It takes at most 256 characters and no control character. A class that binds no display name column on its identity table takes no match text.", + "type": "string" + } + }, + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyMappingHealth.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyMappingHealth.json new file mode 100644 index 000000000000..d5d072ba88dd --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyMappingHealth.json @@ -0,0 +1,111 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/ontologyMappingHealth.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyMappingHealth", + "description": "One page of what an editor must fix before the table bindings of an ontology's classes can be read as records. The check reads catalog metadata only and never queries a bound table. It examines table bindings in class then table id order, a bounded number per request, and names only tables the caller may view. A hidden or deleted table contributes no entry, name or count.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyMappingHealth", + "definitions": { + "columnPath": { + "description": "The exact name segments from a top-level column to the column named, as a column binding spells them. Absent on a finding that names no column.", + "type": "array", + "items": { "type": "string" }, + "default": null + }, + "entryType": { + "description": "What is wrong. `noIdentityTable`: the class has table bindings and none is its identity table. `unassignedBinding`: the table binding has no role. `relationColumnWithoutJoin`: a column bound to an OBJECT property has no join. `joinNotConfirmed`: a join is still `inferred`. `keyLengthMismatch`: a contributing table's subject key has a different number of columns than the identity table's. `keyTypeMismatch`: a contributing table's key column and the identity table's key column at the same position hold different kinds of data. `joinTypeMismatch`: the two columns of a join pair hold different kinds of data. `outsideMappingSource`: the bound table sits outside the ontology's mapping source. `multipleDatabases`: the ontology names no mapping source and its bound tables sit in more than one database. It is reported on each page that finds a database no earlier page found, once two are known. `sensitiveKeyColumn`: a subject key column of a table that has a role is tagged `PII.Sensitive`, or sits under a column that is, or its table is, so its sample data and profile are masked. `columnTypeMismatch`: a column bound to a DATA property whose range is one XSD datatype holds a kind of data that datatype does not fit, for example a text column for an integer property. Both are advice and refuse nothing.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyMappingHealthEntryType", + "enum": [ + "noIdentityTable", + "unassignedBinding", + "relationColumnWithoutJoin", + "joinNotConfirmed", + "keyLengthMismatch", + "keyTypeMismatch", + "joinTypeMismatch", + "outsideMappingSource", + "multipleDatabases", + "sensitiveKeyColumn", + "columnTypeMismatch" + ] + }, + "entry": { + "description": "One finding. `type` decides which of the other fields are present.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyMappingHealthEntry", + "properties": { + "type": { "$ref": "#/definitions/entryType" }, + "concept": { + "description": "The class the finding is about. Absent on `multipleDatabases`.", + "$ref": "../../type/entityReference.json" + }, + "asset": { + "description": "The bound table the finding is about. Absent on `noIdentityTable` and `multipleDatabases`.", + "$ref": "../../type/entityReference.json" + }, + "relatedAsset": { + "description": "The identity table on the key findings, and the join target on the join findings when the caller may view it.", + "$ref": "../../type/entityReference.json" + }, + "property": { + "description": "The property of the bound column on the relation column, join and `columnTypeMismatch` findings, when the caller may view it.", + "$ref": "../../type/entityReference.json" + }, + "columnPath": { + "description": "A column of `asset`: the bound column on `relationColumnWithoutJoin`, `joinNotConfirmed` and `columnTypeMismatch`, the key column on `keyTypeMismatch` and `sensitiveKeyColumn`, and the child column on `joinTypeMismatch`.", + "$ref": "#/definitions/columnPath" + }, + "relatedColumnPath": { + "description": "The column of `relatedAsset` that `columnPath` is paired with, on `keyTypeMismatch` and `joinTypeMismatch`.", + "$ref": "#/definitions/columnPath" + }, + "dataType": { + "description": "Data type of `columnPath` on the type findings and on `columnTypeMismatch`.", + "$ref": "../../entity/data/table.json#/definitions/dataType" + }, + "relatedDataType": { + "description": "Data type of `relatedColumnPath` on the type findings.", + "$ref": "../../entity/data/table.json#/definitions/dataType" + }, + "propertyDatatype": { + "description": "The IRI of the XSD datatype that is the range of `property`, on `columnTypeMismatch`.", + "$ref": "../../type/ontologyIri.json" + }, + "keyLength": { + "description": "Number of subject key columns of `asset`, on `keyLengthMismatch`.", + "type": "integer" + }, + "relatedKeyLength": { + "description": "Number of subject key columns of the identity table, on `keyLengthMismatch`.", + "type": "integer" + }, + "databases": { + "description": "The database of `asset` on `outsideMappingSource`, and every database found so far on `multipleDatabases`.", + "type": "array", + "items": { "$ref": "../../type/entityReference.json" }, + "default": null + } + }, + "required": ["type"], + "additionalProperties": false + } + }, + "properties": { + "mappingSource": { + "description": "The ontology's mapping source, when it names one.", + "$ref": "../../type/entityReference.json" + }, + "entries": { + "type": "array", + "items": { "$ref": "#/definitions/entry" }, + "default": [] + }, + "after": { + "description": "Cursor for the next page. Absent when no table bindings follow. A page can hold no entries while a cursor follows.", + "type": "string" + } + }, + "required": ["entries"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyOpenStatementRequest.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyOpenStatementRequest.json new file mode 100644 index 000000000000..50f2cf0d145b --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyOpenStatementRequest.json @@ -0,0 +1,20 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/ontologyOpenStatementRequest.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyOpenStatementRequest", + "description": "Asks for the statement that reads one record: every bound column of its identity table and of the contributing tables the caller may view.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyOpenStatementRequest", + "properties": { + "version": { + "$ref": "ontologyStatementPlan.json#/definitions/version" + }, + "key": { + "$ref": "ontologyStatementPlan.json#/definitions/key" + } + }, + "required": [ + "key" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json new file mode 100644 index 000000000000..e2a262eeb1a0 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeChecks.json @@ -0,0 +1,254 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/ontologyShapeChecks.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyShapeChecks", + "description": "How each constraint of the shapes that target a class is checked on the tables the class binds. A constraint is answered part by part: by a data quality test that finds a violation exactly when a record breaks the part, by nothing because the mapping already holds it, or not at all, and then with the reason. Nothing is created, scheduled or run (ADR:2026-11-23-a-shape-check-is-exact-or-it-is-not-offered).", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeChecks", + "definitions": { + "part": { + "description": "One part of a constraint. `range` is `minInclusive` and `maxInclusive` together.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyShapePart", + "enum": ["minCount", "maxCount", "class", "datatype", "range", "in", "pattern"] + }, + "outcome": { + "description": "How a part is checked. `check` carries the tests that check it. `heldByMapping` needs no test, because the table bindings already hold the part for every record. `notMapped` means the class binds the property in no column, or the version read has no such property. `notEnforceable` means no test finds exactly the records that break the part, and `reason` says why. `hidden` means the caller may not view a table the answer rests on, or the property the constraint is about.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheckOutcome", + "enum": ["check", "heldByMapping", "notMapped", "notEnforceable", "hidden"] + }, + "reason": { + "description": "Why a part has no exact test. `noIdentityTable`: the class binds the property and has no identity table, so it has no records. `severalTables`: the class binds the property in several columns, and a count over all of them has no test. `boundOnInverse`: the class does not bind the relation and another class binds its inverse. `noJoin` and `joinNotConfirmed`: the relation has no join, or one that is only inferred. `notARelation` and `notADataProperty`: the part asks for the other kind of property. `targetClassNotOnJoin`: the class the part names has no identity table where the join arrives. `subclassOnJoinTable`: a subclass of that class has its identity table there too, and the filter of the class would leave its records out. `valuesAreRecords`: the list names records by IRI. `valueDoesNotFitColumn`: a value does not parse as the data type of the column. `tooManyValues`: the list has more than 1,000 values. `columnTypeNotSupported`: the data type of the column takes no such comparison. `datatypeNotSupported`: the datatype is not one this answer reads. `datatypeMismatch`: nothing shows that every value the column can store is of the datatype, because its data type stores other values on this engine or was not read for it. `patternNotPortable`: the pattern leaves the constructs that are known to be read as SHACL reads them, or is too long for a statement. `columnMissing`: a column of the binding left the table. `otherDatabase`: a table sits in another database than the identity table. `engineNotSupported`: no statement is written for the service type, or none that asks this part. A pattern is matched on Postgres only.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheckReason", + "enum": [ + "noIdentityTable", + "severalTables", + "boundOnInverse", + "noJoin", + "joinNotConfirmed", + "notARelation", + "notADataProperty", + "targetClassNotOnJoin", + "subclassOnJoinTable", + "valuesAreRecords", + "valueDoesNotFitColumn", + "tooManyValues", + "columnTypeNotSupported", + "datatypeNotSupported", + "datatypeMismatch", + "patternNotPortable", + "columnMissing", + "otherDatabase", + "engineNotSupported" + ] + }, + "readBinding": { + "description": "One table binding that a check was built from, with the binding revision of its class.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheckBinding", + "properties": { + "conceptId": { + "description": "Id of the class that binds the table.", + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "assetId": { + "description": "Id of the bound table.", + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "revision": { + "description": "Revision of the bindings of the class, as the bindings endpoint returns it.", + "type": "integer", + "minimum": 0, + "existingJavaType": "java.lang.Long" + } + }, + "required": ["conceptId", "assetId", "revision"], + "additionalProperties": false + }, + "proposalState": { + "description": "Whether a check has reached its table as a test case. `none`: no proposal exists. `proposed`: a suggestion task is open. `rejected`: a person rejected the suggestion of the current content. `accepted`: the test case exists.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheckProposalState", + "enum": ["none", "proposed", "rejected", "accepted"] + }, + "proposal": { + "description": "How a check stands as a test on its table. A reference is left out when the caller may not view the task or the test case.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheckProposal", + "properties": { + "state": { "$ref": "#/definitions/proposalState" }, + "task": { + "description": "The suggestion task. Present for `proposed` and `rejected` when the caller may view it.", + "$ref": "../../type/entityReference.json" + }, + "testCase": { + "description": "The test case. Present for `accepted` when the caller may view it.", + "$ref": "../../type/entityReference.json" + }, + "latestResultStatus": { + "description": "Status of the latest result of the test case. Absent when it has no result or the caller may not view the test case.", + "$ref": "../../tests/basic.json#/definitions/testCaseStatus" + }, + "latestResultTimestamp": { + "description": "Time of the latest result of the test case.", + "$ref": "../../type/basic.json#/definitions/timestamp" + } + }, + "required": ["state"], + "additionalProperties": false + }, + "check": { + "description": "One data quality test on one table: the test `tableCustomSQLQuery` with a statement written for the part. `testDefinition`, `entityLink` and `parameterValues` are what a request to create a test case takes. The result of the test is 0 violations exactly when every record of the class satisfies the part.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeCheck", + "properties": { + "identity": { + "description": "Lowercase hex SHA-256 of the shape id, the constraint id, the part, the class id, the table id and the bound column path. It names the check and does not depend on a value of the constraint, so a changed bound keeps it.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "table": { + "description": "The table the test belongs to: the one whose binding holds the property, which is a link table when a link table holds a relation.", + "$ref": "../../type/entityReference.json" + }, + "columns": { + "description": "The columns of that table that hold the values the test reads: the bound column of a data property, or the columns of the join of a relation.", + "type": "array", + "items": { "$ref": "../../type/ontologyConceptBindings.json#/definitions/columnPath" }, + "default": [] + }, + "testDefinition": { + "description": "Fully qualified name of the test definition, which is `tableCustomSQLQuery` for every check.", + "$ref": "../../type/basic.json#/definitions/fullyQualifiedEntityName" + }, + "entityLink": { + "description": "The table that the test is created on.", + "$ref": "../../type/basic.json#/definitions/entityLink" + }, + "parameterValues": { + "description": "The parameters of the test: the statement in `sqlExpression`, with every colon written as a backslash and a colon, then `strategy` `COUNT`, `operator` `<=` and `threshold` `0`. The statement returns one number, the records in violation.", + "type": "array", + "items": { "$ref": "../../tests/testCase.json#/definitions/testCaseParameterValue" }, + "default": [] + }, + "inspectionQuery": { + "description": "The statement that lists the keys of the records in violation, for a person to read.", + "$ref": "../../type/basic.json#/definitions/sqlQuery" + }, + "readBindings": { + "description": "Every table binding the check read: the identity table of the class, the table that holds the property, and the identity table of the class a `class` part names. All revisions come from one consistent read.", + "type": "array", + "items": { "$ref": "#/definitions/readBinding" }, + "default": [] + }, + "proposal": { + "description": "How the check stands as a test on its table.", + "$ref": "#/definitions/proposal" + } + }, + "required": [ + "identity", + "table", + "columns", + "testDefinition", + "entityLink", + "parameterValues", + "inspectionQuery", + "readBindings" + ], + "additionalProperties": false + }, + "checkedPart": { + "description": "How one part of a constraint is checked. When the class binds the property in several tables and they do not all give the same answer, the part has one entry for each answer.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyCheckedPart", + "properties": { + "part": { "$ref": "#/definitions/part" }, + "outcome": { "$ref": "#/definitions/outcome" }, + "reason": { + "description": "Present exactly when the outcome is `notEnforceable`.", + "$ref": "#/definitions/reason" + }, + "checks": { + "description": "One test for each table. Present exactly when the outcome is `check`.", + "type": "array", + "items": { "$ref": "#/definitions/check" }, + "default": null + } + }, + "required": ["part", "outcome"], + "additionalProperties": false + }, + "checkedConstraint": { + "description": "One constraint of a shape with the answer for each part it states.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyCheckedConstraint", + "properties": { + "id": { + "description": "Id of the constraint within its shape.", + "type": "string" + }, + "path": { + "description": "IRI of the property the constraint is about. Absent when the caller may not view that property.", + "$ref": "../../type/ontologyIri.json" + }, + "parts": { + "description": "The parts the constraint states, in the order `minCount`, `maxCount`, `class`, `datatype`, `range`, `in`, `pattern`.", + "type": "array", + "items": { "$ref": "#/definitions/checkedPart" }, + "default": [] + } + }, + "required": ["id", "parts"], + "additionalProperties": false + }, + "checkedShape": { + "description": "One shape that targets the class.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyCheckedShape", + "properties": { + "id": { + "description": "Id of the shape.", + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "name": { + "description": "Name of the shape.", + "$ref": "../../type/basic.json#/definitions/entityName" + }, + "severity": { "$ref": "../../entity/data/ontologyShape.json#/definitions/severity" }, + "constraints": { + "description": "The constraints of the shape, in the order the shape holds them.", + "type": "array", + "items": { "$ref": "#/definitions/checkedConstraint" }, + "default": [] + } + }, + "required": ["id", "name", "severity", "constraints"], + "additionalProperties": false + } + }, + "properties": { + "conceptId": { + "description": "Id of the class.", + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "classIri": { + "description": "IRI of the class.", + "$ref": "../../type/ontologyIri.json" + }, + "version": { + "description": "The version of the ontology that the class, its shapes and its properties were read from. Table bindings sit outside versions and are always current.", + "$ref": "ontologyStatementPlan.json#/definitions/versionRead" + }, + "shapes": { + "description": "The shapes of that version that target the class and that the caller may view, in name order. A shape that targets a parent of the class is not listed.", + "type": "array", + "items": { "$ref": "#/definitions/checkedShape" }, + "default": [] + } + }, + "required": ["conceptId", "classIri", "version", "shapes"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeImportResult.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeImportResult.json new file mode 100644 index 000000000000..f83aea2e574f --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyShapeImportResult.json @@ -0,0 +1,96 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/ontologyShapeImportResult.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyShapeImportResult", + "description": "What a SHACL import wrote, and every construct of the file it did not take over.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyShapeImportResult", + "definitions": { + "action": { + "javaType": "org.openmetadata.schema.api.data.OntologyShapeImportAction", + "type": "string", + "enum": [ + "CREATED", + "UPDATED" + ] + }, + "shape": { + "javaType": "org.openmetadata.schema.api.data.OntologyShapeImported", + "description": "A shape the import wrote, or would write on a dry run.", + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "action": { + "$ref": "#/definitions/action" + }, + "constraintIds": { + "type": "array", + "items": { + "type": "string" + }, + "default": [] + } + }, + "required": [ + "name", + "action", + "constraintIds" + ], + "additionalProperties": false + }, + "unsupported": { + "javaType": "org.openmetadata.schema.api.data.OntologyShapeUnsupportedConstruct", + "description": "A SHACL construct of the file the shape model does not hold. Reporting it is not an error: the supported parts of the file are imported.", + "type": "object", + "properties": { + "construct": { + "description": "The construct by name, such as sh:or.", + "type": "string" + }, + "shape": { + "description": "Name of the node shape that carries it, when it has one.", + "type": "string" + }, + "path": { + "description": "Full IRI of the property the construct constrains, when it constrains one.", + "$ref": "../../type/ontologyIri.json" + }, + "message": { + "type": "string" + } + }, + "required": [ + "construct", + "message" + ], + "additionalProperties": false + } + }, + "properties": { + "dryRun": { + "type": "boolean" + }, + "shapes": { + "type": "array", + "items": { + "$ref": "#/definitions/shape" + }, + "default": [] + }, + "unsupported": { + "type": "array", + "items": { + "$ref": "#/definitions/unsupported" + }, + "default": [] + } + }, + "required": [ + "dryRun", + "shapes", + "unsupported" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json new file mode 100644 index 000000000000..3f14abf995e8 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/api/data/ontologyStatementPlan.json @@ -0,0 +1,238 @@ +{ + "$id": "https://open-metadata.org/schema/api/data/ontologyStatementPlan.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyStatementPlan", + "description": "One generated SELECT about the records of a class, with a column plan that says what each result column holds. A record is a row of the identity table of its class, and its id is the class IRI with the values of the subject key of that table. OpenMetadata writes the statement and never runs it (ADR:2026-11-22-record-statements-start-from-the-identity-table).", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyStatementPlan", + "definitions": { + "version": { + "description": "Which version of the ontology a statement reads. `release` is the active release. `draft` is the working draft, and reading it takes `EditAll` on the ontology. The class, its properties, the display name flag and the relations come from that version. Bindings sit outside versions and are always current.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyStatementVersion", + "enum": ["release", "draft"], + "default": "release" + }, + "direction": { + "description": "Which way a statement follows a relation. `forward` goes from a record of the class that binds the relation to the records it names. `inverse` goes from a named record back to the records that name it.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyStatementDirection", + "enum": ["forward", "inverse"] + }, + "key": { + "description": "The key of one record: one value for each column of the subject key of the identity table of its class, in key order. Each value is parsed as the data type of its column, and a value that does not parse is a 400 that names the column, the data type and the problem.", + "type": "array", + "items": { "description": "A string, a number or a boolean." } + }, + "measure": { + "description": "What an aggregate over a relation counts. `topRecords` returns the 8 records of the class that relate to the most records along the relation, each with its count. Each record's number counts its joined rows, so a pair that two rows hold counts twice. In either direction the related record must exist, with a whole key, and pass the row filter of its class, which a forward link count does not ask. So the numbers need not add up to `linkCount`. `linkCount` returns one number, the links of the relation. A link is a pair of a record of the class that binds the relation and an object key with no null part. The record passes the row filter of its class, and a row of a link table or another contributing table counts only when it passes that table's own row filter. Forward from the binding class the count is every link. Inverse from the other class it is the links whose object is a record of the start class, and the object need not be a record when the count starts from the binding class. A request that names none asks for `topRecords`.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyStatementMeasure", + "enum": ["topRecords", "linkCount"] + }, + "statementKind": { + "description": "What a statement asks. `find` lists records of a class. `expand` lists the records that one record relates to. `open` reads every bound column of one record. `aggregate` counts.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyStatementKind", + "enum": ["find", "expand", "open", "aggregate"] + }, + "engineFamily": { + "description": "The engines that read a name, a string and a `LIKE` pattern the same way. The family of the service writes every name and every value of the statement.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyStatementEngineFamily", + "enum": [ + "postgres", + "redshift", + "trino", + "mysql", + "clickhouse", + "bigquery", + "snowflake", + "spark", + "tsql" + ] + }, + "columnKind": { + "description": "What a result column holds. `key` is one part of a record key. `displayName` is the value of the display name property of the class. `property` is the value of one data property. `count` is a number of records.", + "type": "string", + "javaType": "org.openmetadata.schema.api.data.OntologyStatementColumnKind", + "enum": ["key", "displayName", "property", "count"] + }, + "column": { + "description": "One result column of the statement.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyStatementColumn", + "properties": { + "index": { + "description": "Position of the column in each result row, from zero.", + "type": "integer", + "minimum": 0 + }, + "kind": { "$ref": "#/definitions/columnKind" }, + "classIri": { + "description": "IRI of the class whose record the column describes. A `count` column of a class count carries the counted class, and a `count` column of a relation carries the class of the records that were counted.", + "$ref": "../../type/ontologyIri.json" + }, + "keyPart": { + "description": "For a `key` column, its position in the subject key of the class, from zero.", + "type": "integer", + "minimum": 0 + }, + "propertyIri": { + "description": "For a `displayName` or `property` column, the IRI of the data property it holds.", + "$ref": "../../type/ontologyIri.json" + } + }, + "required": ["index", "kind", "classIri"], + "additionalProperties": false + }, + "relation": { + "description": "The relation a statement follows.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyStatementRelation", + "properties": { + "propertyIri": { + "description": "IRI of the object property.", + "$ref": "../../type/ontologyIri.json" + }, + "direction": { "$ref": "#/definitions/direction" }, + "relatedClassIri": { + "description": "IRI of the class at the far end of the relation.", + "$ref": "../../type/ontologyIri.json" + } + }, + "required": ["propertyIri", "direction", "relatedClassIri"], + "additionalProperties": false + }, + "versionRead": { + "description": "The version of the ontology that the statement was built from.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyStatementVersionRead", + "properties": { + "kind": { "$ref": "#/definitions/version" }, + "releaseId": { + "description": "Id of the active release, when the statement read a release.", + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "releaseRevision": { + "description": "Release number of that release.", + "type": "integer", + "minimum": 1, + "existingJavaType": "java.lang.Long" + }, + "semanticVersion": { + "description": "Semantic version of that release. Absent on a release that has none.", + "type": "string" + }, + "workingRevision": { + "description": "Working revision of the ontology, when the statement read the draft.", + "type": "integer", + "minimum": 0, + "existingJavaType": "java.lang.Long" + } + }, + "required": ["kind"], + "additionalProperties": false + }, + "bindingRevision": { + "description": "The binding revision of one class whose bindings the statement was built from.", + "type": "object", + "javaType": "org.openmetadata.schema.api.data.OntologyStatementBindingRevision", + "properties": { + "conceptId": { + "description": "Id of the class.", + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "classIri": { + "description": "IRI of the class.", + "$ref": "../../type/ontologyIri.json" + }, + "revision": { + "description": "Revision of the bindings of the class, as the bindings endpoint returns it.", + "type": "integer", + "minimum": 0, + "existingJavaType": "java.lang.Long" + } + }, + "required": ["conceptId", "classIri", "revision"], + "additionalProperties": false + } + }, + "properties": { + "statement": { "$ref": "#/definitions/statementKind" }, + "sql": { + "description": "The statement for a person to read, with every colon written as a colon. It is a single SELECT in the dialect of the engine and carries its own `LIMIT` or `TOP`. Do not pass it to a library that reads `:name` as a bind parameter.", + "type": "string" + }, + "escapedSql": { + "description": "The same statement with every colon written as a backslash and a colon. It is the only form to run through a SQLAlchemy `text()` call, which reads `\\:` as a colon and would read a bare colon as the start of a bind parameter.", + "type": "string" + }, + "family": { "$ref": "#/definitions/engineFamily" }, + "dialect": { "$ref": "ontologyConceptQuery.json#/definitions/dialect" }, + "service": { + "description": "Name of the database service that holds the tables the statement reads.", + "type": "string" + }, + "serviceType": { + "description": "Type of that database service.", + "type": "string" + }, + "tables": { + "description": "Fully qualified names of the tables the statement reads, in join order. A table the caller may not view is never listed.", + "type": "array", + "items": { "$ref": "../../type/basic.json#/definitions/fullyQualifiedEntityName" }, + "default": [] + }, + "columns": { + "description": "The result columns in order.", + "type": "array", + "items": { "$ref": "#/definitions/column" }, + "default": [] + }, + "relation": { "$ref": "#/definitions/relation" }, + "measure": { + "description": "What an aggregate over a relation counts. Absent on every other statement, including the count of a class.", + "$ref": "#/definitions/measure" + }, + "rowCap": { + "description": "The most rows a reader takes from the result. `find` and `expand` take 25, `open` takes 100, a relation count takes 8, and a class count and a link count take 1.", + "type": "integer", + "minimum": 1 + }, + "extraRow": { + "description": "Whether the statement asks for one row more than `rowCap`. That row is not part of the answer. It says only that more rows exist.", + "type": "boolean", + "default": false + }, + "orderedBy": { + "description": "The indexes of the result columns that hold the key of the related record, in key order, for a client to send the values of these columns in the last row it keeps as `after` and read the next page. Only an `expand` statement sets it, and only when every column of its related key has a type the generator writes values for, such as a number or a string and not JSON. Every other statement leaves it empty, `topRecords` too, though it orders by its count. An empty list means the statement takes no `after`.", + "type": "array", + "items": { "type": "integer", "minimum": 0 }, + "default": [] + }, + "version": { "$ref": "#/definitions/versionRead" }, + "bindingRevisions": { + "description": "The binding revision of every class whose bindings the statement read. A statement that follows a relation names both classes.", + "type": "array", + "items": { "$ref": "#/definitions/bindingRevision" }, + "default": [] + } + }, + "required": [ + "statement", + "sql", + "escapedSql", + "family", + "dialect", + "service", + "serviceType", + "tables", + "columns", + "rowCap", + "extraRow", + "version", + "bindingRevisions" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontology.json b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontology.json index 02da5912e1c2..5a29ac754853 100644 --- a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontology.json +++ b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontology.json @@ -95,6 +95,10 @@ "approvalRule": { "description": "How many reviewers must approve a release review. Frozen into each review task when a review is requested.", "$ref": "../../type/ontologyApprovalRule.json" + }, + "mappingSource": { + "description": "The one database whose tables this ontology's classes bind. Once it is set, every table binding written for a class of this ontology must sit in this database. Bindings written earlier are left as they are and listed by the mapping health read. It is operational metadata. A change of it records no new version of the ontology, and releases and their digests leave it out. Setting, changing or clearing it requires EditAll on the ontology. Request it with `fields=mappingSource`.", + "$ref": "../../type/entityReference.json" } }, "required": [ diff --git a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyChangeSet.json b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyChangeSet.json index d9ed082b38fa..b1a65603add7 100644 --- a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyChangeSet.json +++ b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyChangeSet.json @@ -47,11 +47,13 @@ "$ref": "#/definitions/state" }, "operations": { + "description": "The operations of the draft. Reads that ask the draft read right return them. A stored change event never holds them, because an event reaches every subscriber and the server cannot know who may read the draft.", "type": "array", "items": { "$ref": "../../type/ontologyChangeOperation.json" }, - "default": [] + "default": [], + "mask": true }, "undoCursor": { "description": "Number of active operations at the current undo/redo position.", diff --git a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyProperty.json b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyProperty.json index aeedf17dfca1..aa1165944dee 100644 --- a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyProperty.json +++ b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyProperty.json @@ -127,6 +127,10 @@ "type": "boolean", "default": false }, + "isDisplayName": { + "description": "Marks a DATA property as the one whose value names its class's instances. This annotation does not assert functionality or uniqueness. A class has at most one such property, and the field is absent when unset.", + "type": "boolean" + }, "inverse": { "description": "Semantic IRI of the inverse object property.", "$ref": "../../type/ontologyIri.json" diff --git a/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyShape.json b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyShape.json new file mode 100644 index 000000000000..e5e987e9f253 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/entity/data/ontologyShape.json @@ -0,0 +1,104 @@ +{ + "$id": "https://open-metadata.org/schema/entity/data/ontologyShape.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyShape", + "description": "A SHACL node shape that targets one class of an ontology and lists constraints on the properties of its instances.", + "$comment": "@om-entity-type", + "type": "object", + "javaType": "org.openmetadata.schema.entity.data.OntologyShape", + "javaInterfaces": [ + "org.openmetadata.schema.EntityInterface", + "org.openmetadata.schema.OntologyDefinition" + ], + "definitions": { + "severity": { + "javaType": "org.openmetadata.schema.type.OntologyShapeSeverity", + "description": "How serious a failed constraint is, as SHACL defines the severities.", + "type": "string", + "enum": [ + "Violation", + "Warning", + "Info" + ] + } + }, + "properties": { + "id": { + "$ref": "../../type/basic.json#/definitions/uuid" + }, + "name": { + "$ref": "../../type/basic.json#/definitions/entityName" + }, + "displayName": { + "type": "string" + }, + "fullyQualifiedName": { + "$ref": "../../type/basic.json#/definitions/fullyQualifiedEntityName" + }, + "description": { + "$ref": "../../type/basic.json#/definitions/markdown" + }, + "ontology": { + "$ref": "../../type/entityReference.json" + }, + "targetConcept": { + "description": "Full IRI of the class the shape applies to.", + "$ref": "../../type/ontologyIri.json" + }, + "severity": { + "$ref": "#/definitions/severity" + }, + "constraints": { + "description": "Constraints on the properties of the target class, in authored order.", + "type": "array", + "items": { + "$ref": "../../type/ontologyShapeConstraint.json" + }, + "default": [] + }, + "owners": { + "$ref": "../../type/entityReferenceList.json" + }, + "version": { + "$ref": "../../type/entityHistory.json#/definitions/entityVersion" + }, + "updatedAt": { + "$ref": "../../type/basic.json#/definitions/timestamp" + }, + "updatedBy": { + "type": "string" + }, + "impersonatedBy": { + "description": "Bot user that performed the action on behalf of the actual user.", + "$ref": "../../type/basic.json#/definitions/impersonatedBy" + }, + "href": { + "$ref": "../../type/basic.json#/definitions/href" + }, + "changeDescription": { + "$ref": "../../type/entityHistory.json#/definitions/changeDescription" + }, + "incrementalChangeDescription": { + "$ref": "../../type/entityHistory.json#/definitions/changeDescription" + }, + "deleted": { + "type": "boolean", + "default": false + }, + "provider": { + "$ref": "../../type/basic.json#/definitions/providerType" + } + }, + "required": [ + "id", + "name", + "displayName", + "fullyQualifiedName", + "description", + "ontology", + "targetConcept", + "severity", + "constraints" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/tests/testCase.json b/openmetadata-spec/src/main/resources/json/schema/tests/testCase.json index 191c33d82b0d..30c423d142dd 100644 --- a/openmetadata-spec/src/main/resources/json/schema/tests/testCase.json +++ b/openmetadata-spec/src/main/resources/json/schema/tests/testCase.json @@ -7,6 +7,70 @@ "javaType": "org.openmetadata.schema.tests.TestCase", "javaInterfaces": ["org.openmetadata.schema.EntityInterface"], "definitions": { + "generatedByBinding": { + "type": "object", + "javaType": "org.openmetadata.schema.tests.TestCaseGeneratedByBinding", + "description": "One table binding that the statement of a generated test was built from, with the binding revision of its class.", + "properties": { + "conceptId": { + "description": "Id of the class that binds the table.", + "$ref": "../type/basic.json#/definitions/uuid" + }, + "assetId": { + "description": "Id of the bound table.", + "$ref": "../type/basic.json#/definitions/uuid" + }, + "revision": { + "description": "Revision of the bindings of the class when the test was generated.", + "type": "integer", + "minimum": 0, + "existingJavaType": "java.lang.Long" + } + }, + "required": ["conceptId", "assetId", "revision"], + "additionalProperties": false + }, + "generatedBy": { + "type": "object", + "javaType": "org.openmetadata.schema.tests.TestCaseGeneratedBy", + "description": "Where a generated test comes from: the part of a shape constraint it checks on one table. Only a suggestion that creates the test and the server's own reconcile set it, and the test definition, the entity link and the parameter values of such a test cannot be edited.", + "properties": { + "identity": { + "description": "Lowercase hex SHA-256 that names the check. It holds no test definition and no value of the constraint, so a changed bound keeps it.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "shape": { + "description": "The shape whose constraint the test checks.", + "$ref": "../type/entityReference.json" + }, + "constraintId": { + "description": "Id of the constraint within its shape.", + "type": "string" + }, + "part": { + "description": "The part of the constraint the test checks: minCount, maxCount, class, datatype, range, in or pattern.", + "type": "string" + }, + "class": { + "description": "The class whose records the test counts violations of.", + "$ref": "../type/entityReference.json" + }, + "readBindings": { + "description": "Every table binding the statement was built from.", + "type": "array", + "items": { "$ref": "#/definitions/generatedByBinding" }, + "default": [] + }, + "contentDigest": { + "description": "Lowercase hex SHA-256 of the canonical JSON of the test definition, the entity link and the parameter values.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + } + }, + "required": ["identity", "shape", "constraintId", "part", "class", "readBindings", "contentDigest"], + "additionalProperties": false + }, "testCaseParameterValue": { "type": "object", "javaType": "org.openmetadata.schema.tests.TestCaseParameterValue", @@ -148,6 +212,10 @@ "description": "SQL query to retrieve the failed rows for this test case.", "$ref": "../type/basic.json#/definitions/sqlQuery" }, + "generatedBy": { + "description": "Present when the server generated this test from a shape constraint. A create or a patch that sends it is refused, and so is a change to the test definition, the entity link or the parameter values of such a test.", + "$ref": "#/definitions/generatedBy" + }, "domains" : { "description": "Domains the test case belongs to. When not set, the test case inherits the domain from the table it belongs to.", "$ref": "../type/entityReferenceList.json" diff --git a/openmetadata-spec/src/main/resources/json/schema/type/nativeOntologyExportFormat.json b/openmetadata-spec/src/main/resources/json/schema/type/nativeOntologyExportFormat.json index f5f3a71fa9e7..34617665008e 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/nativeOntologyExportFormat.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/nativeOntologyExportFormat.json @@ -2,8 +2,8 @@ "$id": "https://open-metadata.org/schema/type/nativeOntologyExportFormat.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "NativeOntologyExportFormat", - "description": "Serializations and concept projections available for sealed native ontology releases. SKOS and SKOS-XL are written as Turtle, and CSV is the native ontology spreadsheet.", + "description": "Serializations and concept projections available for sealed native ontology releases. SKOS and SKOS-XL are written as Turtle, CSV is the native ontology spreadsheet, and SHACL is the ontology's shapes written as Turtle.", "javaType": "org.openmetadata.schema.type.NativeOntologyExportFormat", "type": "string", - "enum": ["turtle", "rdfxml", "ntriples", "jsonld", "skos", "skos-xl", "csv"] + "enum": ["turtle", "rdfxml", "ntriples", "jsonld", "skos", "skos-xl", "csv", "shacl"] } diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyBindingChange.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyBindingChange.json new file mode 100644 index 000000000000..f8c7f11f6d44 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyBindingChange.json @@ -0,0 +1,74 @@ +{ + "$id": "https://open-metadata.org/schema/type/ontologyBindingChange.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyBindingChange", + "description": "One table binding of one class, as a change set operation carries it. The class and each property are named by IRI, so the operation can refer to definitions that the same change set creates. Applying it adds or replaces the binding of this table and keeps the other bindings of the class.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyBindingChange", + "definitions": { + "join": { + "description": "How a column bound to an OBJECT property reaches the table that holds the related records. It carries no status. A join that a change set writes is stored as `inferred`, and only a write through the bindings API confirms one.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyJoinChange", + "properties": { + "targetAssetId": { + "description": "The table that holds the related records. It sits in the same database as the bound table.", + "$ref": "basic.json#/definitions/uuid" + }, + "on": { + "type": "array", + "items": { "$ref": "ontologyConceptBindings.json#/definitions/joinColumnPair" }, + "minItems": 1, + "maxItems": 16 + } + }, + "required": ["targetAssetId", "on"], + "additionalProperties": false + }, + "columnBinding": { + "description": "One property bound to one column of the table.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyColumnBindingChange", + "properties": { + "propertyIri": { + "description": "Full IRI of a DATA or OBJECT property of the ontology.", + "$ref": "ontologyIri.json" + }, + "columnPath": { "$ref": "ontologyConceptBindings.json#/definitions/columnPath" }, + "join": { + "description": "Required when the property is an OBJECT property, and not allowed otherwise.", + "$ref": "#/definitions/join" + } + }, + "required": ["propertyIri", "columnPath"], + "additionalProperties": false + } + }, + "properties": { + "classIri": { + "description": "Full IRI of the class the table is bound to.", + "$ref": "ontologyIri.json" + }, + "tableId": { + "description": "The table that holds records of the class.", + "$ref": "basic.json#/definitions/uuid" + }, + "role": { "$ref": "ontologyConceptBindings.json#/definitions/role" }, + "subjectKey": { + "description": "Present exactly when the binding has a role.", + "$ref": "ontologyConceptBindings.json#/definitions/subjectKey" + }, + "rowFilter": { + "description": "Applying an operation that sets or changes it also requires ViewSampleData on the table.", + "$ref": "ontologyConceptBindings.json#/definitions/rowFilter" + }, + "columns": { + "type": "array", + "items": { "$ref": "#/definitions/columnBinding" }, + "maxItems": 100, + "default": [] + } + }, + "required": ["classIri", "tableId"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeEvidence.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeEvidence.json new file mode 100644 index 000000000000..604aa518db79 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeEvidence.json @@ -0,0 +1,42 @@ +{ + "$id": "https://open-metadata.org/schema/type/ontologyChangeEvidence.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyChangeEvidence", + "description": "One piece of catalog metadata that supports a change set operation: a table and, when the support is narrower, some of its columns. A caller of the change set API reads and writes only the entries whose table that caller may view.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyChangeEvidence", + "definitions": { + "kind": { + "title": "EvidenceKind", + "description": "The closed set of metadata that can support an operation. `declaredKey` is a key constraint declared on the table. `storedJoinCount` is a join count that the catalog stores for the columns. `testCase` is a data quality test on the table or its columns. `lineage` is lineage that reaches the table or its columns. `profile` is a stored profile of the table or its columns. `name` is the name of the table or of its columns. `sampleData` is values seen in the sample rows that the catalog stores for the table. `measured` is a count or a rate computed by running a query against the source table, such as the distinct and null counts of a key column, or the share of the values of a join column that find a match in the target column.", + "type": "string", + "javaType": "org.openmetadata.schema.type.OntologyChangeEvidenceKind", + "enum": [ + "declaredKey", + "storedJoinCount", + "testCase", + "lineage", + "profile", + "name", + "sampleData", + "measured" + ] + } + }, + "properties": { + "tableId": { + "description": "The table the evidence is about.", + "$ref": "basic.json#/definitions/uuid" + }, + "columns": { + "description": "The columns of that table the evidence is about. Absent when it is about the table as a whole.", + "type": "array", + "items": { "$ref": "ontologyConceptBindings.json#/definitions/columnPath" }, + "maxItems": 32, + "default": null + }, + "kind": { "$ref": "#/definitions/kind" } + }, + "required": ["tableId", "kind"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeOperation.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeOperation.json index 8f8d586b9652..d8c2a0c8f05f 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeOperation.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyChangeOperation.json @@ -24,7 +24,9 @@ "UPSERT_CONCEPT", "DELETE_CONCEPT", "UPSERT_PROPERTY", - "DELETE_PROPERTY" + "DELETE_PROPERTY", + "UPSERT_BINDING", + "UPSERT_SHAPE" ] }, "state": { @@ -35,6 +37,15 @@ "UNDONE" ], "default": "ACTIVE" + }, + "basis": { + "description": "Where a proposed shape comes from. `declared` restates what the catalog already declares, such as a column constraint. `observed` generalizes from what the stored metadata shows, such as a profile.", + "javaType": "org.openmetadata.schema.type.OntologyShapeBasis", + "type": "string", + "enum": [ + "declared", + "observed" + ] } }, "properties": { @@ -48,7 +59,7 @@ "$ref": "basic.json#/definitions/uuid" }, "baseVersion": { - "description": "Version used for optimistic concurrency. Omitted for create operations.", + "description": "Version used for optimistic concurrency. Omitted for create operations. On a binding operation it is the binding revision of the class that the operation was built against, required when the table is already bound to the class.", "type": "number", "minimum": 0.1, "multipleOf": 0.1 @@ -96,7 +107,7 @@ "$ref": "#/definitions/state" }, "requiresConceptIris": { - "description": "IRIs of concepts that an import expects to create in the same change set. Applying the operation without an UPSERT_CONCEPT operation for each of them is refused.", + "description": "IRIs of concepts that the operation needs in the ontology. Applying the operation is refused unless each of them is declared by the ontology or created by an UPSERT_CONCEPT operation of the same change set. A binding or a shape operation always needs its own class, listed here or not.", "type": "array", "items": { "$ref": "ontologyIri.json" @@ -108,6 +119,34 @@ }, "property": { "$ref": "../entity/data/ontologyProperty.json" + }, + "binding": { + "description": "The payload of an UPSERT_BINDING operation.", + "$ref": "ontologyBindingChange.json" + }, + "shape": { + "description": "The payload of an UPSERT_SHAPE operation. Its `targetConcept` names the class by IRI.", + "$ref": "../entity/data/ontologyShape.json" + }, + "basis": { + "description": "Only on an UPSERT_SHAPE operation.", + "$ref": "#/definitions/basis" + }, + "evidence": { + "description": "The tables and columns that support the operation. A save stores the entries about tables its writer may view and keeps the stored entries its writer was not shown. A read returns only the entries whose table the reader may view. A change event has no single reader, so no change event and no recorded change carries an entry.", + "type": "array", + "items": { + "$ref": "ontologyChangeEvidence.json" + }, + "maxItems": 20, + "default": null, + "mask": true + }, + "withheldEvidenceCount": { + "description": "How many evidence entries a read left out of this operation because the reader may not view the table they name, or because that table no longer exists. The server sets it on every operation it returns that stores evidence. It is never stored. It is read-only in effect: a client sends it back unchanged on a save, and when it is present and differs from the number the server withholds from that writer now for the stored operation, the save is refused with a 412 and the writer reads the change set again. A save that sends none is not checked.", + "type": "integer", + "minimum": 0, + "mask": true } }, "required": [ diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindings.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindings.json index ad3f7f400b4e..5f946cad5202 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindings.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindings.json @@ -24,12 +24,87 @@ "minItems": 1, "maxItems": 32 }, + "role": { + "description": "How a bound table takes part in the records of its class. An `identity` table defines the records, and a class has at most one. A `contributing` table adds columns or relations to records the identity table defines. A binding without a role is unassigned.", + "type": "string", + "javaType": "org.openmetadata.schema.type.OntologyBindingRole", + "enum": ["identity", "contributing"] + }, + "subjectKey": { + "description": "The columns of the bound table that identify one record, in order. A contributing table lists its own columns in the order of the identity table's key, so position pairs them.", + "type": "array", + "items": { "$ref": "#/definitions/columnPath" }, + "minItems": 1, + "maxItems": 16, + "default": null + }, + "rowFilterOperator": { + "description": "The closed set of row filter comparisons. `equals`, `notEquals`, `lessThan`, `lessThanOrEquals`, `greaterThan` and `greaterThanOrEquals` compare the column with one value. `in` matches any of a list of values. `isNull` and `isNotNull` take no value.", + "type": "string", + "javaType": "org.openmetadata.schema.type.OntologyRowFilterOperator", + "enum": ["equals", "notEquals", "lessThan", "lessThanOrEquals", "greaterThan", "greaterThanOrEquals", "in", "isNull", "isNotNull"] + }, + "rowFilter": { + "description": "One comparison on one column of the bound table that says which rows belong to the class. A write that sets or changes it parses each value as the data type of the column and refuses a value that does not parse. The value is stored as written.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyRowFilter", + "properties": { + "column": { "$ref": "#/definitions/columnPath" }, + "operator": { "$ref": "#/definitions/rowFilterOperator" }, + "value": { + "description": "The value the column is compared with. A string of at most 1024 characters, a number or a boolean for the comparison operators, an array of 1 to 100 of those for `in`, and absent for `isNull` and `isNotNull`." + } + }, + "required": ["column", "operator"], + "additionalProperties": false + }, + "joinStatus": { + "description": "Whether a person has confirmed a join. An `inferred` join is a proposal, for example one read from a declared foreign key.", + "type": "string", + "javaType": "org.openmetadata.schema.type.OntologyJoinStatus", + "enum": ["inferred", "confirmed"] + }, + "joinColumnPair": { + "description": "One equality of a join. `child` is a column of the bound table and `parent` is a column of the target table.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyJoinColumnPair", + "properties": { + "child": { "$ref": "#/definitions/columnPath" }, + "parent": { "$ref": "#/definitions/columnPath" } + }, + "required": ["child", "parent"], + "additionalProperties": false + }, + "columnJoin": { + "description": "How a column bound to an OBJECT property reaches the table that holds the related records. A key of several columns takes one pair per column.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyColumnJoin", + "properties": { + "targetAssetId": { + "description": "The table that holds the related records. It sits in the same database as the bound table.", + "$ref": "basic.json#/definitions/uuid" + }, + "status": { "$ref": "#/definitions/joinStatus" }, + "on": { + "type": "array", + "items": { "$ref": "#/definitions/joinColumnPair" }, + "minItems": 1, + "maxItems": 16 + } + }, + "required": ["targetAssetId", "status", "on"], + "additionalProperties": false + }, "columnBinding": { "type": "object", "javaType": "org.openmetadata.schema.type.OntologyColumnBinding", "properties": { "propertyId": { "$ref": "basic.json#/definitions/uuid" }, - "columnPath": { "$ref": "#/definitions/columnPath" } + "columnPath": { "$ref": "#/definitions/columnPath" }, + "join": { + "description": "Required when the property is an OBJECT property, and not allowed otherwise. Columns bound before joins existed carry none.", + "$ref": "#/definitions/columnJoin" + } }, "required": ["propertyId", "columnPath"], "additionalProperties": false @@ -40,6 +115,18 @@ "properties": { "assetType": { "$ref": "#/definitions/assetType" }, "assetId": { "$ref": "basic.json#/definitions/uuid" }, + "role": { + "description": "Tables only. Absent on bindings written before roles existed and on bindings nobody has assigned.", + "$ref": "#/definitions/role" + }, + "subjectKey": { + "description": "Tables only. Present exactly when the binding has a role.", + "$ref": "#/definitions/subjectKey" + }, + "rowFilter": { + "description": "Tables only. Setting or changing it also requires ViewSampleData on the table.", + "$ref": "#/definitions/rowFilter" + }, "columns": { "type": "array", "items": { "$ref": "#/definitions/columnBinding" }, diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindingsResponse.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindingsResponse.json index 393db033affa..0c26ef21f6c8 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindingsResponse.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyConceptBindingsResponse.json @@ -33,7 +33,15 @@ "enum": ["resolved", "unresolved"] }, "property": { "$ref": "entityReference.json" }, - "column": { "$ref": "#/definitions/column" } + "column": { "$ref": "#/definitions/column" }, + "join": { + "description": "The join as stored, so a client can send the binding back unchanged.", + "$ref": "ontologyConceptBindings.json#/definitions/columnJoin" + }, + "joinTarget": { + "description": "The join's target table. Absent when the column has no join, or when the table is deleted or hidden from the reader.", + "$ref": "entityReference.json" + } }, "required": ["propertyId", "columnPath", "state"], "additionalProperties": false @@ -49,6 +57,24 @@ "description": "Service type of the asset, for asset types that record one.", "type": "string" }, + "rowCount": { + "description": "Row count of the table's latest stored profile, always measured on the whole table. Filled only on pages of the graph page endpoint, never on this response from the concept's bindings endpoint. Present only for a table the caller may view the data profile of, whose latest profile records a row count.", + "type": "integer", + "existingJavaType": "java.lang.Long", + "format": "int64", + "minimum": 0 + }, + "profiledAt": { + "description": "Time the table's latest stored profile was taken. Filled only on pages of the graph page endpoint. Present only for a table the caller may view the data profile of that has a stored profile.", + "$ref": "basic.json#/definitions/timestamp" + }, + "sampled": { + "description": "True when that profile's column metrics were computed on a sample, as the profile itself records through its profileSample and profileSampleType. Nothing else is read, so a profile computed on a partition or a custom query reports false. Filled only on pages of the graph page endpoint. Present exactly when profiledAt is.", + "type": "boolean" + }, + "role": { "$ref": "ontologyConceptBindings.json#/definitions/role" }, + "subjectKey": { "$ref": "ontologyConceptBindings.json#/definitions/subjectKey" }, + "rowFilter": { "$ref": "ontologyConceptBindings.json#/definitions/rowFilter" }, "columns": { "type": "array", "items": { "$ref": "#/definitions/columnBinding" }, diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyDeclinedDefinition.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyDeclinedDefinition.json new file mode 100644 index 000000000000..215e279e4aa7 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyDeclinedDefinition.json @@ -0,0 +1,54 @@ +{ + "$id": "https://open-metadata.org/schema/type/ontologyDeclinedDefinition.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyDeclinedDefinition", + "description": "A definition that a person declined to add to an ontology. The record is keyed by the operation type, the definition's IRI and the digest of its content, so a definition that changes is no longer declined.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyDeclinedDefinition", + "properties": { + "ontologyId": { + "$ref": "basic.json#/definitions/uuid" + }, + "operationType": { + "$ref": "ontologyChangeOperation.json#/definitions/operationType" + }, + "iri": { + "description": "The definition's IRI. An axiom has none of its own, so it carries its subject IRI.", + "$ref": "ontologyIri.json" + }, + "payloadDigest": { + "description": "Lower-case hexadecimal SHA-256 of the definition's canonical JSON, without id, version, updatedAt, updatedBy, href and changeDescription. Only the server computes it.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "declinedBy": { + "type": "string" + }, + "declinedAt": { + "$ref": "basic.json#/definitions/timestamp" + }, + "reason": { + "type": "string", + "maxLength": 2000 + }, + "changeSetId": { + "description": "The change set the declined operation came from.", + "$ref": "basic.json#/definitions/uuid" + }, + "operationId": { + "description": "The declined operation's id in that change set.", + "$ref": "basic.json#/definitions/uuid" + } + }, + "required": [ + "ontologyId", + "operationType", + "iri", + "payloadDigest", + "declinedBy", + "declinedAt", + "changeSetId", + "operationId" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyDeclinedDefinitionMatches.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyDeclinedDefinitionMatches.json new file mode 100644 index 000000000000..ce23a62e1059 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyDeclinedDefinitionMatches.json @@ -0,0 +1,51 @@ +{ + "$id": "https://open-metadata.org/schema/type/ontologyDeclinedDefinitionMatches.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyDeclinedDefinitionMatches", + "description": "For each candidate operation, whether a declined definition matches its type, IRI and content digest. Results come in the order of the candidates.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyDeclinedDefinitionMatches", + "definitions": { + "match": { + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyDeclinedDefinitionMatch", + "properties": { + "operationId": { + "$ref": "basic.json#/definitions/uuid" + }, + "operationType": { + "$ref": "ontologyChangeOperation.json#/definitions/operationType" + }, + "iri": { + "description": "Absent for an operation that carries no definition.", + "$ref": "ontologyIri.json" + }, + "payloadDigest": { + "description": "The digest the server computed for the candidate. Absent for an operation that carries no definition.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "declined": { + "type": "boolean" + }, + "record": { + "description": "The matching record, present exactly when declined is true.", + "$ref": "ontologyDeclinedDefinition.json" + } + }, + "required": ["operationId", "operationType", "declined"], + "additionalProperties": false + } + }, + "properties": { + "matches": { + "type": "array", + "items": { + "$ref": "#/definitions/match" + }, + "default": [] + } + }, + "required": ["matches"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyDeclinedDefinitionPage.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyDeclinedDefinitionPage.json new file mode 100644 index 000000000000..227d52bb88cf --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyDeclinedDefinitionPage.json @@ -0,0 +1,23 @@ +{ + "$id": "https://open-metadata.org/schema/type/ontologyDeclinedDefinitionPage.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyDeclinedDefinitionPage", + "description": "One page of an ontology's declined definitions, oldest decision first.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyDeclinedDefinitionPage", + "properties": { + "records": { + "type": "array", + "items": { + "$ref": "ontologyDeclinedDefinition.json" + }, + "default": [] + }, + "after": { + "description": "Cursor for the next page. Absent on the last page.", + "type": "string" + } + }, + "required": ["records"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyProfileViolation.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyProfileViolation.json index 46f2a1074aea..8ec4364032ae 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/ontologyProfileViolation.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyProfileViolation.json @@ -31,7 +31,11 @@ "INVALID_CLASS_KIND", "SUBCLASS_CYCLE", "SUBPROPERTY_CYCLE", - "DISJOINT_CLASH" + "DISJOINT_CLASH", + "DUPLICATE_DISPLAY_NAME", + "SHAPE_CARDINALITY_CONFLICT", + "SHAPE_EMPTY_VALUE_LIST", + "SHAPE_INVALID_CONSTRAINT" ] } }, diff --git a/openmetadata-spec/src/main/resources/json/schema/type/ontologyShapeConstraint.json b/openmetadata-spec/src/main/resources/json/schema/type/ontologyShapeConstraint.json new file mode 100644 index 000000000000..8b4d80235586 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/type/ontologyShapeConstraint.json @@ -0,0 +1,74 @@ +{ + "$id": "https://open-metadata.org/schema/type/ontologyShapeConstraint.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyShapeConstraint", + "description": "One constraint of an ontology shape: the values a property may take on instances of the shape's target class.", + "type": "object", + "javaType": "org.openmetadata.schema.type.OntologyShapeConstraint", + "definitions": { + "value": { + "description": "A node a constraint accepts: an IRI or a literal, never both.", + "javaType": "org.openmetadata.schema.type.OntologyShapeValue", + "type": "object", + "properties": { + "iri": { + "$ref": "ontologyIri.json" + }, + "literal": { + "$ref": "ontologyExpression.json#/definitions/literal" + } + }, + "additionalProperties": false + } + }, + "properties": { + "id": { + "description": "Identity of the constraint inside its shape. It stays the same when the constraint is edited.", + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$" + }, + "path": { + "description": "Full IRI of the ontology property the constraint applies to.", + "$ref": "ontologyIri.json" + }, + "minCount": { + "type": "integer", + "minimum": 0 + }, + "maxCount": { + "type": "integer", + "minimum": 0 + }, + "classIri": { + "description": "Every value must be an instance of this class.", + "$ref": "ontologyIri.json" + }, + "datatypeIri": { + "description": "Every value must be a literal of this datatype.", + "$ref": "ontologyIri.json" + }, + "minInclusive": { + "$ref": "ontologyExpression.json#/definitions/literal" + }, + "maxInclusive": { + "$ref": "ontologyExpression.json#/definitions/literal" + }, + "in": { + "description": "Every value must be one of these nodes.", + "type": "array", + "items": { + "$ref": "#/definitions/value" + }, + "default": null + }, + "pattern": { + "description": "Every value's lexical form must match this regular expression.", + "type": "string" + } + }, + "required": [ + "id", + "path" + ], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/json/schema/type/suggestionPayload.json b/openmetadata-spec/src/main/resources/json/schema/type/suggestionPayload.json index b2c1dfc3832b..a13c9166ee8e 100644 --- a/openmetadata-spec/src/main/resources/json/schema/type/suggestionPayload.json +++ b/openmetadata-spec/src/main/resources/json/schema/type/suggestionPayload.json @@ -9,10 +9,10 @@ "suggestionType": { "description": "Type of suggestion.", "type": "string", - "enum": ["Description", "Tag", "Owner", "Tier", "Domain", "CustomProperty"] + "enum": ["Description", "Tag", "Owner", "Tier", "Domain", "CustomProperty", "TableConstraint", "TestCase"] }, "fieldPath": { - "description": "Path to the property being updated. For a Description or Tag suggestion it is written as .[....]., for example 'columns.customer_id.description', or 'description' / 'tags' alone for the entity itself.", + "description": "Path to the property being updated. For a Description or Tag suggestion it is written as .[....]., for example 'columns.customer_id.description', or 'description' / 'tags' alone for the entity itself. A TableConstraint suggestion's path is 'tableConstraints'. A TestCase suggestion's path is 'testCases'.", "type": "string" }, "currentValue": { @@ -20,7 +20,7 @@ "type": "string" }, "suggestedValue": { - "description": "Suggested new value for the field.", + "description": "Suggested new value for the field. For a TableConstraint suggestion it is one tableConstraint object written as JSON: its constraintType (PRIMARY_KEY, UNIQUE or FOREIGN_KEY), its columns, and for a foreign key its referredColumns as full column names and its relationshipType. For a TestCase suggestion it is a testCaseProposal written as JSON: the test case to create, with the statement that lists the records it counts and where it comes from.", "type": "string" }, "confidence": { diff --git a/openmetadata-spec/src/main/resources/json/schema/type/testCaseProposal.json b/openmetadata-spec/src/main/resources/json/schema/type/testCaseProposal.json new file mode 100644 index 000000000000..cd64efcfa04e --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/type/testCaseProposal.json @@ -0,0 +1,24 @@ +{ + "$id": "https://open-metadata.org/schema/type/testCaseProposal.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "TestCaseProposal", + "description": "The suggested value of a TestCase suggestion: the test case to create, the statement that lists the records it counts, and where it comes from. Approving the suggestion creates the test case with those values and nothing else.", + "type": "object", + "javaType": "org.openmetadata.schema.type.TestCaseProposal", + "properties": { + "testCase": { + "description": "The test case to create, in the shape a request to create a test case takes.", + "$ref": "../api/tests/createTestCase.json" + }, + "inspectionQuery": { + "description": "The statement that lists the keys of the records the test counts, for a person to read. It is stored on the test case as it is, and no test runner executes it.", + "$ref": "basic.json#/definitions/sqlQuery" + }, + "generatedBy": { + "description": "Where the test comes from. It carries the identity of the check, the table bindings it was built from and the digest of its content.", + "$ref": "../tests/testCase.json#/definitions/generatedBy" + } + }, + "required": ["testCase", "inspectionQuery", "generatedBy"], + "additionalProperties": false +} diff --git a/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl b/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl index 9d355194ad7b..021936d80777 100644 --- a/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl +++ b/openmetadata-spec/src/main/resources/rdf/ontology/openmetadata.ttl @@ -930,6 +930,11 @@ om:OntologyRelease a owl:Class ; rdfs:comment "A sealed, immutable version of an ontology's content, reviewed through the approval workflow before it is activated." ; rdfs:subClassOf om:Entity . +om:OntologyShape a owl:Class ; + rdfs:label "Ontology Shape" ; + rdfs:comment "A set of constraints on the properties of one class of an ontology, held with the ontology and kept out of its releases." ; + rdfs:subClassOf om:Entity . + om:Page a owl:Class ; rdfs:label "Page" ; rdfs:comment "A knowledge page in the Knowledge Center: an article or quick link, possibly with sub-pages." ; @@ -2533,86 +2538,71 @@ om:ExtensionProperty a owl:Class ; om:projectionStatus om:Stored ; rdfs:label "description" ; rdfs:comment "The description written for the entity in OpenMetadata, usually Markdown. On a tag node it is the description carried by a tag label, and on om:LineageDetails it describes the lineage edge. Read it for business meaning when names are ambiguous." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:LineageDetails, om:MLModel, om:MLModelService, - om:McpServer, om:McpService, om:MessagingService, om:MetadataService, - om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, - om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, - om:OntologyRelease, om:Page, om:Persona, om:Pipeline, - om:PipelineService, om:Policy, om:PromptTemplate, om:Query, - om:RelationshipType, om:Report, om:Role, om:SearchIndex, - om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, - om:StoredProcedure, om:Table, om:Tag, om:Team, - om:TestConnectionDefinition, om:Topic, om:Type, om:User, - om:Workflow, om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:LineageDetails, om:MLModel, om:MLModelService, om:McpServer, + om:McpService, om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, + om:NotificationTemplate, om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, + om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, + om:Persona, om:Pipeline, om:PipelineService, om:Policy, om:PromptTemplate, om:Query, + om:RelationshipType, om:Report, om:Role, om:SearchIndex, om:SearchService, + om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, om:Table, om:Tag, + om:Team, om:TestConnectionDefinition, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "hasVersion" ; rdfs:comment "The entity's OpenMetadata metadata version, a decimal that grows with every change (0.1, 0.2, then 1.0 after a major change). dcat:version carries the same number." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, - om:McpService, om:MessagingService, om:MetadataService, om:Metric, - om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Page, om:Persona, om:Pipeline, om:PipelineService, - om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, - om:Report, om:Role, om:SearchIndex, om:SearchService, - om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, - om:Table, om:Tag, om:Team, om:TestConnectionDefinition, - om:Topic, om:Type, om:User, om:Workflow, - om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, om:McpService, + om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, + om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Persona, om:Pipeline, + om:PipelineService, om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, om:Report, + om:Role, om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, + om:StorageService, om:StoredProcedure, om:Table, om:Tag, om:Team, + om:TestConnectionDefinition, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "modified" ; rdfs:comment "When the entity last changed in OpenMetadata, as xsd:dateTime. On om:LineageDetails it is the lineage edge's last update, in Unix epoch milliseconds (xsd:long)." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:LineageDetails, om:MLModel, om:MLModelService, - om:McpServer, om:McpService, om:MessagingService, om:MetadataService, - om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, - om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, - om:OntologyRelease, om:Page, om:Persona, om:Pipeline, - om:PipelineService, om:Policy, om:PromptTemplate, om:Query, - om:RelationshipType, om:Report, om:Role, om:SearchIndex, - om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, - om:StoredProcedure, om:Table, om:Tag, om:Task, - om:Team, om:TestCase, om:TestConnectionDefinition, om:Topic, - om:Type, om:User, om:Workflow, om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:LineageDetails, om:MLModel, om:MLModelService, om:McpServer, + om:McpService, om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, + om:NotificationTemplate, om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, + om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, + om:Persona, om:Pipeline, om:PipelineService, om:Policy, om:PromptTemplate, om:Query, + om:RelationshipType, om:Report, om:Role, om:SearchIndex, om:SearchService, + om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, om:Table, om:Tag, + om:Task, om:Team, om:TestCase, om:TestConnectionDefinition, om:Topic, om:Type, om:User, + om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "publisher" ; rdfs:comment "Who provides the definition (the provider field): system for definitions OpenMetadata ships and seeds, user for ones people created." ; - schema:domainIncludes om:App, om:Bot, om:Classification, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:MetadataService, om:Metric, - om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Policy, om:RelationshipType, om:Role, om:Tag . + schema:domainIncludes om:App, om:Bot, om:Classification, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, + om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, + om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, + om:OntologyRelease, om:OntologyShape, om:Policy, om:RelationshipType, om:Role, om:Tag . a rdf:Property ; om:projectionStatus om:Stored ; @@ -2639,27 +2629,22 @@ om:ExtensionProperty a owl:Class ; om:projectionStatus om:Stored ; rdfs:label "label" ; rdfs:comment "The entity's name (the name field), the last segment of its fully qualified name. Use om:fullyQualifiedName to identify an entity exactly and skos:prefLabel for the name people see." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Column, om:Container, om:ContextFile, - om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, - om:DashboardService, om:DataContract, om:DataProduct, om:Database, - om:DatabaseSchema, om:DatabaseService, om:Directory, om:Document, - om:Domain, om:DriveService, om:File, om:Folder, - om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, - om:LLMService, om:LearningResource, om:MLModel, om:MLModelService, - om:McpServer, om:McpService, om:MessagingService, om:MetadataService, - om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, - om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, - om:OntologyRelease, om:Page, om:Persona, om:Pipeline, - om:PipelineService, om:Policy, om:PromptTemplate, om:Query, - om:RelationshipType, om:Report, om:Role, om:SearchIndex, - om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, - om:StoredProcedure, om:Table, om:Tag, om:Team, - om:TestConnectionDefinition, om:TestDefinition, om:TestResultValue, om:TestSuite, - om:Topic, om:Type, - om:User, om:Workflow, om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Column, om:Container, + om:ContextFile, om:ContextFileContent, om:ContextMemory, om:Dashboard, + om:DashboardDataModel, om:DashboardService, om:DataContract, om:DataProduct, om:Database, + om:DatabaseSchema, om:DatabaseService, om:Directory, om:Document, om:Domain, + om:DriveService, om:File, om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, + om:LLMModel, om:LLMService, om:LearningResource, om:MLModel, om:MLModelService, + om:McpServer, om:McpService, om:MessagingService, om:MetadataService, om:Metric, + om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, + om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, + om:OntologyShape, om:Page, om:Persona, om:Pipeline, om:PipelineService, om:Policy, + om:PromptTemplate, om:Query, om:RelationshipType, om:Report, om:Role, om:SearchIndex, + om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, + om:Table, om:Tag, om:Team, om:TestConnectionDefinition, om:TestDefinition, + om:TestResultValue, om:TestSuite, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; @@ -2707,26 +2692,21 @@ om:ExtensionProperty a owl:Class ; om:projectionStatus om:Stored ; rdfs:label "prefLabel" ; rdfs:comment "The entity's display name (displayName), the name shown in the UI. It may be absent or differ from rdfs:label." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, - om:McpService, om:MessagingService, om:MetadataService, om:Metric, - om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Page, om:Persona, om:Pipeline, om:PipelineService, - om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, - om:Report, om:Role, om:SearchIndex, om:SearchService, - om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, - om:Table, om:Tag, om:Team, om:TestConnectionDefinition, - om:Topic, om:Type, om:User, om:Workflow, - om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, om:McpService, + om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, + om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Persona, om:Pipeline, + om:PipelineService, om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, om:Report, + om:Role, om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, + om:StorageService, om:StoredProcedure, om:Table, om:Tag, om:Team, + om:TestConnectionDefinition, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; @@ -2744,26 +2724,21 @@ om:ExtensionProperty a owl:Class ; om:projectionStatus om:Stored ; rdfs:label "version" ; rdfs:comment "The entity's OpenMetadata metadata version as a number, the same value as dct:hasVersion." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, - om:McpService, om:MessagingService, om:MetadataService, om:Metric, - om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Page, om:Persona, om:Pipeline, om:PipelineService, - om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, - om:Report, om:Role, om:SearchIndex, om:SearchService, - om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, - om:Table, om:Tag, om:Task, om:Team, - om:TestCase, om:TestConnectionDefinition, om:Topic, om:Type, - om:User, om:Workflow, om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, om:McpService, + om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, + om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Persona, om:Pipeline, + om:PipelineService, om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, om:Report, + om:Role, om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, + om:StorageService, om:StoredProcedure, om:Table, om:Tag, om:Task, om:Team, om:TestCase, + om:TestConnectionDefinition, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:InferenceOnly ; @@ -2814,26 +2789,21 @@ om:ExtensionProperty a owl:Class ; om:projectionStatus om:Stored ; rdfs:label "invalidatedAtTime" ; rdfs:comment "Present only on a soft-deleted entity: its last update time, which is when it was deleted." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, - om:McpService, om:MessagingService, om:MetadataService, om:Metric, - om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Page, om:Persona, om:Pipeline, om:PipelineService, - om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, - om:Report, om:Role, om:SearchIndex, om:SearchService, - om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, - om:Table, om:Tag, om:Task, om:Team, - om:TestCase, om:TestConnectionDefinition, om:Topic, om:Type, - om:User, om:Workflow, om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, om:McpService, + om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, + om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Persona, om:Pipeline, + om:PipelineService, om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, om:Report, + om:Role, om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, + om:StorageService, om:StoredProcedure, om:Table, om:Tag, om:Task, om:Team, om:TestCase, + om:TestConnectionDefinition, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; @@ -2862,24 +2832,20 @@ om:ExtensionProperty a owl:Class ; om:projectionStatus om:Stored ; rdfs:label "wasAttributedTo" ; rdfs:comment "An owner of the entity, the PROV-O mirror of om:hasOwner: a user or team that owns it." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Chart, om:Classification, - om:Container, om:ContextFile, om:ContextMemory, om:Dashboard, - om:DashboardDataModel, om:DashboardService, om:DataContract, om:DataProduct, - om:Database, om:DatabaseSchema, om:DatabaseService, om:Directory, - om:Domain, om:DriveService, om:File, om:Folder, - om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, - om:LLMService, om:LearningResource, om:MLModel, om:MLModelService, - om:McpServer, om:McpService, om:MessagingService, om:MetadataService, - om:Metric, om:MetricGroup, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Page, om:Pipeline, om:PipelineService, om:Policy, - om:PromptTemplate, om:Query, om:RelationshipType, om:Report, - om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, - om:StorageService, om:StoredProcedure, om:Table, om:Tag, - om:Team, om:TestConnectionDefinition, om:Topic, om:Workflow, - om:Worksheet . + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Chart, om:Classification, om:Container, om:ContextFile, om:ContextMemory, + om:Dashboard, om:DashboardDataModel, om:DashboardService, om:DataContract, om:DataProduct, + om:Database, om:DatabaseSchema, om:DatabaseService, om:Directory, om:Domain, + om:DriveService, om:File, om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, + om:LLMModel, om:LLMService, om:LearningResource, om:MLModel, om:MLModelService, + om:McpServer, om:McpService, om:MessagingService, om:MetadataService, om:Metric, + om:MetricGroup, om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Pipeline, + om:PipelineService, om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, om:Report, + om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, + om:StoredProcedure, om:Table, om:Tag, om:Team, om:TestConnectionDefinition, om:Topic, + om:Workflow, om:Worksheet . a rdf:Property ; om:projectionStatus om:Stored ; @@ -3159,6 +3125,27 @@ om:axiomType a rdf:Property ; rdfs:domain om:OntologyAxiom ; rdfs:range xsd:string . +om:constraints a rdf:Property ; + om:projectionStatus om:Stored ; + rdfs:label "constraints" ; + rdfs:comment "Constraints a shape places on the properties of its target class, in authored order. Set on om:OntologyShape. The value is the field's JSON, serialized as a string." ; + rdfs:domain om:OntologyShape ; + rdfs:range xsd:string . + +om:severity a rdf:Property ; + om:projectionStatus om:Stored ; + rdfs:label "severity" ; + rdfs:comment "How serious a violation of a shape is. Set on om:OntologyShape." ; + rdfs:domain om:OntologyShape ; + rdfs:range xsd:string . + +om:targetConcept a rdf:Property ; + om:projectionStatus om:Stored ; + rdfs:label "targetConcept" ; + rdfs:comment "Full IRI of the class a shape applies to. Set on om:OntologyShape." ; + rdfs:domain om:OntologyShape ; + rdfs:range xsd:string . + om:baseModel a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "baseModel" ; @@ -4583,23 +4570,19 @@ om:impersonatedBy a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "impersonatedBy" ; rdfs:comment "The bot that made the entity's last change on behalf of a user, when that change was impersonated." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:App, om:AppMarketPlaceDefinition, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextMemory, om:Dashboard, - om:DashboardDataModel, om:DashboardService, om:DataContract, om:DataProduct, - om:Database, om:DatabaseSchema, om:DatabaseService, om:Directory, - om:Document, om:Domain, om:DriveService, om:File, - om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, - om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, - om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:App, + om:AppMarketPlaceDefinition, om:Bot, om:Chart, om:Classification, om:Container, + om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, om:DataContract, + om:DataProduct, om:Database, om:DatabaseSchema, om:DatabaseService, om:Directory, + om:Document, om:Domain, om:DriveService, om:File, om:Glossary, om:GlossaryTerm, + om:IngestionPipeline, om:LLMModel, om:LearningResource, om:MLModel, om:MLModelService, + om:McpServer, om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, om:OntologyConcept, - om:OntologyProperty, om:OntologyRelease, om:Page, om:Persona, - om:Pipeline, om:PipelineService, om:Policy, om:Query, - om:RelationshipType, om:Report, om:Role, om:SearchIndex, - om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, - om:StoredProcedure, om:Table, om:Tag, om:Team, - om:TestConnectionDefinition, om:Topic, om:Type, om:User, - om:Workflow, om:Worksheet ; + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Persona, om:Pipeline, + om:PipelineService, om:Policy, om:Query, om:RelationshipType, om:Report, om:Role, + om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, om:StorageService, + om:StoredProcedure, om:Table, om:Tag, om:Team, om:TestConnectionDefinition, om:Topic, + om:Type, om:User, om:Workflow, om:Worksheet ; rdfs:range xsd:string . om:includeRedacted a rdf:Property ; @@ -4613,26 +4596,21 @@ om:incrementalChangeDescription a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "incrementalChangeDescription" ; rdfs:comment "JSON of the change that produced the entity's current version: fields added, updated and deleted. It is one step, not the history; the entity version APIs keep the history." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, - om:DatabaseService, om:Directory, om:Document, om:Domain, - om:DriveService, om:File, om:Folder, om:Glossary, - om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, - om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, - om:McpService, om:MessagingService, om:MetadataService, om:Metric, - om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, - om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, - om:Page, om:Persona, om:Pipeline, om:PipelineService, - om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, - om:Report, om:Role, om:SearchIndex, om:SearchService, - om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, - om:Table, om:Tag, om:Team, om:TestConnectionDefinition, - om:Topic, om:Type, om:User, om:Workflow, - om:Worksheet ; + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:DataProduct, om:Database, om:DatabaseSchema, + om:DatabaseService, om:Directory, om:Document, om:Domain, om:DriveService, om:File, + om:Folder, om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, om:LLMService, + om:LearningResource, om:MLModel, om:MLModelService, om:McpServer, om:McpService, + om:MessagingService, om:MetadataService, om:Metric, om:MetricGroup, om:NotificationTemplate, + om:Ontology, om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, + om:OntologyProperty, om:OntologyRelease, om:OntologyShape, om:Page, om:Persona, om:Pipeline, + om:PipelineService, om:Policy, om:PromptTemplate, om:Query, om:RelationshipType, om:Report, + om:Role, om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, + om:StorageService, om:StoredProcedure, om:Table, om:Tag, om:Team, + om:TestConnectionDefinition, om:Topic, om:Type, om:User, om:Workflow, om:Worksheet ; rdfs:range xsd:string . om:index a rdf:Property ; @@ -4731,24 +4709,20 @@ om:isDeleted a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "isDeleted" ; rdfs:comment "True when the entity is soft-deleted (the deleted field)." ; - schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, - om:AiFrameworkControl, om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, - om:AppMarketPlaceDefinition, om:AuditReport, om:Bot, om:Chart, - om:Classification, om:Container, om:ContextFile, om:ContextFileContent, - om:ContextMemory, om:Dashboard, om:DashboardDataModel, om:DashboardService, - om:DataContract, om:Database, om:DatabaseSchema, om:DatabaseService, - om:Directory, om:DriveService, om:File, om:Folder, - om:Glossary, om:GlossaryTerm, om:IngestionPipeline, om:LLMModel, - om:LLMService, om:LearningResource, om:MLModel, om:MLModelService, - om:McpServer, om:McpService, om:MessagingService, om:MetadataService, - om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, - om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, - om:OntologyRelease, om:Pipeline, om:PipelineService, om:Policy, - om:PromptTemplate, om:RelationshipType, om:Report, om:Role, - om:SearchIndex, om:SearchService, om:SecurityService, om:Spreadsheet, - om:StorageService, om:StoredProcedure, om:Table, om:Tag, - om:Team, om:TestConnectionDefinition, om:Topic, om:User, - om:Workflow, om:Worksheet ; + schema:domainIncludes om:AIApplication, om:APICollection, om:APIEndpoint, om:APIService, om:AiFrameworkControl, + om:AiGovernanceFramework, om:AiGovernancePolicy, om:App, om:AppMarketPlaceDefinition, + om:AuditReport, om:Bot, om:Chart, om:Classification, om:Container, om:ContextFile, + om:ContextFileContent, om:ContextMemory, om:Dashboard, om:DashboardDataModel, + om:DashboardService, om:DataContract, om:Database, om:DatabaseSchema, om:DatabaseService, + om:Directory, om:DriveService, om:File, om:Folder, om:Glossary, om:GlossaryTerm, + om:IngestionPipeline, om:LLMModel, om:LLMService, om:LearningResource, om:MLModel, + om:MLModelService, om:McpServer, om:McpService, om:MessagingService, om:MetadataService, + om:Metric, om:MetricGroup, om:NotificationTemplate, om:Ontology, om:OntologyAxiom, + om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, + om:OntologyShape, om:Pipeline, om:PipelineService, om:Policy, om:PromptTemplate, + om:RelationshipType, om:Report, om:Role, om:SearchIndex, om:SearchService, + om:SecurityService, om:Spreadsheet, om:StorageService, om:StoredProcedure, om:Table, om:Tag, + om:Team, om:TestConnectionDefinition, om:Topic, om:User, om:Workflow, om:Worksheet ; rdfs:range xsd:boolean . om:isDeployed a rdf:Property ; @@ -4964,6 +4938,13 @@ om:manifest a rdf:Property ; rdfs:domain om:AuditReport ; rdfs:range xsd:string . +om:mappingSource a rdf:Property ; + om:projectionStatus om:Stored ; + rdfs:label "mappingSource" ; + rdfs:comment "The one database whose tables the classes of an ontology bind. Set on om:Ontology. The value is the reference's JSON, serialized as a string." ; + rdfs:domain om:Ontology ; + rdfs:range xsd:string . + om:maximumMessageSize a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "maximumMessageSize" ; @@ -5161,8 +5142,8 @@ om:ontology a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "ontology" ; rdfs:comment "The ontology that owns a concept, property, axiom, change set or release, as the reference's JSON text." ; - schema:domainIncludes om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, - om:OntologyRelease ; + schema:domainIncludes om:OntologyAxiom, om:OntologyChangeSet, om:OntologyConcept, om:OntologyProperty, om:OntologyRelease, + om:OntologyShape ; rdfs:range xsd:string . om:operations a rdf:Property ; @@ -6572,6 +6553,13 @@ om:isIdentifier a rdf:Property ; rdfs:domain om:OntologyProperty ; rdfs:range xsd:boolean . +om:isDisplayName a rdf:Property ; + om:projectionStatus om:Stored ; + rdfs:label "isDisplayName" ; + rdfs:comment "Whether a DATA property supplies the display name of its class. Set on om:OntologyProperty." ; + rdfs:domain om:OntologyProperty ; + rdfs:range xsd:boolean . + om:abstract a rdf:Property ; om:projectionStatus om:Stored ; rdfs:label "abstract" ; @@ -6594,6 +6582,10 @@ om:identifierIntent a owl:AnnotationProperty ; rdfs:label "identifier intent" ; rdfs:comment "Authored identifier intent, without asserting functionality, an OWL key or source-data uniqueness." . +om:displayNameIntent a owl:AnnotationProperty ; + rdfs:label "display name intent" ; + rdfs:comment "Marks a data property whose value names its class's instances, without asserting functionality or source-data uniqueness." . + om:tableSharding a owl:DatatypeProperty ; om:projectionStatus om:Stored ; rdfs:domain om:Table ; diff --git a/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx index ceb96b088201..97d7dad046c0 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/Entity/Task/TaskTab/TaskTabNew.component.test.tsx @@ -11,6 +11,7 @@ * limitations under the License. */ import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { act } from 'react'; import { MemoryRouter } from 'react-router-dom'; import { EntityType } from '../../../../enums/entity.enum'; @@ -465,8 +466,11 @@ jest.mock( } ); -// The edit modal's form (the one with `onChange`) as a plain comment field the -// tests can type in; the read-only payload details render for real. +// A transition form's data, as a person fills it in. While it is set, the edit +// modal's form (the one with `onChange`) is one button that submits it; otherwise +// that form is a plain comment field the tests can type in. The read-only +// payload details render for real. +let mockFilledPayload: Record | undefined; jest.mock('../../../../pages/TasksPage/shared/TaskPayloadSchemaFields', () => { const Actual = jest.requireActual( '../../../../pages/TasksPage/shared/TaskPayloadSchemaFields' @@ -478,7 +482,13 @@ jest.mock('../../../../pages/TasksPage/shared/TaskPayloadSchemaFields', () => { payload?: Record; onChange?: (payload: Record) => void; }) => - props.onChange ? ( + mockFilledPayload && props.onChange ? ( + + ) : props.onChange ? (