This is an automated email from the ASF dual-hosted git repository.
mchades pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/main by this push:
new a37757c5ec [#14952] fix(semantic): Resolve Semantic Model keys and
joins as dataset fields (#14953)
a37757c5ec is described below
commit a37757c5ecf6b86856c4687af9315651a89add79
Author: mchades <[email protected]>
AuthorDate: Fri Nov 13 20:17:16 2026 +0800
[#14952] fix(semantic): Resolve Semantic Model keys and joins as dataset
fields (#14953)
### What changes were proposed in this pull request?
- `SemanticModelValidator` resolves `primaryKey`, `uniqueKeys`,
`fromColumns`, and `toColumns` against fields declared in the referenced
datasets' `fields` (case-insensitive), per the Ossie Name Resolution
rules. Undeclared references are rejected with path-specific errors; a
dataset with no fields exposes no names.
- `SemanticModelSourceValidator` no longer reads physical column
metadata; it still resolves source existence, supported entity type,
caller authorization, and registered source identity for persistence.
- API javadocs (`Dataset`, `Relationship`), user docs, OpenAPI
descriptions/examples, the design doc, and the Web UI validator are
updated to field-name semantics.
### Why are the changes needed?
The latest Apache Ossie spec (0.3.0.dev0, apache/ossie#486) explicitly
defines these references as dataset field names — a breaking
clarification. Gravitino's previous physical-column interpretation
contradicts the spec: a field may rename or compute over source columns
(e.g. field `order_id` over column `o_orderkey`), and keys and joins
should reference the semantic interface rather than bypass it.
Fixes #14952
### Does this PR introduce _any_ user-facing change?
Yes — validation behavior change:
- Definitions whose keys or join columns name undeclared fields are now
rejected (they were previously checked against physical source columns).
- Definitions referencing field names that are not physical columns
(e.g. aliased fields) are now accepted.
- Field expressions remain uninterpreted; source existence and
authorization checks are unchanged.
### How was this patch tested?
- `./gradlew :core:test --tests 'TestSemanticModel*'` — new cases cover
declared/undeclared/case-insensitive field references and fieldless
datasets.
- `./gradlew :server:test --tests 'TestSemanticModel*'` — source
validator tests assert physical column metadata is never consulted; REST
operation tests updated.
- `./gradlew :api:test :common:test` semantic/Ossie converter tests.
- `./gradlew :docs:build` — OpenAPI validation.
- `npx vitest run src/lib/utils/semanticModel.test.js` — 78 tests.
- `SemanticModelIT` fixtures updated (IT profile).
- `./gradlew spotlessApply` clean.
Generated with [Devin](https://devin.ai)
---------
Co-authored-by: Devin
<158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
.../org/apache/gravitino/semantic/Dataset.java | 24 ++--
.../apache/gravitino/semantic/Relationship.java | 32 +++--
.../client/integration/test/SemanticModelIT.java | 69 ++++++---
.../catalog/ManagedSemanticModelOperations.java | 14 +-
.../gravitino/catalog/SemanticModelValidator.java | 111 +++++++++++++--
.../TestManagedSemanticModelOperations.java | 43 ++++++
.../TestSemanticModelOperationDispatcher.java | 42 +++++-
.../catalog/TestSemanticModelValidator.java | 155 ++++++++++++++++++++-
design-docs/gravitino-semantic-model-design.md | 14 +-
...nage-semantic-model-metadata-using-gravitino.md | 81 +++++++++--
docs/open-api/semantic-models.yaml | 77 ++++++++--
docs/semantic-models.md | 18 +--
.../web/rest/SemanticModelSourceValidator.java | 69 ++-------
.../web/rest/TestSemanticModelOperations.java | 34 ++---
.../web/rest/TestSemanticModelSourceValidator.java | 92 +++++-------
web-v2/web/src/lib/utils/semanticModel.js | 55 +++++++-
web-v2/web/src/lib/utils/semanticModel.test.js | 99 ++++++++++++-
17 files changed, 786 insertions(+), 243 deletions(-)
diff --git a/api/src/main/java/org/apache/gravitino/semantic/Dataset.java
b/api/src/main/java/org/apache/gravitino/semantic/Dataset.java
index d7e7c7336f..6f441d8eb5 100644
--- a/api/src/main/java/org/apache/gravitino/semantic/Dataset.java
+++ b/api/src/main/java/org/apache/gravitino/semantic/Dataset.java
@@ -81,9 +81,11 @@ public final class Dataset {
}
/**
- * Returns a copy of the primary key columns.
+ * Returns a copy of the primary key field names.
*
- * @return The primary key columns, or {@code null} if they are not set.
+ * <p>The names refer to fields declared by this dataset, not columns of its
source.
+ *
+ * @return The primary key field names, or {@code null} if they are not set.
*/
@Nullable
public String[] primaryKey() {
@@ -91,9 +93,11 @@ public final class Dataset {
}
/**
- * Returns a deep copy of the unique key definitions.
+ * Returns a deep copy of the unique key field names.
+ *
+ * <p>The names refer to fields declared by this dataset, not columns of its
source.
*
- * @return The unique keys, or {@code null} if they are not set.
+ * @return The unique key field names, or {@code null} if they are not set.
*/
@Nullable
public String[][] uniqueKeys() {
@@ -250,9 +254,11 @@ public final class Dataset {
}
/**
- * Sets the optional primary key columns.
+ * Sets the optional primary key field names.
*
- * @param primaryKey The primary key columns, or {@code null} to leave
them unset.
+ * <p>The names must refer to fields declared by this dataset, not columns
of its source.
+ *
+ * @param primaryKey The primary key field names, or {@code null} to leave
them unset.
* @return This builder.
*/
public Builder withPrimaryKey(@Nullable String[] primaryKey) {
@@ -261,9 +267,11 @@ public final class Dataset {
}
/**
- * Sets the optional unique key definitions.
+ * Sets the optional unique key field names.
+ *
+ * <p>The names must refer to fields declared by this dataset, not columns
of its source.
*
- * @param uniqueKeys The unique keys, or {@code null} to leave them unset.
+ * @param uniqueKeys The unique key field names, or {@code null} to leave
them unset.
* @return This builder.
*/
public Builder withUniqueKeys(@Nullable String[][] uniqueKeys) {
diff --git a/api/src/main/java/org/apache/gravitino/semantic/Relationship.java
b/api/src/main/java/org/apache/gravitino/semantic/Relationship.java
index e6dc0ba2d0..562b07f1d3 100644
--- a/api/src/main/java/org/apache/gravitino/semantic/Relationship.java
+++ b/api/src/main/java/org/apache/gravitino/semantic/Relationship.java
@@ -25,8 +25,8 @@ import javax.annotation.Nullable;
import org.apache.gravitino.annotation.Evolving;
/**
- * An immutable relationship between two datasets in the same semantic model.
The endpoint column
- * arrays describe the corresponding join columns on the source and target
datasets.
+ * An immutable relationship between two datasets in the same semantic model.
The endpoint arrays
+ * name fields declared by the source and target datasets that form the join.
*/
@Evolving
public final class Relationship {
@@ -87,18 +87,22 @@ public final class Relationship {
}
/**
- * Returns a copy of the source dataset columns.
+ * Returns a copy of the source dataset field names.
*
- * @return The source columns.
+ * <p>The names refer to fields declared by the source dataset, not columns
of its source.
+ *
+ * @return The source field names.
*/
public String[] fromColumns() {
return Arrays.copyOf(fromColumns, fromColumns.length);
}
/**
- * Returns a copy of the target dataset columns.
+ * Returns a copy of the target dataset field names.
+ *
+ * <p>The names refer to fields declared by the target dataset, not columns
of its source.
*
- * @return The target columns.
+ * @return The target field names.
*/
public String[] toColumns() {
return Arrays.copyOf(toColumns, toColumns.length);
@@ -241,9 +245,11 @@ public final class Relationship {
}
/**
- * Sets the source dataset columns.
+ * Sets the source dataset join field names.
*
- * @param fromColumns The non-empty source column array.
+ * <p>The names must refer to fields declared by the source dataset, not
columns of its source.
+ *
+ * @param fromColumns The non-empty source field name array.
* @return This builder.
*/
public Builder withFromColumns(String[] fromColumns) {
@@ -252,9 +258,11 @@ public final class Relationship {
}
/**
- * Sets the target dataset columns.
+ * Sets the target dataset join field names.
+ *
+ * <p>The names must refer to fields declared by the target dataset, not
columns of its source.
*
- * @param toColumns The non-empty target column array.
+ * @param toColumns The non-empty target field name array.
* @return This builder.
*/
public Builder withToColumns(String[] toColumns) {
@@ -288,8 +296,8 @@ public final class Relationship {
* Builds an immutable {@link Relationship}.
*
* @return The new relationship.
- * @throws IllegalArgumentException If a required name is null or empty, a
required column array
- * is null or empty, a column name or custom extension is null, or the
endpoint column
+ * @throws IllegalArgumentException If a required name is null or empty, a
required endpoint
+ * array is null or empty, an endpoint name or custom extension is
null, or the endpoint
* arrays have different lengths.
*/
public Relationship build() {
diff --git
a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/SemanticModelIT.java
b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/SemanticModelIT.java
index a59ebb5cb7..3b19444f06 100644
---
a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/SemanticModelIT.java
+++
b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/SemanticModelIT.java
@@ -25,7 +25,6 @@ import static
org.junit.jupiter.api.Assertions.assertArrayEquals;
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;
@@ -375,7 +374,11 @@ public class SemanticModelIT extends BaseIT {
assertEquals(
"TRINO",
created.definition().datasets()[0].fields()[1].expression().dialects()[0].dialect());
- assertArrayEquals(new Field[0],
created.definition().datasets()[1].fields());
+ assertEquals(
+ List.of("id", "email"),
+ Arrays.stream(created.definition().datasets()[1].fields())
+ .map(Field::name)
+ .collect(Collectors.toList()));
assertThrows(
SemanticModelAlreadyExistsException.class,
@@ -402,7 +405,7 @@ public class SemanticModelIT extends BaseIT {
Map<String, String> alteredProperties =
Map.of("certified", "true", "owner", "analytics",
PROPERTY_OSSIE_VERSION, DEFAULT_VERSION);
assertSemanticModel(RENAMED_MODEL_NAME, "", replacement,
alteredProperties, altered);
- assertNull(altered.definition().datasets()[0].fields());
+ assertEquals("order_id",
altered.definition().datasets()[0].fields()[0].name());
assertArrayEquals(new Field[0],
altered.definition().datasets()[1].fields());
assertArrayEquals(new Relationship[0],
altered.definition().relationships());
assertArrayEquals(new Metric[0], altered.definition().metrics());
@@ -1275,10 +1278,17 @@ public class SemanticModelIT extends BaseIT {
ObjectNode root = JSON_MAPPER.createObjectNode();
root.put("version", DEFAULT_VERSION);
root.put("name", OSSIE_MODEL_NAME);
- root.putArray("datasets")
+ ObjectNode dataset = root.putArray("datasets").addObject();
+ dataset.put("name", "orders");
+ dataset.put("source", CATALOG_NAME + "." + SCHEMA_NAME + "." +
ORDERS_TABLE);
+ ObjectNode field = dataset.putArray("fields").addObject();
+ field.put("name", "order_id");
+ field
+ .putObject("expression")
+ .putArray("dialects")
.addObject()
- .put("name", "orders")
- .put("source", CATALOG_NAME + "." + SCHEMA_NAME + "." + ORDERS_TABLE);
+ .put("dialect", "ANSI_SQL")
+ .put("expression", "order_id");
return root;
}
@@ -1460,11 +1470,13 @@ public class SemanticModelIT extends BaseIT {
.withName("orders")
.withSource(NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME,
"missing_table"))
.build();
- Dataset missingColumn =
+ // order_time is a real source column, but keys resolve to declared
fields, so a dataset
+ // without fields rejects it.
+ Dataset undeclaredKeyField =
Dataset.builder()
.withName("orders")
.withSource(NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME,
ORDERS_TABLE))
- .withPrimaryKey(new String[] {"missing_column"})
+ .withPrimaryKey(new String[] {"order_time"})
.build();
return Stream.of(
Arguments.of(
@@ -1472,9 +1484,11 @@ public class SemanticModelIT extends BaseIT {
SemanticModelDefinition.builder().withDatasets(new Dataset[]
{missingSource}).build(),
"missing_table does not exist"),
Arguments.of(
- "missing column",
- SemanticModelDefinition.builder().withDatasets(new Dataset[]
{missingColumn}).build(),
- "Dataset orders source has no column missing_column"));
+ "undeclared key field",
+ SemanticModelDefinition.builder()
+ .withDatasets(new Dataset[] {undeclaredKeyField})
+ .build(),
+ "'order_time' is not a declared field of dataset 'orders'"));
}
private static Stream<Arguments> invalidOssieSourceDocuments() {
@@ -1487,9 +1501,9 @@ public class SemanticModelIT extends BaseIT {
ossieSourceDocument("missing_table", null, format),
"missing_table does not exist"),
Arguments.of(
- "missing column " + format,
- ossieSourceDocument(ORDERS_TABLE, "missing_column",
format),
- "Dataset orders source has no column
missing_column")));
+ "undeclared key field " + format,
+ ossieSourceDocument(ORDERS_TABLE, "order_time",
format),
+ "'order_time' is not a declared field of dataset
'orders'")));
}
private static OssieDocument ossieSourceDocument(
@@ -1568,6 +1582,16 @@ public class SemanticModelIT extends BaseIT {
.withDatatype(DataType.DECIMAL)
.withCustomExtensions(new CustomExtension[] {extension})
.build();
+ Field orderId =
+ Field.builder()
+ .withName("order_id")
+ .withExpression(expression(Dialects.ANSI_SQL, "order_id"))
+ .build();
+ Field orderCustomer =
+ Field.builder()
+ .withName("customer_id")
+ .withExpression(expression(Dialects.ANSI_SQL, "customer_id"))
+ .build();
Dataset orders =
Dataset.builder()
.withName("orders")
@@ -1576,15 +1600,22 @@ public class SemanticModelIT extends BaseIT {
.withUniqueKeys(new String[0][])
.withDescription("Governed order facts")
.withAIContext(AIContext.of("Use completed orders"))
- .withFields(new Field[] {orderTime, orderAmount})
+ .withFields(new Field[] {orderTime, orderAmount, orderId,
orderCustomer})
.withCustomExtensions(new CustomExtension[0])
.build();
+ Field customerId =
+
Field.builder().withName("id").withExpression(expression(Dialects.ANSI_SQL,
"id")).build();
+ Field customerEmail =
+ Field.builder()
+ .withName("email")
+ .withExpression(expression(Dialects.ANSI_SQL, "email"))
+ .build();
Dataset customers =
Dataset.builder()
.withName("customers")
.withSource(NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME,
CUSTOMERS_TABLE))
.withUniqueKeys(new String[][] {{"email"}})
- .withFields(new Field[0])
+ .withFields(new Field[] {customerId, customerEmail})
.build();
Relationship relationship =
Relationship.builder()
@@ -1615,11 +1646,17 @@ public class SemanticModelIT extends BaseIT {
}
private static SemanticModelDefinition replacementDefinition() {
+ Field orderId =
+ Field.builder()
+ .withName("order_id")
+ .withExpression(expression(Dialects.ANSI_SQL, "order_id"))
+ .build();
Dataset orders =
Dataset.builder()
.withName("orders")
.withSource(NameIdentifier.of(CATALOG_NAME, SCHEMA_NAME,
ORDERS_TABLE))
.withPrimaryKey(new String[] {"order_id"})
+ .withFields(new Field[] {orderId})
.build();
Dataset customers =
Dataset.builder()
diff --git
a/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java
b/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java
index 477a1e191b..ab4249ab8e 100644
---
a/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java
+++
b/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java
@@ -243,9 +243,17 @@ public class ManagedSemanticModelOperations {
oldEntity -> {
SemanticModelEntity candidate = applyChanges(oldEntity,
sourceUpdate, changes);
if (validateForWrite) {
- writeValidator.accept(
- NameIdentifier.of(candidate.namespace(), candidate.name()),
- candidate.definition());
+ NameIdentifier candidateIdent =
+ NameIdentifier.of(candidate.namespace(), candidate.name());
+ // Every replacement is validated, even when a later change
replaces the
+ // definition again before the update is persisted.
+ for (SemanticModelChange change : changes) {
+ if (change instanceof SemanticModelChange.ReplaceDefinition) {
+ writeValidator.accept(
+ candidateIdent,
+ ((SemanticModelChange.ReplaceDefinition)
change).getDefinition());
+ }
+ }
}
sourceUpdate.validate(candidate.definition());
return candidate;
diff --git
a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelValidator.java
b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelValidator.java
index aab54da4e0..38ae9aa9b9 100644
---
a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelValidator.java
+++
b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelValidator.java
@@ -21,7 +21,10 @@ package org.apache.gravitino.catalog;
import static
org.apache.gravitino.semantic.CustomExtension.GRAVITINO_PROPERTIES_VENDOR;
import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Locale;
import java.util.Map;
+import java.util.Set;
import javax.annotation.Nullable;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.exceptions.IllegalSemanticModelException;
@@ -45,12 +48,19 @@ import
org.apache.gravitino.semantic.SemanticModelDefinition;
* <p>The API value-object builders enforce value-level invariants, including
required values, array
* element validity, relationship column shapes, and expression dialect
uniqueness. This validator
* handles constraints that span value objects: name uniqueness, relationship
endpoint resolution,
- * Semantic Model source identifier shape, and the reserved root properties
extension vendor.
+ * key and relationship field resolution, Semantic Model source identifier
shape, and the reserved
+ * root properties extension vendor.
+ *
+ * <p>Following the Ossie Name Resolution rules, {@code primaryKey}, {@code
uniqueKeys}, {@code
+ * fromColumns}, and {@code toColumns} name fields declared in the referenced
datasets, not columns
+ * of the datasets' sources. Field names are compared case-insensitively,
including for uniqueness,
+ * so a dataset that declares two names equal ignoring case is rejected. A
dataset that declares no
+ * fields exposes no names to keys or relationships.
*
* <p>Validation is deterministic and performs no catalog I/O. Catalog-backed
source validation,
- * including existence, columns, and authorization, must be completed by the
caller before this
- * validator is invoked. SQL expression semantics, transitive View semantics,
and query engine
- * compatibility are outside this validator's scope.
+ * including existence and authorization, must be completed by the caller
before this validator is
+ * invoked. SQL expression semantics, transitive View semantics, and query
engine compatibility are
+ * outside this validator's scope.
*/
final class SemanticModelValidator {
@@ -63,11 +73,12 @@ final class SemanticModelValidator {
Dataset[] datasets = definition.datasets();
Map<String, String> datasetNames = new HashMap<>();
+ Map<String, Set<String>> datasetFields = new HashMap<>();
for (int index = 0; index < datasets.length; index++) {
- validateDataset(datasets[index], "datasets[" + index + "]",
datasetNames);
+ validateDataset(datasets[index], "datasets[" + index + "]",
datasetNames, datasetFields);
}
- validateRelationships(definition.relationships(), datasetNames);
+ validateRelationships(definition.relationships(), datasetNames,
datasetFields);
validateMetrics(definition.metrics());
validateRootCustomExtensions(definition.customExtensions());
}
@@ -86,11 +97,16 @@ final class SemanticModelValidator {
}
private static void validateDataset(
- Dataset dataset, String path, Map<String, String> datasetNames) {
+ Dataset dataset,
+ String path,
+ Map<String, String> datasetNames,
+ Map<String, Set<String>> datasetFields) {
String namePath = path + ".name";
validateUniqueName(dataset.name(), namePath, "dataset", datasetNames);
validateSource(dataset.source(), path + ".source");
- validateFields(dataset.fields(), path + ".fields");
+ Set<String> fieldNames = validateFields(dataset.fields(), path +
".fields");
+ validateKeys(dataset, path, fieldNames);
+ datasetFields.put(dataset.name(), fieldNames);
}
private static void validateSource(NameIdentifier source, String path) {
@@ -100,22 +116,53 @@ final class SemanticModelValidator {
}
}
- private static void validateFields(@Nullable Field[] fields, String path) {
+ private static Set<String> validateFields(@Nullable Field[] fields, String
path) {
+ Set<String> fieldNames = new HashSet<>();
if (fields == null) {
- return;
+ return fieldNames;
}
- Map<String, String> fieldNames = new HashMap<>();
+ Map<String, String> uniqueNames = new HashMap<>();
for (int index = 0; index < fields.length; index++) {
String fieldPath = path + "[" + index + "]";
Field field = fields[index];
String namePath = fieldPath + ".name";
- validateUniqueName(field.name(), namePath, "field", fieldNames);
+ // Key and relationship references resolve field names
case-insensitively, so two
+ // declared names equal ignoring case would make every reference to them
ambiguous.
+ validateUniqueName(normalizeFieldName(field.name()), namePath, "field",
uniqueNames);
+ fieldNames.add(normalizeFieldName(field.name()));
+ }
+ return fieldNames;
+ }
+
+ private static void validateKeys(Dataset dataset, String path, Set<String>
fieldNames) {
+ String[] primaryKey = dataset.primaryKey();
+ if (primaryKey != null) {
+ for (int index = 0; index < primaryKey.length; index++) {
+ validateFieldReference(
+ primaryKey[index], path + ".primaryKey[" + index + "]",
dataset.name(), fieldNames);
+ }
+ }
+
+ String[][] uniqueKeys = dataset.uniqueKeys();
+ if (uniqueKeys != null) {
+ for (int keyIndex = 0; keyIndex < uniqueKeys.length; keyIndex++) {
+ String[] uniqueKey = uniqueKeys[keyIndex];
+ for (int index = 0; index < uniqueKey.length; index++) {
+ validateFieldReference(
+ uniqueKey[index],
+ path + ".uniqueKeys[" + keyIndex + "][" + index + "]",
+ dataset.name(),
+ fieldNames);
+ }
+ }
}
}
private static void validateRelationships(
- @Nullable Relationship[] relationships, Map<String, String>
datasetNames) {
+ @Nullable Relationship[] relationships,
+ Map<String, String> datasetNames,
+ Map<String, Set<String>> datasetFields) {
if (relationships == null) {
return;
}
@@ -128,9 +175,47 @@ final class SemanticModelValidator {
validateUniqueName(relationship.name(), namePath, "relationship",
relationshipNames);
validateEndpoint(relationship.from(), path + ".from", datasetNames);
validateEndpoint(relationship.to(), path + ".to", datasetNames);
+ validateRelationshipColumns(relationship, path, datasetFields);
+ }
+ }
+
+ private static void validateRelationshipColumns(
+ Relationship relationship, String path, Map<String, Set<String>>
datasetFields) {
+ validateColumnReferences(
+ relationship.fromColumns(),
+ path + ".fromColumns",
+ relationship.from(),
+ datasetFields.get(relationship.from()));
+ validateColumnReferences(
+ relationship.toColumns(),
+ path + ".toColumns",
+ relationship.to(),
+ datasetFields.get(relationship.to()));
+ }
+
+ private static void validateColumnReferences(
+ String[] references, String path, String datasetName, @Nullable
Set<String> fieldNames) {
+ if (fieldNames == null) {
+ // The unknown endpoint is already reported by validateEndpoint.
+ return;
+ }
+ for (int index = 0; index < references.length; index++) {
+ validateFieldReference(references[index], path + "[" + index + "]",
datasetName, fieldNames);
}
}
+ private static void validateFieldReference(
+ String reference, String path, String datasetName, Set<String>
fieldNames) {
+ if (!fieldNames.contains(normalizeFieldName(reference))) {
+ throw invalid(
+ path, "'" + reference + "' is not a declared field of dataset '" +
datasetName + "'");
+ }
+ }
+
+ private static String normalizeFieldName(String name) {
+ return name.toLowerCase(Locale.ROOT);
+ }
+
private static void validateEndpoint(
String endpoint, String path, Map<String, String> datasetNames) {
if (!datasetNames.containsKey(endpoint)) {
diff --git
a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperations.java
b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperations.java
index 7d8f9f6444..5dfd980bb1 100644
---
a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperations.java
+++
b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperations.java
@@ -382,6 +382,49 @@ public class TestManagedSemanticModelOperations {
assertEquals(1, writeValidationCount.get());
}
+ @Test
+ public void testEveryDefinitionReplacementIsValidatedBeforePersistence() {
+ AtomicInteger writeValidationCount = new AtomicInteger();
+ ManagedSemanticModelOperations operations =
+ new ManagedSemanticModelOperations(
+ new InMemoryEntityStore(),
+ new RandomIdGenerator(),
+ (ident, definition) -> {
+ SemanticModelValidator.validateDefinition(definition);
+ writeValidationCount.incrementAndGet();
+ });
+ operations.createSemanticModel(
+ IDENT, "Original", definition("orders"), Map.of(),
sources(definition("orders")));
+
+ SemanticModelDefinition first = definition("invoices");
+ SemanticModelDefinition second = definition("payments");
+ SemanticModel altered =
+ operations.alterSemanticModel(
+ IDENT,
+ sources(second),
+ SemanticModelChange.replaceDefinition(first),
+ SemanticModelChange.replaceDefinition(second));
+ assertEquals(second, altered.definition());
+ assertEquals(3, writeValidationCount.get());
+
+ // An invalid intermediate replacement aborts the batch even when a later
+ // replacement is valid.
+ SemanticModelDefinition invalid =
+ SemanticModelDefinition.builder()
+ .withDatasets(new Dataset[] {dataset("duplicate"),
dataset("duplicate")})
+ .build();
+ assertThrows(
+ IllegalSemanticModelException.class,
+ () ->
+ operations.alterSemanticModel(
+ IDENT,
+ sources(second),
+ SemanticModelChange.replaceDefinition(invalid),
+ SemanticModelChange.replaceDefinition(definition("orders"))));
+ assertEquals(3, writeValidationCount.get());
+ assertEquals(second, operations.loadSemanticModel(IDENT).definition());
+ }
+
@Test
public void
testLaterMetadataChangesDoNotSkipDefinitionReplacementValidation() {
AtomicInteger writeValidationCount = new AtomicInteger();
diff --git
a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java
b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java
index bc80fef2da..6e2c3c57a4 100644
---
a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java
+++
b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java
@@ -55,6 +55,10 @@ import org.apache.gravitino.lock.LockManager;
import org.apache.gravitino.secret.SecretManager;
import org.apache.gravitino.semantic.CustomExtension;
import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.DialectExpression;
+import org.apache.gravitino.semantic.Dialects;
+import org.apache.gravitino.semantic.Expression;
+import org.apache.gravitino.semantic.Field;
import org.apache.gravitino.semantic.OssieDocument;
import org.apache.gravitino.semantic.OssieFormat;
import org.apache.gravitino.semantic.Relationship;
@@ -530,9 +534,16 @@ public class TestSemanticModelOperationDispatcher {
private static SemanticModelDefinition validDefinition() {
Dataset orders =
- dataset("orders", "orders", new String[] {"order_id"}, new String[][]
{{"customer_id"}});
+ dataset(
+ "orders",
+ "orders",
+ new String[] {"order_id"},
+ new String[][] {{"customer_id"}},
+ "order_id",
+ "customer_id");
Dataset customers =
- dataset("customers", "customers", new String[] {"customer_id"}, new
String[0][]);
+ dataset(
+ "customers", "customers", new String[] {"customer_id"}, new
String[0][], "customer_id");
Relationship relationship =
Relationship.builder()
.withName("orders_to_customers")
@@ -560,12 +571,37 @@ public class TestSemanticModelOperationDispatcher {
}
private static Dataset dataset(
- String name, String source, String[] primaryKey, String[][] uniqueKeys) {
+ String name,
+ String source,
+ String[] primaryKey,
+ String[][] uniqueKeys,
+ String... fieldNames) {
+ Field[] fields = new Field[fieldNames.length];
+ for (int index = 0; index < fieldNames.length; index++) {
+ fields[index] = field(fieldNames[index]);
+ }
return Dataset.builder()
.withName(name)
.withSource(NameIdentifier.of("sales", "mart", source))
.withPrimaryKey(primaryKey)
.withUniqueKeys(uniqueKeys)
+ .withFields(fields)
+ .build();
+ }
+
+ private static Field field(String name) {
+ return Field.builder()
+ .withName(name)
+ .withExpression(
+ Expression.builder()
+ .withDialects(
+ new DialectExpression[] {
+ DialectExpression.builder()
+ .withDialect(Dialects.ANSI_SQL)
+ .withExpression(name)
+ .build()
+ })
+ .build())
.build();
}
}
diff --git
a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelValidator.java
b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelValidator.java
index 757354f7d7..b2d8664459 100644
---
a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelValidator.java
+++
b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelValidator.java
@@ -50,7 +50,12 @@ public class TestSemanticModelValidator {
.withUniqueKeys(new String[][] {{"order_id"}, {"external_id",
"source"}})
.withFields(
new Field[] {
- field("id", expression("order_id")), field("amount",
expression("amount"))
+ field("order_id", expression("o_orderkey")),
+ field("external_id", expression("external_id")),
+ field("source", expression("source")),
+ field("customer_id", expression("o_custkey")),
+ field("tenant_id", expression("tenant_id")),
+ field("amount", expression("amount"))
})
.withCustomExtensions(new CustomExtension[] {extension})
.build();
@@ -58,7 +63,11 @@ public class TestSemanticModelValidator {
Dataset.builder()
.withName("customers")
.withSource(NameIdentifier.of("missing_catalog", "missing_schema",
"customers"))
- .withFields(new Field[] {field("id", expression("customer_id"))})
+ .withFields(
+ new Field[] {
+ field("id", expression("customer_id")),
+ field("tenant_id", expression("tenant_id"))
+ })
.build();
Relationship relationship =
relationship(
@@ -165,6 +174,19 @@ public class TestSemanticModelValidator {
"datasets[0].fields[1].name: duplicate field name 'id'; first declared
at "
+ "datasets[0].fields[0].name");
+ // Field names resolve case-insensitively, so names equal ignoring case
are duplicates too.
+ Dataset caseFoldedDuplicateFields =
+ Dataset.builder()
+ .withName("orders")
+ .withSource(NameIdentifier.of("sales", "mart", "orders"))
+ .withFields(
+ new Field[] {field("id", expression("id")), field("ID",
expression("other_id"))})
+ .build();
+ assertInvalid(
+ definition(caseFoldedDuplicateFields),
+ "datasets[0].fields[1].name: duplicate field name 'id'; first declared
at "
+ + "datasets[0].fields[0].name");
+
assertDoesNotThrow(
() ->
SemanticModelValidator.validateDefinition(
@@ -173,8 +195,8 @@ public class TestSemanticModelValidator {
@Test
public void testRelationshipNamesAndEndpoints() {
- Dataset orders = dataset("orders");
- Dataset customers = dataset("customers");
+ Dataset orders = datasetWithField("orders", "customer_id");
+ Dataset customers = datasetWithField("customers", "id");
Relationship relationship = relationship("by_customer", "orders",
"customers");
assertInvalid(
@@ -201,6 +223,121 @@ public class TestSemanticModelValidator {
"metrics[1].name: duplicate metric name 'revenue'; first declared at
metrics[0].name");
}
+ @Test
+ public void testKeyReferencesResolveToDeclaredFields() {
+ Dataset aliased =
+ Dataset.builder()
+ .withName("orders")
+ .withSource(NameIdentifier.of("sales", "mart", "orders"))
+ .withPrimaryKey(new String[] {"Order_ID"})
+ .withUniqueKeys(new String[][] {{"order_id", "Tenant_ID"}})
+ .withFields(
+ new Field[] {
+ field("order_id", expression("o_orderkey")),
+ field("tenant_id", expression("o_tenantkey"))
+ })
+ .build();
+ assertDoesNotThrow(() ->
SemanticModelValidator.validateDefinition(definition(aliased)));
+
+ // A source column name is not a field reference even when a field
expression uses it.
+ Dataset physicalColumn =
+ Dataset.builder()
+ .withName("orders")
+ .withSource(NameIdentifier.of("sales", "mart", "orders"))
+ .withPrimaryKey(new String[] {"o_orderkey"})
+ .withFields(new Field[] {field("order_id",
expression("o_orderkey"))})
+ .build();
+ assertInvalid(
+ definition(physicalColumn),
+ "datasets[0].primaryKey[0]: 'o_orderkey' is not a declared field of
dataset 'orders'");
+
+ Dataset uniqueKeyViolation =
+ Dataset.builder()
+ .withName("orders")
+ .withSource(NameIdentifier.of("sales", "mart", "orders"))
+ .withUniqueKeys(new String[][] {{"order_id"}, {"region",
"tenant_id"}})
+ .withFields(
+ new Field[] {
+ field("order_id", expression("o_orderkey")),
+ field("tenant_id", expression("o_tenantkey"))
+ })
+ .build();
+ assertInvalid(
+ definition(uniqueKeyViolation),
+ "datasets[0].uniqueKeys[1][0]: 'region' is not a declared field of
dataset 'orders'");
+
+ Dataset noFields =
+ Dataset.builder()
+ .withName("orders")
+ .withSource(NameIdentifier.of("sales", "mart", "orders"))
+ .withPrimaryKey(new String[] {"order_id"})
+ .build();
+ assertInvalid(
+ definition(noFields),
+ "datasets[0].primaryKey[0]: 'order_id' is not a declared field of
dataset 'orders'");
+ }
+
+ @Test
+ public void testRelationshipColumnsResolveToEndpointFields() {
+ Dataset orders = datasetWithFields("orders", "customer_id", "tenant_id");
+ Dataset customers = datasetWithFields("customers", "id", "tenant_id");
+
+ assertDoesNotThrow(
+ () ->
+ SemanticModelValidator.validateDefinition(
+ definition(
+ new Dataset[] {orders, customers},
+ new Relationship[] {
+ relationship(
+ "by_customer",
+ "orders",
+ "customers",
+ new String[] {"Customer_ID", "TENANT_ID"},
+ new String[] {"id", "Tenant_Id"})
+ },
+ null)));
+
+ assertInvalid(
+ definition(
+ new Dataset[] {orders, customers},
+ new Relationship[] {
+ relationship(
+ "bad_from", "orders", "customers", new String[] {"missing"},
new String[] {"id"})
+ },
+ null),
+ "relationships[0].fromColumns[0]: 'missing' is not a declared field of
dataset 'orders'");
+
+ assertInvalid(
+ definition(
+ new Dataset[] {orders, customers},
+ new Relationship[] {
+ relationship(
+ "bad_to",
+ "orders",
+ "customers",
+ new String[] {"customer_id"},
+ new String[] {"missing"})
+ },
+ null),
+ "relationships[0].toColumns[0]: 'missing' is not a declared field of
dataset 'customers'");
+
+ // A dataset that declares no fields exposes nothing to relationship
columns.
+ Dataset fieldless = dataset("customers");
+ assertInvalid(
+ definition(
+ new Dataset[] {orders, fieldless},
+ new Relationship[] {
+ relationship(
+ "bad_to",
+ "orders",
+ "customers",
+ new String[] {"customer_id"},
+ new String[] {"id"})
+ },
+ null),
+ "relationships[0].toColumns[0]: 'id' is not a declared field of
dataset 'customers'");
+ }
+
private static void assertInvalid(
@Nullable SemanticModelDefinition definition, String expectedMessage) {
IllegalSemanticModelException exception =
@@ -231,10 +368,18 @@ public class TestSemanticModelValidator {
}
private static Dataset datasetWithField(String name, String fieldName) {
+ return datasetWithFields(name, fieldName);
+ }
+
+ private static Dataset datasetWithFields(String name, String... fieldNames) {
+ Field[] fields = new Field[fieldNames.length];
+ for (int index = 0; index < fieldNames.length; index++) {
+ fields[index] = field(fieldNames[index], expression(fieldNames[index]));
+ }
return Dataset.builder()
.withName(name)
.withSource(NameIdentifier.of("sales", "mart", name))
- .withFields(new Field[] {field(fieldName, expression(fieldName))})
+ .withFields(fields)
.build();
}
diff --git a/design-docs/gravitino-semantic-model-design.md
b/design-docs/gravitino-semantic-model-design.md
index ac72ab07cc..7f353ef560 100644
--- a/design-docs/gravitino-semantic-model-design.md
+++ b/design-docs/gravitino-semantic-model-design.md
@@ -181,10 +181,12 @@ Field
reference contract is defined.
- Inline query sources are not supported. A query-backed source must first be
created as a logical
View and then referenced by `NameIdentifier`.
-- For Table and logical View sources, every column named by `primary_key`,
`unique_keys`,
- `from_columns`, or `to_columns` must exist in the source metadata.
Validation rejects the
- definition when column metadata is unavailable or a named column is missing;
Gravitino does not
- infer these references from free-form field or metric expressions.
+- `primary_key`, `unique_keys`, `from_columns`, and `to_columns` name fields
declared in the
+ referenced datasets' `fields`, not columns of the datasets' sources,
following the Ossie Name
+ Resolution rules. Field names compare case-insensitively. A dataset that
declares no fields
+ exposes no names to keys or relationships. Validation rejects the definition
when a named field
+ is not declared; Gravitino does not infer these references from free-form
field or metric
+ expressions.
#### Relationships and Metrics
@@ -209,8 +211,8 @@ Metric
- Relationship and Metric names are unique within a Semantic Model.
- Each relationship endpoint names a Dataset in the same Semantic Model.
-- `from_columns` and `to_columns` are non-empty, have equal lengths, and name
columns exposed by
- their respective Dataset sources.
+- `from_columns` and `to_columns` are non-empty, have equal lengths, and name
fields declared by
+ the `from` and `to` datasets respectively.
- Metrics may reference fields and datasets in the same Semantic Model.
Cross-model metric
references are not defined by this contract.
diff --git a/docs/manage-semantic-model-metadata-using-gravitino.md
b/docs/manage-semantic-model-metadata-using-gravitino.md
index 3506589aca..c1631d765d 100644
--- a/docs/manage-semantic-model-metadata-using-gravitino.md
+++ b/docs/manage-semantic-model-metadata-using-gravitino.md
@@ -125,8 +125,8 @@ metric over orders and links orders to customers by
`customer_id`. The native RE
definition under `definition`. Its field names include `primaryKey` and
`datatype`.
The relationship's `from` and `to` name datasets in the model. Its column
lists and the datasets'
-keys use source table column names, even when those columns are not listed in
`fields`. Each array
-inside `uniqueKeys` defines one unique key.
+keys name fields declared in `fields` by the referenced datasets, not columns
of the source
+tables. Each array inside `uniqueKeys` defines one unique key.
<Tabs groupId='language' queryString>
<TabItem value="shell" label="REST">
@@ -150,6 +150,18 @@ curl -X POST -H "Accept:
application/vnd.gravitino.v1+json" \
"dialects": [{"dialect": "ANSI_SQL", "expression":
"order_amount"}]
},
"datatype": "Decimal"
+ },
+ {
+ "name": "order_id",
+ "expression": {
+ "dialects": [{"dialect": "ANSI_SQL", "expression": "order_id"}]
+ }
+ },
+ {
+ "name": "customer_id",
+ "expression": {
+ "dialects": [{"dialect": "ANSI_SQL", "expression":
"customer_id"}]
+ }
}
]
},
@@ -158,7 +170,20 @@ curl -X POST -H "Accept:
application/vnd.gravitino.v1+json" \
"source": {"namespace": ["sales", "mart"], "name": "customers"},
"primaryKey": ["customer_id"],
"uniqueKeys": [["customer_code"]],
- "fields": []
+ "fields": [
+ {
+ "name": "customer_id",
+ "expression": {
+ "dialects": [{"dialect": "ANSI_SQL", "expression":
"customer_id"}]
+ }
+ },
+ {
+ "name": "customer_code",
+ "expression": {
+ "dialects": [{"dialect": "ANSI_SQL", "expression":
"customer_code"}]
+ }
+ }
+ ]
}
],
"relationships": [
@@ -194,15 +219,33 @@ Expression amountExpression = Expression.builder()
}).build();
Field amount = Field.builder().withName("order_amount")
.withExpression(amountExpression).withDatatype(DataType.DECIMAL).build();
+// Key and join fields only need a name and an expression over the source
columns.
+private static Expression keyExpression(String column) {
+ return Expression.builder()
+ .withDialects(new DialectExpression[] {
+ DialectExpression.builder().withDialect(Dialects.ANSI_SQL)
+ .withExpression(column).build()
+ }).build();
+}
+Field orderId = Field.builder().withName("order_id")
+ .withExpression(keyExpression("order_id")).build();
+Field orderCustomer = Field.builder().withName("customer_id")
+ .withExpression(keyExpression("customer_id")).build();
+Field customerId = Field.builder().withName("customer_id")
+ .withExpression(keyExpression("customer_id")).build();
+Field customerCode = Field.builder().withName("customer_code")
+ .withExpression(keyExpression("customer_code")).build();
Dataset orders = Dataset.builder().withName("orders")
.withSource(NameIdentifier.of("sales", "mart", "orders"))
.withPrimaryKey(new String[] {"order_id"})
- .withFields(new Field[] {amount}).build();
+ .withFields(new Field[] {amount, orderId, orderCustomer})
+ .build();
Dataset customers = Dataset.builder().withName("customers")
.withSource(NameIdentifier.of("sales", "mart", "customers"))
.withPrimaryKey(new String[] {"customer_id"})
.withUniqueKeys(new String[][] {{"customer_code"}})
- .withFields(new Field[0]).build();
+ .withFields(new Field[] {customerId, customerCode})
+ .build();
Relationship ordersToCustomers =
Relationship.builder().withName("orders_to_customers")
.withFrom("orders").withTo("customers")
.withFromColumns(new String[] {"customer_id"})
@@ -232,17 +275,19 @@ amount = Field(
"order_amount",
Expression([DialectExpression(Dialects.ANSI_SQL, "order_amount")]),
datatype=DataType.DECIMAL)
+def key_field(name):
+ return Field(name, Expression([DialectExpression(Dialects.ANSI_SQL,
name)]))
orders = Dataset(
"orders",
NameIdentifier.of("sales", "mart", "orders"),
primary_key=["order_id"],
- fields=[amount])
+ fields=[amount, key_field("order_id"), key_field("customer_id")])
customers = Dataset(
"customers",
NameIdentifier.of("sales", "mart", "customers"),
primary_key=["customer_id"],
unique_keys=[["customer_code"]],
- fields=[])
+ fields=[key_field("customer_id"), key_field("customer_code")])
orders_to_customers = Relationship(
"orders_to_customers",
from_dataset="orders",
@@ -633,11 +678,31 @@ datasets:
- dialect: ANSI_SQL
expression: order_amount
datatype: Decimal
+ - name: order_id
+ expression:
+ dialects:
+ - dialect: ANSI_SQL
+ expression: order_id
+ - name: customer_id
+ expression:
+ dialects:
+ - dialect: ANSI_SQL
+ expression: customer_id
- name: customers
source: sales.mart.customers
primary_key: [customer_id]
unique_keys: [[customer_code]]
- fields: []
+ fields:
+ - name: customer_id
+ expression:
+ dialects:
+ - dialect: ANSI_SQL
+ expression: customer_id
+ - name: customer_code
+ expression:
+ dialects:
+ - dialect: ANSI_SQL
+ expression: customer_code
relationships:
- name: orders_to_customers
from: orders
diff --git a/docs/open-api/semantic-models.yaml
b/docs/open-api/semantic-models.yaml
index 8207706ade..89a6f82458 100644
--- a/docs/open-api/semantic-models.yaml
+++ b/docs/open-api/semantic-models.yaml
@@ -511,16 +511,16 @@ components:
primaryKey:
type: array
description: >-
- Source columns that form the primary key. The property may be
omitted; an explicitly
- supplied empty array is retained as empty.
+ Names of fields declared in this dataset's fields that form the
primary key. The
+ property may be omitted; an explicitly supplied empty array is
retained as empty.
items:
type: string
minLength: 1
uniqueKeys:
type: array
description: >-
- Source column sets that form unique keys. The property may be
omitted; an explicitly
- supplied empty array is retained as empty.
+ Sets of field names declared in this dataset's fields that form
unique keys. The
+ property may be omitted; an explicitly supplied empty array is
retained as empty.
items:
type: array
minItems: 1
@@ -570,16 +570,16 @@ components:
primary_key:
type: array
description: >-
- Source columns that form the primary key. The property may be
omitted; an explicitly
- supplied empty array is retained as empty.
+ Names of fields declared in this dataset's fields that form the
primary key. The
+ property may be omitted; an explicitly supplied empty array is
retained as empty.
items:
type: string
minLength: 1
unique_keys:
type: array
description: >-
- Source column sets that form unique keys. The property may be
omitted; an explicitly
- supplied empty array is retained as empty.
+ Sets of field names declared in this dataset's fields that form
unique keys. The
+ property may be omitted; an explicitly supplied empty array is
retained as empty.
items:
type: array
minItems: 1
@@ -667,7 +667,8 @@ components:
type: array
minItems: 1
description: >-
- Non-empty source columns. The array must have the same number of
entries as toColumns.
+ Non-empty field names declared by the from dataset. The array must
have the same
+ number of entries as toColumns.
items:
type: string
minLength: 1
@@ -675,8 +676,8 @@ components:
type: array
minItems: 1
description: >-
- Non-empty target columns. The array must have the same number of
entries as
- fromColumns.
+ Non-empty field names declared by the to dataset. The array must
have the same number
+ of entries as fromColumns.
items:
type: string
minLength: 1
@@ -841,7 +842,8 @@ components:
type: array
minItems: 1
description: >-
- Non-empty source columns. The array must have the same number of
entries as to_columns.
+ Non-empty field names declared by the from dataset. The array must
have the same
+ number of entries as to_columns.
items:
type: string
minLength: 1
@@ -849,8 +851,8 @@ components:
type: array
minItems: 1
description: >-
- Non-empty target columns. The array must have the same number of
entries as
- from_columns.
+ Non-empty field names declared by the to dataset. The array must
have the same number
+ of entries as from_columns.
items:
type: string
minLength: 1
@@ -1520,6 +1522,17 @@ components:
]
},
"datatype": "Decimal"
+ },
+ {
+ "name": "order_id",
+ "expression": {
+ "dialects": [
+ {
+ "dialect": "ANSI_SQL",
+ "expression": "order_id"
+ }
+ ]
+ }
}
]
}
@@ -1614,6 +1627,28 @@ components:
"data": "{\"semantic_type\":\"money\"}"
}
]
+ },
+ {
+ "name": "order_id",
+ "expression": {
+ "dialects": [
+ {
+ "dialect": "ANSI_SQL",
+ "expression": "order_id"
+ }
+ ]
+ }
+ },
+ {
+ "name": "customer_id",
+ "expression": {
+ "dialects": [
+ {
+ "dialect": "ANSI_SQL",
+ "expression": "customer_id"
+ }
+ ]
+ }
}
],
"customExtensions": []
@@ -1624,7 +1659,19 @@ components:
"namespace": ["sales", "mart"],
"name": "customers"
},
- "fields": []
+ "fields": [
+ {
+ "name": "customer_id",
+ "expression": {
+ "dialects": [
+ {
+ "dialect": "ANSI_SQL",
+ "expression": "customer_id"
+ }
+ ]
+ }
+ }
+ ]
}
],
"relationships": [
diff --git a/docs/semantic-models.md b/docs/semantic-models.md
index 4c48c53ccf..99a137bda4 100644
--- a/docs/semantic-models.md
+++ b/docs/semantic-models.md
@@ -42,7 +42,7 @@ definition, and audit information. The definition uses these
components:
|-----------|---------|
| `datasets` | A required, non-empty list of named sources. Each dataset can
define fields, a primary key, and unique keys. |
| `fields` | Named expressions within a dataset, with optional data types,
labels, descriptions, and dimension information. |
-| `relationships` | Links between datasets in the same model, using source
column names in `fromColumns` and `toColumns`. |
+| `relationships` | Links between datasets in the same model, using the
endpoint datasets' field names in `fromColumns` and `toColumns`. |
| `metrics` | Named expressions such as `SUM(orders.order_amount)`, with
optional data types and descriptions. |
| `aiContext` | Context for consumers, represented as text or a structured
object. |
| `customExtensions` | Vendor-specific information preserved with the
definition. |
@@ -71,17 +71,19 @@ catalog or schema in that metalake. Each source must
resolve to an existing tabl
supported by its catalog. Cross-metalake references are not supported.
The `from` and `to` endpoints of a relationship name datasets within the model.
-Primary-key, unique-key, and relationship columns refer to columns of the
source table or view,
-rather than field aliases in the model. Gravitino checks that these columns
exist; it does not
+Primary-key, unique-key, and relationship entries name fields declared in
`fields` by the
+referenced datasets, not columns of the source table or view. A dataset that
declares no fields
+exposes no names to keys or relationships. Gravitino checks that these fields
exist; it does not
check whether the data satisfies the declared keys or relationships.
-Creating, importing, or replacing a definition checks source existence and
these columns, even
-when authorization is disabled. With authorization enabled, source lookups
also require the
-caller's access to the source metadata.
+Creating, importing, or replacing a definition checks source existence and
these field
+references, even when authorization is disabled. With authorization enabled,
source lookups also
+require the caller's access to the source metadata.
Loading or exporting a model, renaming it, and changing only its comment or
properties do not
-revalidate source metadata. Review definitions when their source schemas
change: a stored model
-can become stale after a source column is changed or removed.
+revalidate source metadata. Review definitions when their source schemas
change: field
+expressions are not checked against source columns, so a stored model can
become stale after a
+source column is changed or removed.
### Exchanging Definitions
diff --git
a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelSourceValidator.java
b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelSourceValidator.java
index 4f10549318..3f9f34bd04 100644
---
a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelSourceValidator.java
+++
b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelSourceValidator.java
@@ -19,10 +19,8 @@
package org.apache.gravitino.server.web.rest;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -43,13 +41,11 @@ import org.apache.gravitino.connector.CatalogOperations;
import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.exceptions.IllegalSemanticModelException;
import org.apache.gravitino.exceptions.NotFoundException;
-import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.TableCatalog;
import org.apache.gravitino.rel.View;
import org.apache.gravitino.rel.ViewCatalog;
import org.apache.gravitino.semantic.Dataset;
-import org.apache.gravitino.semantic.Relationship;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.semantic.SemanticModelSource;
import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
@@ -58,7 +54,7 @@ import
org.apache.gravitino.server.authorization.expression.AuthorizationExpress
import
org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;
import org.apache.gravitino.utils.NameIdentifierUtil;
-/** Validates source visibility, existence, and explicit column references
before model writes. */
+/** Validates source visibility and existence before model writes. */
public class SemanticModelSourceValidator {
private final TableDispatcher tables;
private final ViewDispatcher views;
@@ -112,10 +108,13 @@ public class SemanticModelSourceValidator {
}
/**
- * Validates every dataset source and key or relationship column under the
current caller.
+ * Validates every dataset source under the current caller.
*
- * <p>This method must run even when authorization is disabled. It does not
interpret SQL
- * expressions or validate transitive view dependencies. Connection failures
propagate unchanged.
+ * <p>Key and relationship references resolve to fields declared inside the
model and are checked
+ * by {@code SemanticModelValidator}; this validator only resolves the
datasets' sources against
+ * the catalog. This method must run even when authorization is disabled. It
does not interpret
+ * SQL expressions or validate transitive view dependencies. Connection
failures propagate
+ * unchanged.
*
* @param metalake the request's metalake, also used for cross-catalog
source references
* @param definition the complete definition to validate before persistence
@@ -124,7 +123,6 @@ public class SemanticModelSourceValidator {
public SemanticModelSourceUpdate validate(String metalake,
SemanticModelDefinition definition) {
AuthorizationRequestContext context = new AuthorizationRequestContext();
GravitinoAuthorizer currentAuthorizer = authorizer.get();
- Map<String, Set<String>> datasetColumns = new HashMap<>();
Map<NameIdentifier, ResolvedSource> resolvedSources = new HashMap<>();
List<SemanticModelSource> associations = new ArrayList<>();
for (Dataset dataset : definition.datasets()) {
@@ -138,25 +136,7 @@ public class SemanticModelSourceValidator {
ResolvedSource resolved =
resolvedSources.computeIfAbsent(
ident, key -> loadSource(key, currentAuthorizer, context));
- Set<String> columns = resolved.columns;
associations.add(new SemanticModelSource(dataset.name(), resolved.type,
resolved.id));
- datasetColumns.put(dataset.name(), columns);
- checkColumns(dataset.name(), dataset.primaryKey(), columns);
- if (dataset.uniqueKeys() != null) {
- for (String[] key : dataset.uniqueKeys()) {
- checkColumns(dataset.name(), key, columns);
- }
- }
- }
- if (definition.relationships() != null) {
- for (Relationship relationship : definition.relationships()) {
- checkColumns(
- relationship.from(),
- relationship.fromColumns(),
- datasetColumns.get(relationship.from()));
- checkColumns(
- relationship.to(), relationship.toColumns(),
datasetColumns.get(relationship.to()));
- }
}
return SemanticModelSourceUpdate.replace(associations);
}
@@ -188,17 +168,14 @@ public class SemanticModelSourceValidator {
if (tableAllowed && supported.contains(Entity.EntityType.TABLE)) {
try {
Table table = tables.loadTable(ident);
- Set<String> columns = columnNames(ident, table.columns());
- return new ResolvedSource(
- registeredTableId(ident, table), Entity.EntityType.TABLE,
columns);
+ return new ResolvedSource(registeredTableId(ident, table),
Entity.EntityType.TABLE);
} catch (NotFoundException missing) {
// An untyped source can also refer to a view.
}
}
if (viewAllowed && supported.contains(Entity.EntityType.VIEW)) {
View view = views.loadView(ident);
- Set<String> columns = columnNames(ident, view.columns());
- return new ResolvedSource(registeredViewId(ident, view),
Entity.EntityType.VIEW, columns);
+ return new ResolvedSource(registeredViewId(ident, view),
Entity.EntityType.VIEW);
}
} catch (NotFoundException missing) {
// Do not disclose whether the other, inaccessible object type exists.
@@ -250,12 +227,10 @@ public class SemanticModelSourceValidator {
private static class ResolvedSource {
private final long id;
private final Entity.EntityType type;
- private final Set<String> columns;
- private ResolvedSource(long id, Entity.EntityType type, Set<String>
columns) {
+ private ResolvedSource(long id, Entity.EntityType type) {
this.id = id;
this.type = type;
- this.columns = columns;
}
}
@@ -270,28 +245,4 @@ public class SemanticModelSourceValidator {
NameIdentifierUtil.splitNameIdentifier(ident.namespace().level(0),
type, ident),
context);
}
-
- private Set<String> columnNames(NameIdentifier ident, Column[] columns) {
- if (columns == null) {
- throw new IllegalSemanticModelException(
- "Column metadata is unavailable for source %s", ident);
- }
- Set<String> names = new HashSet<>();
- Arrays.stream(columns).forEach(column -> names.add(column.name()));
- return names;
- }
-
- private void checkColumns(String dataset, String[] references, Set<String>
columns) {
- if (columns == null) {
- throw new IllegalSemanticModelException("Unknown dataset %s in
relationship", dataset);
- }
- if (references != null) {
- for (String reference : references) {
- if (!columns.contains(reference)) {
- throw new IllegalSemanticModelException(
- "Dataset %s source has no column %s", dataset, reference);
- }
- }
- }
- }
}
diff --git
a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
index 97334951f0..a3aef2c439 100644
---
a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
+++
b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
@@ -213,9 +213,6 @@ public class TestSemanticModelOperations extends
BaseOperationsTest {
viewsSupported = true;
sourceAuthorizer = new PassThroughAuthorizer();
Table table = registeredTable();
- Column column = mock(Column.class);
- when(column.name()).thenReturn("order_id");
- when(table.columns()).thenReturn(new Column[] {column});
when(tables.loadTable(any())).thenReturn(table);
when(dispatcher.loadSemanticModel(any())).thenReturn(semanticModel("sales",
null));
doCallRealMethod().when(dispatcher).importOssieDocument(any(), any(),
any());
@@ -287,7 +284,7 @@ public class TestSemanticModelOperations extends
BaseOperationsTest {
}
@ParameterizedTest
- @ValueSource(strings = {"missing", "denied", "connection", "column"})
+ @ValueSource(strings = {"missing", "denied", "connection"})
void testOssieImportValidatesSourcesBeforePersistence(String failure) {
String yaml =
"version: 0.2.0.dev0\nname: sales\ndatasets:\n"
@@ -315,12 +312,6 @@ public class TestSemanticModelOperations extends
BaseOperationsTest {
type = ConnectionFailedException.class;
message = "offline";
break;
- case "column":
- Table table = registeredTable();
- when(table.columns()).thenReturn(new Column[0]);
- when(tables.loadTable(any())).thenReturn(table);
- message = "order_id";
- break;
default:
throw new AssertionError(failure);
}
@@ -728,9 +719,6 @@ public class TestSemanticModelOperations extends
BaseOperationsTest {
// The original table was renamed and another table now uses its previous
name.
Table replacementTable = registeredTable(202L);
- Column column = mock(Column.class);
- when(column.name()).thenReturn("order_id");
- when(replacementTable.columns()).thenReturn(new Column[] {column});
when(tables.loadTable(any())).thenReturn(replacementTable);
SemanticModelDefinition replacement = original;
if (metricOnlyChange) {
@@ -1016,17 +1004,21 @@ public class TestSemanticModelOperations extends
BaseOperationsTest {
@ParameterizedTest
@ValueSource(booleans = {false, true})
- void testMissingColumnWithAuthorizationDisabled(boolean replaceDefinition) {
+ void testSourceColumnMetadataIsNotConsulted(boolean replaceDefinition) {
+ // Keys and relationship columns resolve to declared dataset fields, so
source column
+ // metadata is never read during source validation.
Table table = registeredTable();
when(table.columns()).thenReturn(new Column[0]);
when(tables.loadTable(any())).thenReturn(table);
- assertError(
- writeDefinition(replaceDefinition, semanticModelDefinition()),
- Response.Status.BAD_REQUEST,
- ErrorConstants.ILLEGAL_ARGUMENTS_CODE,
- IllegalSemanticModelException.class.getSimpleName(),
- "order_id");
- verifyNoModelWrites();
+ when(dispatcher.createSemanticModel(any(), any(), any(), any(), any()))
+ .thenReturn(semanticModel("sales", null));
+ when(dispatcher.alterSemanticModel(any(), any(),
any(SemanticModelChange[].class)))
+ .thenReturn(semanticModel("sales", null));
+ Assertions.assertEquals(
+ Response.Status.OK.getStatusCode(),
+ writeDefinition(replaceDefinition,
semanticModelDefinition()).getStatus());
+ verify(table, never()).columns();
+ verifyNoInteractions(views);
}
@ParameterizedTest
diff --git
a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelSourceValidator.java
b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelSourceValidator.java
index 688af61c45..bbf34bab6b 100644
---
a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelSourceValidator.java
+++
b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelSourceValidator.java
@@ -23,10 +23,10 @@ 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.doReturn;
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.verifyNoInteractions;
@@ -58,7 +58,6 @@ import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.exceptions.NoSuchViewException;
import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.meta.ViewEntity;
-import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.TableCatalog;
import org.apache.gravitino.rel.View;
@@ -90,7 +89,7 @@ public class TestSemanticModelSourceValidator {
@Test
void testCrossCatalogSourceAndKeysWithDisabledAuthorization() {
- table("id", "unique_id");
+ table();
validator.validate(
"metalake",
definition(dataset("orders", new String[] {"id"}, new String[][]
{{"id", "unique_id"}})));
@@ -101,7 +100,6 @@ public class TestSemanticModelSourceValidator {
@Test
void testManagedTableUsesIdentityFromLoadedProperties() {
Table managed = mock(Table.class);
- doReturn(columns("id")).when(managed).columns();
when(managed.properties())
.thenReturn(StringIdentifier.newPropertiesWithId(StringIdentifier.fromId(303L),
Map.of()));
EntityCombinedTable combined =
EntityCombinedTable.of(managed).withImported(true);
@@ -123,7 +121,6 @@ public class TestSemanticModelSourceValidator {
@Test
void testTableWithoutRegisteredIdentityIsRejected() {
Table table = mock(Table.class);
- doReturn(columns("id")).when(table).columns();
when(tables.loadTable(FULL_SOURCE)).thenReturn(table);
assertThrows(
IllegalStateException.class,
@@ -142,14 +139,12 @@ public class TestSemanticModelSourceValidator {
void testViewWithoutRegisteredIdentityIsRejected() {
when(tables.loadTable(FULL_SOURCE)).thenThrow(new
NoSuchTableException("missing"));
View view = mock(View.class);
- doReturn(columns("id")).when(view).columns();
when(views.loadView(FULL_SOURCE)).thenReturn(view);
assertThrows(
IllegalStateException.class,
() -> validator.validate("metalake", definition(dataset("orders",
null, null))));
EntityCombinedView combined = mock(EntityCombinedView.class);
- doReturn(columns("id")).when(combined).columns();
when(views.loadView(FULL_SOURCE)).thenReturn(combined);
assertThrows(
IllegalStateException.class,
@@ -160,7 +155,6 @@ public class TestSemanticModelSourceValidator {
void testManagedViewUsesIdentityFromLoadedProperties() {
when(tables.loadTable(FULL_SOURCE)).thenThrow(new
NoSuchTableException("missing"));
View managed = mock(View.class);
- doReturn(columns("id")).when(managed).columns();
when(managed.properties())
.thenReturn(StringIdentifier.newPropertiesWithId(StringIdentifier.fromId(404L),
Map.of()));
EntityCombinedView combined =
EntityCombinedView.of(managed).withImported(true);
@@ -184,40 +178,49 @@ public class TestSemanticModelSourceValidator {
}
@Test
- void testViewFallbackAndColumns() {
+ void testViewFallback() {
when(tables.loadTable(FULL_SOURCE)).thenThrow(new
NoSuchTableException("missing"));
View view = registeredView();
- doReturn(columns("id")).when(view).columns();
when(views.loadView(FULL_SOURCE)).thenReturn(view);
SemanticModelSourceUpdate update =
- validator.validate("metalake", definition(dataset("orders", new
String[] {"id"}, null)));
+ validator.validate("metalake", definition(dataset("orders", null,
null)));
assertEquals(1, update.sources().size());
assertEquals(202L, update.sources().get(0).getSourceId());
assertEquals(EntityType.VIEW, update.sources().get(0).getSourceType());
- assertThrows(
- IllegalSemanticModelException.class,
- () ->
- validator.validate(
- "metalake", definition(dataset("orders", new String[]
{"missing"}, null))));
}
@Test
- void testMissingUniqueKeyAndUnavailableColumns() {
- Table table = table("id");
- assertThrows(
- IllegalSemanticModelException.class,
- () ->
- validator.validate(
- "metalake", definition(dataset("orders", null, new String[][]
{{"missing"}}))));
- when(table.columns()).thenReturn(null);
- assertThrows(
- IllegalSemanticModelException.class,
- () -> validator.validate("metalake", definition(dataset("orders",
null, null))));
+ void testKeyAndJoinReferencesAreNotResolvedAgainstSource() {
+ // Keys and relationship columns name fields declared inside the model;
this validator never
+ // reads source column metadata, so undeclared names still pass here.
+ Table table = table();
+ Dataset orders =
+ dataset("orders", new String[] {"undeclared_key"}, new String[][]
{{"undeclared_unique"}});
+ Dataset customers = dataset("customers", null, null);
+ SemanticModelDefinition definition =
+ SemanticModelDefinition.builder()
+ .withDatasets(new Dataset[] {orders, customers})
+ .withRelationships(
+ new Relationship[] {
+ Relationship.builder()
+ .withName("orders_customers")
+ .withFrom("orders")
+ .withTo("customers")
+ .withFromColumns(new String[] {"undeclared_join"})
+ .withToColumns(new String[] {"undeclared_join"})
+ .build()
+ })
+ .build();
+
+ SemanticModelSourceUpdate update = validator.validate("metalake",
definition);
+
+ assertEquals(2, update.sources().size());
+ verify(table, never()).columns();
}
@Test
- void testRelationshipColumnsAndRepeatedSource() {
- table("id");
+ void testRelationshipAndRepeatedSource() {
+ table();
Dataset first = dataset("orders", null, null);
Dataset second = dataset("customers", null, null);
SemanticModelDefinition valid = related(first, second, "id", "id");
@@ -229,19 +232,12 @@ public class TestSemanticModelSourceValidator {
assertEquals("orders", update.sources().get(0).getDatasetName());
assertEquals("customers", update.sources().get(1).getDatasetName());
verify(tables, times(1)).loadTable(FULL_SOURCE);
- assertThrows(
- IllegalSemanticModelException.class,
- () -> validator.validate("metalake", related(first, second, "missing",
"id")));
- assertThrows(
- IllegalSemanticModelException.class,
- () -> validator.validate("metalake", related(first, second, "id",
"missing")));
}
@Test
void testDeniedTableCanResolveAuthorizedViewWithoutTableLookup() {
authorizeOnly(MetadataObject.Type.VIEW, Privilege.Name.SELECT_VIEW);
View view = registeredView();
- doReturn(columns("id")).when(view).columns();
when(views.loadView(FULL_SOURCE)).thenReturn(view);
validator.validate("metalake", definition(dataset("orders", null, null)));
verifyNoInteractions(tables);
@@ -251,13 +247,8 @@ public class TestSemanticModelSourceValidator {
@Test
void testAuthorizedTableDoesNotRequireViewAccess() {
authorizeOnly(MetadataObject.Type.TABLE, Privilege.Name.SELECT_TABLE);
- table("id");
- validator.validate("metalake", definition(dataset("orders", new String[]
{"id"}, null)));
- assertThrows(
- IllegalSemanticModelException.class,
- () ->
- validator.validate(
- "metalake", definition(dataset("orders", new String[]
{"missing"}, null))));
+ table();
+ validator.validate("metalake", definition(dataset("orders", null, null)));
verifyNoInteractions(views);
}
@@ -359,12 +350,11 @@ public class TestSemanticModelSourceValidator {
void testViewOnlyCatalogCanResolveSourceWithoutTableLookup() {
authorizeOnly(MetadataObject.Type.VIEW, Privilege.Name.SELECT_VIEW);
View view = registeredView();
- doReturn(columns("id")).when(view).columns();
when(views.loadView(FULL_SOURCE)).thenReturn(view);
SemanticModelSourceValidator checking =
new SemanticModelSourceValidator(
tables, views, () -> authorizer, ident ->
EnumSet.of(EntityType.VIEW));
- checking.validate("metalake", definition(dataset("orders", new String[]
{"id"}, null)));
+ checking.validate("metalake", definition(dataset("orders", null, null)));
verifyNoInteractions(tables);
verify(views).loadView(FULL_SOURCE);
when(views.loadView(FULL_SOURCE)).thenThrow(new
NoSuchViewException("missing"));
@@ -418,22 +408,12 @@ public class TestSemanticModelSourceValidator {
});
}
- private Table table(String... names) {
+ private Table table() {
Table table = registeredTable();
- doReturn(columns(names)).when(table).columns();
when(tables.loadTable(FULL_SOURCE)).thenReturn(table);
return table;
}
- private Column[] columns(String... names) {
- Column[] columns = new Column[names.length];
- for (int i = 0; i < names.length; i++) {
- columns[i] = mock(Column.class);
- when(columns[i].name()).thenReturn(names[i]);
- }
- return columns;
- }
-
private Dataset dataset(String name, String[] primaryKey, String[][]
uniqueKeys) {
return Dataset.builder()
.withName(name)
diff --git a/web-v2/web/src/lib/utils/semanticModel.js
b/web-v2/web/src/lib/utils/semanticModel.js
index ce8145873b..1499e6bb10 100644
--- a/web-v2/web/src/lib/utils/semanticModel.js
+++ b/web-v2/web/src/lib/utils/semanticModel.js
@@ -38,6 +38,24 @@ export const semanticDataTypes = [
const isNonBlankString = value => typeof value === 'string' && value.trim()
!== ''
+const normalizeFieldName = name => name.toLowerCase()
+
+const declaredFieldNames = dataset =>
+ new Set(
+ (Array.isArray(dataset?.fields) ? dataset.fields : [])
+ .map(field => field?.name)
+ .filter(isNonBlankString)
+ .map(normalizeFieldName)
+ )
+
+const validateFieldReferences = (references, path, datasetName, fieldNames,
errors) => {
+ references.forEach((reference, index) => {
+ if (isNonBlankString(reference) &&
!fieldNames.has(normalizeFieldName(reference))) {
+ errors.push(`${path}[${index}] '${reference}' is not a declared field of
dataset "${datasetName}".`)
+ }
+ })
+}
+
const duplicatesOf = names => {
const seen = new Set()
const duplicates = new Set()
@@ -147,7 +165,13 @@ const validateDatasets = (datasets, errors) => {
validateSource(dataset, errors)
validateMetadata(dataset, `datasets[${index}]`, errors)
+
+ // Keys name fields declared by the dataset, not columns of its source.
+ const fieldNames = declaredFieldNames(dataset)
validateStringArray(dataset.primaryKey, `datasets[${index}].primaryKey`,
errors)
+ if (Array.isArray(dataset.primaryKey)) {
+ validateFieldReferences(dataset.primaryKey,
`datasets[${index}].primaryKey`, dataset.name, fieldNames, errors)
+ }
if (dataset.uniqueKeys != null) {
if (!Array.isArray(dataset.uniqueKeys)) {
@@ -159,6 +183,7 @@ const validateDatasets = (datasets, errors) => {
errors.push(`${path} must be a non-empty array.`)
} else {
validateStringArray(key, path, errors)
+ validateFieldReferences(key, path, dataset.name, fieldNames,
errors)
}
})
}
@@ -183,7 +208,13 @@ const validateDatasets = (datasets, errors) => {
validateMetadata(field, path, errors)
})
- const duplicateFields = duplicatesOf((fields || []).map(field =>
field?.name).filter(isNonBlankString))
+ // Field names resolve case-insensitively, so names equal ignoring case
must not coexist.
+ const duplicateFields = duplicatesOf(
+ (fields || [])
+ .map(field => field?.name)
+ .filter(isNonBlankString)
+ .map(normalizeFieldName)
+ )
if (duplicateFields.length) {
errors.push(`Field names must be unique within dataset
"${dataset.name}": ${duplicateFields.join(', ')}.`)
}
@@ -195,7 +226,7 @@ const validateDatasets = (datasets, errors) => {
}
}
-const validateRelationships = (relationships, datasetNames, errors) => {
+const validateRelationships = (relationships, datasetNames, datasetFields,
errors) => {
relationships.forEach((relationship, index) => {
if (!isPlainObject(relationship) || !isNonBlankString(relationship.name)) {
errors.push(`relationships[${index}] must have a non-empty name.`)
@@ -222,6 +253,16 @@ const validateRelationships = (relationships,
datasetNames, errors) => {
}
validateStringArray(fromColumns, `relationships[${index}].fromColumns`,
errors)
validateStringArray(toColumns, `relationships[${index}].toColumns`, errors)
+
+ // Endpoint columns name fields declared by the endpoint datasets, not
source columns.
+ const fromFieldNames = datasetFields.get(from)
+ const toFieldNames = datasetFields.get(to)
+ if (fromFieldNames) {
+ validateFieldReferences(fromColumns,
`relationships[${index}].fromColumns`, from, fromFieldNames, errors)
+ }
+ if (toFieldNames) {
+ validateFieldReferences(toColumns, `relationships[${index}].toColumns`,
to, toFieldNames, errors)
+ }
})
const duplicates = duplicatesOf(relationships.map(relationship =>
relationship?.name).filter(isNonBlankString))
@@ -251,7 +292,7 @@ const validateMetrics = (metrics, errors) => {
/**
* Checks the structural rules the server also enforces, so obvious mistakes
are reported before the
* request is sent. The server stays the authority: it additionally resolves
every dataset source
- * and its columns against the catalog, which the browser cannot do.
+ * against the catalog, which the browser cannot do.
*
* @param {unknown} definition The parsed semantic model definition.
* @returns {string[]} The problems found, empty when the definition looks
well formed.
@@ -274,9 +315,15 @@ export const validateSemanticModelDefinition = definition
=> {
const datasetNames = new Set(datasets.map(dataset =>
dataset?.name).filter(isNonBlankString))
+ const datasetFields = new Map(
+ datasets
+ .filter(dataset => isPlainObject(dataset) &&
isNonBlankString(dataset?.name))
+ .map(dataset => [dataset.name, declaredFieldNames(dataset)])
+ )
+
if (relationships != null) {
if (Array.isArray(relationships)) {
- validateRelationships(relationships, datasetNames, errors)
+ validateRelationships(relationships, datasetNames, datasetFields, errors)
} else {
errors.push('The definition must declare relationships as an array.')
}
diff --git a/web-v2/web/src/lib/utils/semanticModel.test.js
b/web-v2/web/src/lib/utils/semanticModel.test.js
index 3b39d35bbd..7d9d421d02 100644
--- a/web-v2/web/src/lib/utils/semanticModel.test.js
+++ b/web-v2/web/src/lib/utils/semanticModel.test.js
@@ -34,7 +34,11 @@ const orders = {
const customers = {
name: 'customers',
- source: { namespace: ['sales', 'mart'], name: 'customers' }
+ source: { namespace: ['sales', 'mart'], name: 'customers' },
+ fields: [
+ { name: 'id', expression: { dialects: [{ dialect: 'ANSI_SQL', expression:
'id' }] } },
+ { name: 'tenant_id', expression: { dialects: [{ dialect: 'ANSI_SQL',
expression: 'tenant_id' }] } }
+ ]
}
const definitionOf = overrides => ({ datasets: [orders], ...overrides })
@@ -109,6 +113,22 @@ describe('validateSemanticModelDefinition', () => {
expect(errors).toEqual(['Field names must be unique within dataset
"orders": order_id.'])
})
+ test('rejects field names that differ only by case', () => {
+ const errors = validateSemanticModelDefinition({
+ datasets: [
+ {
+ ...orders,
+ fields: [
+ ...orders.fields,
+ { name: 'Order_Id', expression: { dialects: [{ dialect:
'ANSI_SQL', expression: 'other_id' }] } }
+ ]
+ }
+ ]
+ })
+
+ expect(errors).toEqual(['Field names must be unique within dataset
"orders": order_id.'])
+ })
+
test('accepts the same field name in two different datasets', () => {
const errors = validateSemanticModelDefinition({
datasets: [orders, { ...customers, fields: orders.fields }]
@@ -121,7 +141,7 @@ describe('validateSemanticModelDefinition', () => {
const errors = validateSemanticModelDefinition({
datasets: [orders],
relationships: [
- { name: 'orders_customers', from: 'orders', to: 'customers',
fromColumns: ['a'], toColumns: ['b'] }
+ { name: 'orders_customers', from: 'orders', to: 'customers',
fromColumns: ['order_id'], toColumns: ['id'] }
]
})
@@ -132,7 +152,13 @@ describe('validateSemanticModelDefinition', () => {
const errors = validateSemanticModelDefinition({
datasets: [orders, customers],
relationships: [
- { name: 'orders_customers', from: 'orders', to: 'customers',
fromColumns: ['a'], toColumns: ['b', 'c'] }
+ {
+ name: 'orders_customers',
+ from: 'orders',
+ to: 'customers',
+ fromColumns: ['order_id'],
+ toColumns: ['id', 'tenant_id']
+ }
]
})
@@ -153,7 +179,7 @@ describe('validateSemanticModelDefinition', () => {
name: 'orders_customers',
from: 'orders',
to: 'customers',
- fromColumns: ['customer_id'],
+ fromColumns: ['order_id'],
toColumns: ['id']
}
@@ -182,11 +208,60 @@ describe('validateSemanticModelDefinition', () => {
'Dataset "customers" must have a source with a namespace and a name.'
])
})
+
+ test('rejects key references that are not declared fields', () => {
+ const errors = validateSemanticModelDefinition({
+ datasets: [{ ...orders, primaryKey: ['missing_key'], uniqueKeys:
[['order_id'], ['missing_unique']] }]
+ })
+
+ expect(errors).toEqual([
+ `datasets[0].primaryKey[0] 'missing_key' is not a declared field of
dataset "orders".`,
+ `datasets[0].uniqueKeys[1][0] 'missing_unique' is not a declared field
of dataset "orders".`
+ ])
+ })
+
+ test('rejects relationship columns that are not declared fields of the
endpoint datasets', () => {
+ const errors = validateSemanticModelDefinition({
+ datasets: [orders, { ...customers, fields: [] }],
+ relationships: [
+ {
+ name: 'orders_customers',
+ from: 'orders',
+ to: 'customers',
+ fromColumns: ['missing_from'],
+ toColumns: ['id']
+ }
+ ]
+ })
+
+ expect(errors).toEqual([
+ `relationships[0].fromColumns[0] 'missing_from' is not a declared field
of dataset "orders".`,
+ `relationships[0].toColumns[0] 'id' is not a declared field of dataset
"customers".`
+ ])
+ })
+
+ test('matches declared field references case-insensitively', () => {
+ const errors = validateSemanticModelDefinition({
+ datasets: [{ ...orders, primaryKey: ['ORDER_ID'], uniqueKeys:
[['Order_Id']] }],
+ relationships: [
+ { name: 'self', from: 'orders', to: 'orders', fromColumns:
['Order_ID'], toColumns: ['order_id'] }
+ ]
+ })
+
+ expect(errors).toEqual([])
+ })
})
describe('nested Semantic Model contract validation', () => {
const expression = { dialects: [{ dialect: 'ANSI_SQL', expression: 'amount'
}] }
- const relationship = { name: 'self', from: 'orders', to: 'orders',
fromColumns: ['id'], toColumns: ['id'] }
+
+ const relationship = {
+ name: 'self',
+ from: 'orders',
+ to: 'orders',
+ fromColumns: ['order_id'],
+ toColumns: ['order_id']
+ }
test.each(['field', 'metric'])('accepts only the server-supported optional
%s data types', kind => {
const withType = datatype =>
@@ -317,7 +392,19 @@ describe('nested Semantic Model contract validation', ()
=> {
).toEqual([])
expect(
validateSemanticModelDefinition({
- datasets: [{ ...orders, primaryKey: ['order_id'], uniqueKeys:
[['amount'], ['id', 'region']] }],
+ datasets: [
+ {
+ ...orders,
+ fields: [
+ ...orders.fields,
+ { name: 'amount', expression },
+ { name: 'id', expression },
+ { name: 'region', expression }
+ ],
+ primaryKey: ['order_id'],
+ uniqueKeys: [['amount'], ['id', 'region']]
+ }
+ ],
relationships: [relationship],
metrics: [
{