Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions converters/salesforce/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,10 +255,11 @@ dimensions.

### Metric expressions

Metrics select `TABLEAU`, then `SNOWFLAKE`, then `ANSI_SQL`, independent of entry
order. The selected expression is parsed and validated; an invalid preferred
expression fails rather than falling back to another dialect. Duplicate selected
dialect entries are errors. Successful conversion exports every declared metric.
Metrics select `TABLEAU`, then `SNOWFLAKE`, then `ANSI_SQL`, then
`OSSIE_SQL_2026`, independent of entry order. The selected expression is parsed
and validated; an invalid preferred expression fails rather than falling back to
another dialect. Duplicate selected dialect entries are errors. Successful
conversion exports every declared metric.

The target is the Salesforce/Tableau Next semantic model's
[Tua calculation language](https://developer.salesforce.com/docs/data/semantic-layer/guide/query-api-in-depth-functions.html).
Expand Down Expand Up @@ -317,7 +318,15 @@ belong to separate converter work.
subset is the Tua equivalents above, including `IF`, `IFNULL`, `ISNULL`, `COUNTD`
and `CEILING`. Existing `ANSI_SQL` expressions using complete bracket notation
retain that spelling as a compatibility case and receive the same validation.
Bracket notation is not accepted as Snowflake SQL.
Bracket notation is not accepted as Snowflake or `OSSIE_SQL_2026` SQL.

`OSSIE_SQL_2026` is the spec's own
[portable expression language](../../core-spec/expression_language.md), based on
ANSI SQL:2003 Core, so it is parsed and validated exactly like `ANSI_SQL` and
quotes identifiers with double quotes. It is selected last because a dialect
authored for a specific engine states that engine's intent more precisely. The
supported function subset is unchanged: spec aliases such as `IFNULL`, `NVL` and
`CEILING` remain outside it, as they already are for `ANSI_SQL`.

Fields need a known compatible datatype, either declared in OSI or restored from
an existing Salesforce field type. Arithmetic and `SUM`/`AVG` require numbers;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@

/** Compiles the documented metric subset: parse, bind/check, then emit bounded Tua text. */
final class MetricExpressionTranslator {
private static final List<String> DIALECTS = List.of("TABLEAU", "SNOWFLAKE", "ANSI_SQL");
/** Preference order. OSSIE_SQL_2026 is the spec's portable ANSI-SQL-based dialect, so it parses as SQL. */
private static final List<String> DIALECTS = List.of("TABLEAU", "SNOWFLAKE", "ANSI_SQL", "OSSIE_SQL_2026");
private static final String SUPPORTED = String.join(", ", DIALECTS);
private static final Set<String> AGGREGATES = Set.of("SUM", "AVG", "MIN", "MAX", "COUNT", "COUNTD");
record Result(String expression, String dataType) {}
private MetricExpressionTranslator() {}
Expand All @@ -48,7 +50,7 @@ static Result translate(Map<String, Object> metric, MetricFieldResolver resolver
Map<String, Object> expression = getMap(metric, "expression");
List<Object> dialects = expression == null ? null : getList(expression, "dialects");
if (dialects == null) {
throw new IllegalArgumentException("missing expression.dialects; provide TABLEAU, SNOWFLAKE or ANSI_SQL");
throw new IllegalArgumentException("missing expression.dialects; provide one of " + SUPPORTED);
}
Map<String, String> candidates = new java.util.LinkedHashMap<>();
for (Object entry : dialects) {
Expand All @@ -63,7 +65,7 @@ static Result translate(Map<String, Object> metric, MetricFieldResolver resolver
}
String dialect = DIALECTS.stream().filter(candidates::containsKey).findFirst()
.orElseThrow(() -> new IllegalArgumentException(
"no supported dialect; provide TABLEAU, SNOWFLAKE or ANSI_SQL"));
"no supported dialect; provide one of " + SUPPORTED));
String text = candidates.get(dialect);
if (text == null || text.isBlank()) {
throw new IllegalArgumentException(dialect + " expression is empty");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@

/** Native Tua frontend for the bounded supported grammar; produces the same AST as SQL. */
final class TuaMetricExpressionParser {
/** Bracketed identifiers are Tua's own notation; ANSI_SQL keeps them as a documented compatibility case. */
private static final Set<String> BRACKET_DIALECTS = Set.of("TABLEAU", "ANSI_SQL");
private final List<Token> tokens;
private int position;
private int depth;
Expand Down Expand Up @@ -156,7 +158,7 @@ static List<Token> tokenize(String text, String dialect) {
if (Character.isWhitespace(c)) { i++; continue; }
int start = i;
if (c == '\'' || c == '"' || c == '[') {
if (c == '[' && dialect.equals("SNOWFLAKE")) throw lexical(dialect, i, "use double-quoted SQL identifiers");
if (c == '[' && !BRACKET_DIALECTS.contains(dialect)) throw lexical(dialect, i, "use double-quoted SQL identifiers");
boolean string = c == '\'' || (c == '"' && dialect.equals("TABLEAU"));
char end = c == '[' ? ']' : c;
StringBuilder value = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ void setUp() {
}

@ParameterizedTest
@ValueSource(strings = {"SNOWFLAKE", "ANSI_SQL"})
@ValueSource(strings = {"SNOWFLAKE", "ANSI_SQL", "OSSIE_SQL_2026"})
void translatesComposedMetricsThroughStringApi(String dialect) throws Exception {
Map<String, Object> output = convertOne(model("sales", List.of(
metric("margin", dialect, "SUM(orders.profit) / NULLIF(SUM(orders.revenue), 0)"),
Expand Down Expand Up @@ -295,12 +295,16 @@ void translatedComposedMetricsValidateAgainstTheSalesforceSchema() throws Except
Map<String, Object> output = convertOne(model("sales", List.of(
metric("margin", "SNOWFLAKE", "SUM(orders.profit) / NULLIF(SUM(orders.revenue), 0)"),
metric("customers", "ANSI_SQL", "COUNT(DISTINCT orders.customer_id)"),
metric("rounding", "ANSI_SQL", "ROUND(AVG(ABS(orders.profit)), 2) + CEIL(1.2) - FLOOR(1.2)"))));
metric("rounding", "ANSI_SQL", "ROUND(AVG(ABS(orders.profit)), 2) + CEIL(1.2) - FLOOR(1.2)"),
metric("portable", "OSSIE_SQL_2026",
"SUM(\"ORDERS\".\"PROFIT\") / NULLIF(SUM(\"ORDERS\".\"REVENUE\"), 0)"))));
SchemaValidator validator = new SchemaValidator(JSON, SchemaValidator.SALESFORCE_SCHEMA_PATH);

for (Map<String, Object> metric : measurements(output)) {
assertMeasurementMetadata(metric);
}
assertEquals("(SUM([orders].[profit]) / (IF (SUM([orders].[revenue]) = 0) THEN NULL "
+ "ELSE SUM([orders].[revenue]) END))", measurements(output).get(3).get("expression"));
assertDoesNotThrow(() -> validator.validate(output));

// OSI expression objects cannot be emitted where Salesforce requires a scalar formula.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
import org.junit.jupiter.params.provider.ValueSource;

class MetricExpressionTranslatorTest {
/** The dialects that share the SQL frontend; OSSIE_SQL_2026 is ANSI SQL by specification. */
private static final List<String> SQL_DIALECTS = List.of("SNOWFLAKE", "ANSI_SQL", "OSSIE_SQL_2026");
private static final Map<String, String> TYPES = Map.of(
"amount", "Decimal", "profit", "Decimal", "revenue", "Decimal", "discount", "Decimal",
"quantity", "Integer", "status", "String", "active", "Boolean", "ordered", "Date");
Expand Down Expand Up @@ -107,9 +109,10 @@ static Stream<Arguments> supported() {

@ParameterizedTest
@MethodSource("supported")
void compilesComposedSqlInBothDialects(String expression, String expected) {
assertEquals(expected, translate("SNOWFLAKE", expression));
assertEquals(expected, translate("ANSI_SQL", expression));
void compilesComposedSqlInEverySqlDialect(String expression, String expected) {
for (String dialect : SQL_DIALECTS) {
assertEquals(expected, translate(dialect, expression), dialect);
}
// Every generated expression can be read through the bounded TABLEAU path.
assertEquals(expected, translate("TABLEAU", expected));
}
Expand Down Expand Up @@ -216,6 +219,32 @@ void tableauCannotBypassParsingOrReferenceValidation(String expression) {
assertThrows(ConversionException.class, () -> translate("TABLEAU", expression));
}

@Test
void portableOssieSqlCompilesWhenItIsTheOnlyDialect() {
assertEquals("SUM([orders].[amount])", translate("OSSIE_SQL_2026", "SUM(orders.amount)"));
}

@Test
void vendorDialectsArePreferredOverPortableOssieSql() {
Map<String, Object> metric = metric("OSSIE_SQL_2026", "SUM(orders.amount)");
for (String preferred : List.of("TABLEAU", "SNOWFLAKE", "ANSI_SQL")) {
metric.put("expression", Map.of("dialects", List.of(
Map.of("dialect", "OSSIE_SQL_2026", "expression", "SUM(orders.amount)"),
Map.of("dialect", preferred, "expression", preferred.equals("TABLEAU")
? "SUM([orders].[profit])" : "SUM(orders.profit)"))));
assertEquals("SUM([orders].[profit])",
MetricExpressionTranslator.translate(metric, source(), target()).expression(), preferred);
}
}

@Test
void portableOssieSqlQuotesIdentifiersTheAnsiWay() {
assertEquals("SUM([orders].[amount])", translate("OSSIE_SQL_2026", "SUM(\"ORDERS\".\"AMOUNT\")"));
assertTrue(assertThrows(ConversionException.class,
() -> translate("OSSIE_SQL_2026", "SUM([orders].[amount])"))
.getMessage().contains("use double-quoted SQL identifiers"));
}

@Test
void selectedDialectFailureNeverFallsBack() {
Map<String, Object> metric = metric("TABLEAU", "SUM([orders].[missing])");
Expand Down Expand Up @@ -271,7 +300,7 @@ void limitsNestingAndExpansionWithoutStackOverflow() {
@Test
void redundantParenthesesStayWithinTheBoundedFastParsingPath() {
assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
for (String dialect : List.of("SNOWFLAKE", "ANSI_SQL")) {
for (String dialect : SQL_DIALECTS) {
for (int depth : List.of(20, 60, 126)) {
String grouped = "(".repeat(depth) + "orders.amount" + ")".repeat(depth);
assertEquals("SUM([orders].[amount])", translate(dialect, "SUM(" + grouped + ")"));
Expand All @@ -287,7 +316,7 @@ void redundantParenthesesStayWithinTheBoundedFastParsingPath() {

@Test
void normalizationRetainsOriginalLimitsAndOperandTypes() {
for (String dialect : List.of("SNOWFLAKE", "ANSI_SQL")) {
for (String dialect : SQL_DIALECTS) {
for (String expression : List.of("SUM(" + "- ".repeat(129) + "orders.amount)",
"SUM(CASE WHEN " + "NOT ".repeat(129) + "orders.active THEN 1 ELSE 0 END)",
"SUM(" + "(".repeat(128) + "orders.amount" + ")".repeat(128) + ")",
Expand All @@ -305,7 +334,7 @@ void normalizationRetainsOriginalLimitsAndOperandTypes() {

@Test
void redundantGroupingCannotTurnTuplesIntoFunctionArguments() {
for (String dialect : List.of("SNOWFLAKE", "ANSI_SQL")) {
for (String dialect : SQL_DIALECTS) {
for (String function : List.of("COALESCE", "ROUND")) {
for (int depth : List.of(1, 20)) {
String tuple = "(".repeat(depth) + "SUM(orders.amount), 2" + ")".repeat(depth);
Expand Down Expand Up @@ -366,7 +395,7 @@ void quotedDotsAndEscapesPreserveFieldReferenceBoundaries() {
Map<String, Object> target = Map.of("semanticDataObjects", List.of(Map.of("apiName", "ORDER.ITEMS",
"semanticMeasurements", List.of(Map.of("apiName", "NET REVENUE", "dataType", "Number",
"dataObjectFieldName", "net__c")))));
for (String dialect : List.of("SNOWFLAKE", "ANSI_SQL")) {
for (String dialect : SQL_DIALECTS) {
assertEquals("SUM([ORDER.ITEMS].[NET REVENUE])", MetricExpressionTranslator.translate(
metric(dialect, "SUM(\"ORDER.ITEMS\".\"NET REVENUE\")"), source, target).expression());
var field = (MetricExpression.Field) SqlMetricExpressionParser.parse("\"a\"\"b.c\".\"d\"\"e\"", dialect);
Expand Down
Loading