You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@ossie.apache.org by "owlas (via GitHub)" <gi...@apache.org> on 2026/10/21 12:28:04 UTC
[PR] Add lightdash converter [ossie-converters]
owlas opened a new pull request, #7:
URL: https://github.com/apache/ossie-converters/pull/7
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
-->
## Summary
Migrated from main repo
## Related Issues
<!-- Link any related GitHub issues: Closes #123, Fixes #456 -->
## Checklist
### Converters
- [ ] Converter logic is updated to reflect spec or ontology changes in [apache/ossie-converters](https://github.com/apache/ossie-converters)
- [ ] New converters include tests under the converter's test directory
- [ ] If adding a new converter, `.github/labeler.yml`, `.github/dependabot.yml` and a `converter-<name>-ci.yml` workflow are added for the new path
### Documentation
- [ ] The converter's `README.md` is updated to reflect any user-facing changes
### Tests
- [ ] All existing tests pass (`pytest` / `mvn verify` / CI green)
- [ ] New functionality is covered by tests
### Compliance
- [ ] ASF license headers are present on all new source files
- [ ] No third-party dependencies are added without PMC/IPMC approval
- [ ] If third-party source code is vendored/copied (not just declared as a dependency), `NOTICE` and/or `LICENSE` have been updated per [ASF policy](https://infra.apache.org/licensing-howto.html)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ossie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add lightdash converter [ossie-converters]
Posted by "jbonofre (via GitHub)" <gi...@apache.org>.
jbonofre commented on code in PR #7:
URL: https://github.com/apache/ossie-converters/pull/7#discussion_r4375969400
##########
lightdash/src/ossie_lightdash/expression_utils.py:
##########
@@ -0,0 +1,317 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+"""Expression helpers shared by both conversion directions.
+
+Lightdash SQL snippets reference the current model as ``${TABLE}.column``,
+sibling fields as ``${column}`` or ``${metric}``, joined models as
+``${other_table.column}`` and project parameters or user attributes as
+``${lightdash.…}`` or ``${ld.…}``. Ossie expressions reference columns as
+``dataset.column``. These helpers translate between the two forms and
+recognize the aggregation shapes that map to Lightdash's typed metrics.
+"""
+
+import re
+from dataclasses import dataclass, field
+from typing import Callable, Dict, List, Optional
+
+import sqlglot
+from sqlglot import exp
+
+_SQLGLOT_DIALECTS = {
+ "BIGQUERY": "bigquery",
+ "SNOWFLAKE": "snowflake",
+ "DATABRICKS": "databricks",
+}
+
+_REFERENCE_RE = re.compile(r"\$\{([^}]+)\}")
+_NON_PORTABLE_REFERENCE_RE = re.compile(r"\$\{(?:lightdash|ld)\.[^}]*\}")
+# Lightdash evaluates Liquid tags, and the bare `ld.parameters.x`,
+# `ld.query.filters`, and `ld.user.x` references inside them, at query time.
+_NON_PORTABLE_SYNTAX_RE = re.compile(
+ r"\{%|\{\{|(?<![\w.])(?:lightdash|ld)\.(?:parameters|query|user)\."
+)
+_COLUMN_REFERENCE_RE = re.compile(r"^[A-Za-z_]\w*(?:\.\w+)?$")
+
+# Lightdash metric types that the Ossie expression encodes as an aggregation.
+# Any other type exports as a `number` metric with raw SQL.
+_AGGREGATE_FUNCTIONS = {
+ "sum": "SUM",
+ "min": "MIN",
+ "max": "MAX",
+ "average": "AVG",
+ "median": "MEDIAN",
+ "count": "COUNT",
+}
+_DISTINCT_AGGREGATE_FUNCTIONS = {
+ "count_distinct": "COUNT",
+ "sum_distinct": "SUM",
+ "average_distinct": "AVG",
+}
+AGGREGATE_TYPES = frozenset(
+ {*_AGGREGATE_FUNCTIONS, *_DISTINCT_AGGREGATE_FUNCTIONS, "percentile"}
+)
+
+_FUNCTION_TO_TYPE = {
+ "SUM": "sum",
+ "MIN": "min",
+ "MAX": "max",
+ "AVG": "average",
+ "AVERAGE": "average",
+ "MEDIAN": "median",
+ "COUNT": "count",
+}
+_DISTINCT_FUNCTION_TO_TYPE = {
+ "COUNT": "count_distinct",
+ "SUM": "sum_distinct",
+ "AVG": "average_distinct",
+ "AVERAGE": "average_distinct",
+}
+
+_CALL_RE = re.compile(r"^\s*(?P<func>[A-Za-z_]+)\s*\((?P<body>.*)\)\s*$", re.DOTALL)
+_DISTINCT_RE = re.compile(r"^DISTINCT\s+(?P<inner>.+)$", re.IGNORECASE | re.DOTALL)
+_PERCENTILE_RE = re.compile(
+ r"^\s*PERCENTILE_CONT\s*\(\s*(?P<fraction>[0-9]*\.?[0-9]+)\s*\)\s*"
+ r"WITHIN\s+GROUP\s*\(\s*ORDER\s+BY\s+(?P<inner>.+?)\s*\)\s*$",
+ re.IGNORECASE | re.DOTALL,
+)
+
+
+@dataclass(frozen=True)
+class ParsedAggregation:
+ lightdash_type: str
+ inner: str
+ percentile: Optional[float] = None
+
+
+def _is_single_call_body(body: str) -> bool:
+ """Checks whether the parentheses in ``body`` are balanced, that is,
+ whether the parentheses around it belong to one function call."""
+ depth = 0
+ for char in body:
+ if char == "(":
+ depth += 1
+ elif char == ")":
+ depth -= 1
+ if depth < 0:
+ return False
+ return depth == 0
+
+
+def parse_aggregation(expression: str) -> Optional[ParsedAggregation]:
+ """Parses an expression that is exactly one aggregation over an operand.
+
+ ``SUM(x)``, ``COUNT(DISTINCT x)``, ``SUM(DISTINCT x)``, and
+ ``PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY x)`` map to Lightdash's typed
+ metrics. The operand can be a bare column reference or any expression.
+
+ Returns:
+ The parsed aggregation, or None for any other shape (``COUNT(*)``,
+ arithmetic between aggregations, unknown functions).
+ """
+ percentile_match = _PERCENTILE_RE.match(expression)
+ if percentile_match:
+ percentile = float(percentile_match.group("fraction")) * 100
+ if percentile.is_integer():
+ percentile = int(percentile)
+ return ParsedAggregation(
+ "percentile", percentile_match.group("inner").strip(), percentile
+ )
+
+ match = _CALL_RE.match(expression)
+ if match is None or not _is_single_call_body(match.group("body")):
+ return None
+ function = match.group("func").upper()
+ inner = match.group("body").strip()
+ distinct = _DISTINCT_RE.match(inner)
+ if distinct:
+ lightdash_type = _DISTINCT_FUNCTION_TO_TYPE.get(function)
+ inner = distinct.group("inner").strip()
+ else:
+ lightdash_type = _FUNCTION_TO_TYPE.get(function)
+ if lightdash_type is None or not inner or inner == "*":
+ return None
+ return ParsedAggregation(lightdash_type, inner)
+
+
+def build_aggregation(
+ lightdash_type: str, inner: str, percentile: Optional[float] = None
+) -> Optional[str]:
+ """Builds the Ossie expression for a typed Lightdash metric over ``inner``.
+
+ Returns:
+ The expression, or None for a metric type that is not an aggregation
+ (``number``, ``string``, ``boolean``, and so on).
+ """
+ if lightdash_type == "percentile":
+ fraction = (50 if percentile is None else percentile) / 100
+ return f"PERCENTILE_CONT({fraction:g}) WITHIN GROUP (ORDER BY {inner})"
+ if lightdash_type in _DISTINCT_AGGREGATE_FUNCTIONS:
+ return f"{_DISTINCT_AGGREGATE_FUNCTIONS[lightdash_type]}(DISTINCT {inner})"
+ function = _AGGREGATE_FUNCTIONS.get(lightdash_type)
+ if function is None:
+ return None
+ return f"{function}({inner})"
+
+
+def is_column_reference(expression: str) -> bool:
+ """Checks whether ``expression`` is a bare ``column`` or ``qualifier.column`` reference."""
+ return _COLUMN_REFERENCE_RE.match(expression) is not None
+
+
+def strip_qualifier(column_ref: str) -> str:
+ """Gets the bare column name of a ``column`` or ``qualifier.column`` reference."""
+ return column_ref.rsplit(".", 1)[-1]
+
+
+def qualifier_of(column_ref: str) -> Optional[str]:
+ """Gets the qualifier of a ``qualifier.column`` reference, or None."""
+ if "." in column_ref:
+ return column_ref.rsplit(".", 1)[0]
+ return None
+
+
+def ossie_sql_to_lightdash(
+ expression: str, dataset: str, references: Optional[Dict[str, str]] = None
+) -> str:
+ """Rewrites Ossie column references into Lightdash references.
+
+ ``dataset.column`` becomes ``${TABLE}.column``. A dataset in
+ ``references`` (joined from ``dataset``) becomes
+ ``${<join reference>.column}``, where the join reference is the joined
+ model's name or its alias.
+ """
+ # The dataset's own mapping is applied last, so a join reference can't
+ # override it. In a self-join (`employees` joined as `manager`), the
+ # model's own columns stay `${TABLE}.col`.
+ names = {**(references or {}), dataset: None}
+
+ def replace(match: "re.Match[str]") -> str:
+ name, column = match.group(1), match.group(2)
+ reference = names[name]
+ if reference is None:
+ return f"${{TABLE}}.{column}"
+ return f"${{{reference}.{column}}}"
+
+ alternatives = "|".join(re.escape(name) for name in names)
+ return re.sub(rf"\b({alternatives})\.(\w+)", replace, expression)
Review Comment:
`ossie_sql_to_lightdash` rewrites `\b(dataset)\.(\w+)` anywhere in the text. That includes string literals and the tail of a longer dotted path:
- `CASE WHEN note = 'see orders.total' THEN 1 END` becomes `'see ${TABLE}.total'` in the literal, which changes the data being compared.
- `warehouse.orders.id` becomes `warehouse.${TABLE}.id`, which is invalid SQL, because `\b` matches between the dots.
`referenced_datasets` has the same flow. A dataset mentioned only in a literal counts as referenced, which can pick the wrong target dataset or raise `FIELD_REFERENCE_UNJOINED`.
I suggest to tokenize or mask quoted literal before substitution. We could add a negative lookbehind (`(?<![\w.])`) so qualified paths are not touched. We could share one helper between `ossie_sql_to_lightdash` and `referenced_datasets` so they can't drift apart. A couple of tests would be welcome 😄
##########
lightdash/src/ossie_lightdash/ossie_to_lightdash.py:
##########
@@ -0,0 +1,676 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+"""Converts an Ossie document into Lightdash semantic definitions.
+
+``convert`` produces a dictionary in the shape of a dbt ``schema.yml``, whose
+``meta`` blocks hold Lightdash dimensions, metrics, and joins, for merging
+into a dbt project that Lightdash reads. ``convert_models`` produces native
+Lightdash model files (``type: model``, ``sql_from``, typed dimensions),
+which ``lightdash deploy`` reads directly. Lightdash presentation attributes
+that have no Ossie vocabulary round-trip through ``custom_extensions``
+entries with ``vendor_name: LIGHTDASH``. Their keys are merged into the
+generated definitions and win for presentation attributes. Structural keys
+(``sql`` and ``label`` on dimensions, ``sql`` and ``description`` on metrics,
+``join`` and ``sql_on`` on joins) are protected, so they can't override the
+definition derived from Ossie.
+"""
+
+import json
+import re
+from typing import Any, Dict, List, Optional, Set, Tuple
+
+from ossie import (
+ OssieDataset,
+ OssieDialect,
+ OssieDocument,
+ OssieExpression,
+ OssieMetric,
+ OssieSemanticModel,
+)
+
+from ossie_lightdash.converter_issues import (
+ ConverterIssue,
+ ConverterIssueType,
+ ConverterResult,
+)
+from ossie_lightdash.datatype_utils import datatype_to_lightdash_type, is_temporal
+from ossie_lightdash.expression_utils import (
+ is_column_reference,
+ ossie_sql_to_lightdash,
+ parse_aggregation,
+ qualifier_of,
+ referenced_datasets,
+ strip_qualifier,
+)
+
+LIGHTDASH_VENDOR_NAME = "LIGHTDASH"
+
+# Ossie vocabulary owns the structural keys, and the import never writes them
+# to the extension. Dropping them here keeps a hand-written extension from
+# overriding the definition derived from Ossie. ``type`` stays overridable on
+# a metric whose expression is not a recognized aggregation, because that is
+# how a type an expression can't express (``boolean``, ``string``, and so on)
+# reaches Lightdash.
+_PROTECTED_DIMENSION_KEYS = {"sql", "label", "ai_hint", "hidden", "column_meta"}
+_PROTECTED_METRIC_KEYS = {"sql", "description", "ai_hint", "name", "model"}
+_PROTECTED_AGGREGATION_KEYS = _PROTECTED_METRIC_KEYS | {"type", "percentile"}
+_PROTECTED_JOIN_KEYS = {"join", "sql_on", "alias"}
+# Dataset extension keys that map to Ossie vocabulary or are handled separately.
+_PROTECTED_MODEL_KEYS = {"joins", "metrics", "primary_key", "ai_hint", "name", "type", "sql_from"}
+# Order of the top-level keys in a Lightdash model file. Any other key (model
+# meta from the extension) follows in source order.
+_MODEL_KEY_ORDER = ("type", "name", "label", "description", "sql_from", "primary_key", "ai_hint")
+_DIMENSION_KEY_ORDER = ("name", "type", "label", "description", "sql", "hidden")
+
+# The joins a dataset declares, keyed by the joined dataset. The value is the
+# name Lightdash SQL uses to reference it: the joined model, or its alias. When
+# a dataset is joined more than once, the first join wins.
+JoinReferences = Dict[str, str]
+
+
+def _lightdash_extension_data(element: Any, issues: List[ConverterIssue]) -> Dict[str, Any]:
+ """Gets the ``LIGHTDASH`` extension data of an Ossie element, or an empty mapping."""
+ data: Dict[str, Any] = {}
+ for extension in element.custom_extensions or []:
+ # The vendor name is LIGHTDASH. Documents written before it was
+ # registered used the lowercase name.
+ if extension.vendor_name.upper() == LIGHTDASH_VENDOR_NAME:
+ try:
+ data.update(json.loads(extension.data))
+ except (TypeError, ValueError):
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.EXTENSION_DATA_INVALID,
+ element_name=getattr(element, "name", "<unnamed>"),
+ )
+ )
+ else:
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.FOREIGN_EXTENSION_IGNORED,
+ element_name=getattr(element, "name", "<unnamed>"),
+ )
+ )
+ return data
+
+
+def _ai_hint(ai_context: Any) -> Any:
+ """Converts an Ossie `ai_context` to a Lightdash `ai_hint`. One line stays
+ a string, a multi-line instruction becomes a list, and the synonyms and
+ examples of the structured form become extra hints."""
+ if ai_context is None:
+ return None
+ if isinstance(ai_context, str):
+ hints = ai_context.split("\n")
+ else:
+ hints = (ai_context.instructions or "").split("\n")
+ if ai_context.synonyms:
+ hints.append("Also known as: " + ", ".join(ai_context.synonyms))
+ if ai_context.examples:
+ hints.append("Example questions: " + "; ".join(ai_context.examples))
+ hints = [hint for hint in hints if hint]
+ if not hints:
+ return None
+ return hints[0] if len(hints) == 1 else hints
+
+
+def _ordered(entries: Dict[str, Any], order: Tuple[str, ...]) -> Dict[str, Any]:
+ """Reorders ``entries`` so the keys in ``order`` come first. The rest keep their order."""
+ return {
+ **{key: entries[key] for key in order if key in entries},
+ **{key: value for key, value in entries.items() if key not in order},
+ }
+
+
+def _to_lightdash_model(
+ dataset: OssieDataset, model: Dict[str, Any], issues: List[ConverterIssue]
+) -> Dict[str, Any]:
+ """Reshapes a dbt model with Lightdash meta into a Lightdash model file."""
+ meta = dict(model.get("meta") or {})
+ out: Dict[str, Any] = {"type": "model", "name": model["name"]}
+ if model.get("description"):
+ out["description"] = model["description"]
+ out["sql_from"] = dataset.source
+ joins = meta.pop("joins", None)
+ model_metrics = meta.pop("metrics", None)
+ out.update(meta)
+ if joins:
+ out["joins"] = joins
+ if model_metrics:
+ out["metrics"] = model_metrics
+
+ dimensions: List[Dict[str, Any]] = []
+ for column in model.get("columns") or []:
+ column_meta = column.get("meta") or {}
+ dimension = dict(column_meta.get("dimension") or {})
+ dimension["name"] = column["name"]
+ if column.get("description") and "description" not in dimension:
+ dimension["description"] = column["description"]
+ if not dimension.get("type"):
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.DIMENSION_TYPE_DEFAULTED,
+ element_name=f"{model['name']}.{column['name']}",
+ )
+ )
+ dimension["type"] = "string"
+ if not dimension.get("sql"):
+ dimension["sql"] = f"${{TABLE}}.{column['name']}"
+ if column_meta.get("metrics"):
+ dimension["metrics"] = column_meta["metrics"]
+ if column_meta.get("additional_dimensions"):
+ dimension["additional_dimensions"] = column_meta["additional_dimensions"]
+ if any(key not in ("dimension", "metrics", "additional_dimensions") for key in column_meta):
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.COLUMN_META_NOT_REPRESENTABLE,
+ element_name=f"{model['name']}.{column['name']}",
+ )
+ )
+ dimensions.append(_ordered(dimension, _DIMENSION_KEY_ORDER))
+ out["dimensions"] = dimensions
+ return _ordered(out, _MODEL_KEY_ORDER)
+
+
+def _nest_meta_under_config(node: Dict[str, Any]) -> None:
+ """Moves a node's ``meta`` under ``config``, the placement dbt 1.10 and later use."""
+ meta = node.pop("meta", None)
+ if meta:
+ node["config"] = {"meta": meta}
+
+
+_MODEL_NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
+_SOURCE_IDENTIFIER = r'(?:[A-Za-z_][A-Za-z0-9_$]*|"(?:""|[^"])+"|`(?:``|[^`])+`|\[(?:\]\]|[^\]])+\])'
+_SOURCE_PATH_RE = re.compile(rf"{_SOURCE_IDENTIFIER}(?:\s*\.\s*{_SOURCE_IDENTIFIER})*")
+
+
+def _model_name_for(dataset: OssieDataset) -> str:
+ """Derives the model name: a simple source's table name, otherwise the dataset name.
+
+ Raises:
+ ValueError: If neither forms a valid model name.
+ """
+ source = dataset.source.strip()
+ # BigQuery can quote the whole project.dataset.table path with backticks.
+ if re.fullmatch(r"`[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+`", source):
+ source = source[1:-1]
+ candidate = source.rsplit(".", 1)[-1]
+ elif _SOURCE_PATH_RE.fullmatch(source):
+ candidate = re.findall(_SOURCE_IDENTIFIER, source)[-1]
+ if candidate[0] in ('"', '`', '['):
+ candidate = candidate[1:-1]
+ else:
+ candidate = dataset.name
+ if not _MODEL_NAME_RE.fullmatch(candidate):
+ candidate = dataset.name
+ if not _MODEL_NAME_RE.fullmatch(candidate):
+ raise ValueError(
+ f"Dataset {dataset.name!r} has no safe Lightdash model name; use a dataset "
+ "name starting with a letter or underscore, followed by letters, digits or underscores."
+ )
+ return candidate
+
+
+class OssieToLightdashConverter:
+ """Converts an ``OssieDocument`` into Lightdash definitions.
+
+ ``dialect`` is the expression dialect to prefer, the project's warehouse.
+ ``OSSIE_SQL_2026`` and ``ANSI_SQL`` are the fallbacks. For an expression
+ that offers none of these, the converter takes the first dialect offered
+ and records a ``DIALECT_UNAVAILABLE`` issue.
+ """
+
+ def __init__(
+ self,
+ dialect: OssieDialect = OssieDialect.ANSI_SQL,
+ *,
+ meta_under_config: bool = False,
+ ) -> None:
+ self._dialect = dialect
+ self._meta_under_config = meta_under_config
+
+ def convert(self, document: OssieDocument) -> ConverterResult[Dict[str, Any]]:
+ """Converts the document into a dbt ``schema.yml`` dictionary with Lightdash ``meta``."""
+ issues: List[ConverterIssue] = []
+ models = [model for _, model in self._convert_semantic_model(document, issues)]
+ if self._meta_under_config:
+ for model in models:
+ _nest_meta_under_config(model)
+ for column in model.get("columns") or []:
+ _nest_meta_under_config(column)
+ return ConverterResult(output={"version": 2, "models": models}, issues=issues)
+
+ def convert_models(self, document: OssieDocument) -> ConverterResult[List[Dict[str, Any]]]:
+ """Converts the document into Lightdash model files, one dictionary per dataset.
+
+ The model-file format has a place for everything the dbt format keeps
+ in the extension: ``sql_from`` is the dataset's ``source`` verbatim,
+ model meta becomes top-level keys, and every dimension has its own
+ ``type`` and ``sql``.
+ """
+ issues: List[ConverterIssue] = []
+ models: List[Dict[str, Any]] = []
+ for dataset, model in self._convert_semantic_model(document, issues):
+ models.append(_to_lightdash_model(dataset, model, issues))
+ return ConverterResult(output=models, issues=issues)
+
+ def _pick_expression(
+ self, expression: OssieExpression, element_name: str, issues: List[ConverterIssue]
+ ) -> str:
+ by_dialect = {
+ dialect_expression.dialect: dialect_expression.expression
+ for dialect_expression in expression.dialects
+ }
+ for dialect in (self._dialect, OssieDialect.OSSIE_SQL_2026, OssieDialect.ANSI_SQL):
+ if dialect in by_dialect:
+ return by_dialect[dialect]
+ if not expression.dialects:
+ return ""
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.DIALECT_UNAVAILABLE,
+ element_name=element_name,
+ )
+ )
+ return expression.dialects[0].expression
+
+ def _convert_semantic_model(
+ self, semantic_model: OssieSemanticModel, issues: List[ConverterIssue]
+ ) -> List[Tuple[OssieDataset, Dict[str, Any]]]:
+ datasets = semantic_model.datasets or []
+ dataset_names = {dataset.name for dataset in datasets}
+ model_name_by_dataset: Dict[str, str] = {}
+ dataset_by_model_name: Dict[str, str] = {}
+ for dataset in datasets:
+ name = _model_name_for(dataset)
+ # Also reject names that differ only in case, for case-insensitive
+ # file systems.
+ previous = dataset_by_model_name.get(name.casefold())
+ if previous is not None:
+ raise ValueError(
+ f"Datasets {previous!r} and {dataset.name!r} both export to "
+ f"Lightdash model {name!r}; model names must be unique (ignoring case)."
+ )
+ if dataset.name in model_name_by_dataset:
+ raise ValueError(f"Duplicate dataset name: {dataset.name!r}")
+ dataset_by_model_name[name.casefold()] = dataset.name
+ model_name_by_dataset[dataset.name] = name
+
+ # Joins are planned first, because field and metric expressions can
+ # reference other datasets only through the joins their own dataset
+ # declares.
+ joins_by_dataset, references_by_dataset = self._plan_joins(
+ semantic_model, model_name_by_dataset, issues
+ )
+
+ models_by_dataset: Dict[str, Dict[str, Any]] = {}
+ columns_by_dataset: Dict[str, Dict[str, Dict[str, Any]]] = {}
+ stash_by_dataset: Dict[str, Dict[str, Any]] = {}
+ for dataset in datasets:
+ stash = _lightdash_extension_data(dataset, issues)
+ stash_by_dataset[dataset.name] = stash
+ # A join kept in the extension (chained, expression, extra
+ # conditions) is restored verbatim. It replaces the generated join
+ # to the same target and alias, and its target becomes
+ # referenceable.
+ joins = joins_by_dataset.setdefault(dataset.name, [])
+ references = references_by_dataset.setdefault(dataset.name, {})
+ for stashed_join in stash.get("joins") or []:
+ if not isinstance(stashed_join, dict) or not isinstance(stashed_join.get("join"), str):
+ continue
+ key = (stashed_join.get("join"), stashed_join.get("alias"))
+ for index, join in enumerate(joins):
+ if (join.get("join"), join.get("alias")) == key:
+ joins[index] = stashed_join
+ break
+ else:
+ joins.append(stashed_join)
+ # `references` is keyed by Ossie dataset name, the way field
+ # and metric expressions name a dataset. The join names the
+ # Lightdash model, which can differ: dataset `customer_ds`
+ # over source `public.customer` is model `customer`. A join
+ # to a model outside the document is keyed by the model name,
+ # so an expression that names it still resolves.
+ joined_model = stashed_join["join"]
+ joined_dataset = dataset_by_model_name.get(joined_model.casefold(), joined_model)
+ references.setdefault(
+ joined_dataset, stashed_join.get("alias") or joined_model
+ )
+ if not joins:
+ del joins_by_dataset[dataset.name]
+
+ for dataset in datasets:
+ model, columns = self._convert_dataset(
+ dataset,
+ model_name_by_dataset[dataset.name],
+ dataset_names,
+ references_by_dataset.get(dataset.name, {}),
+ issues,
+ )
+ meta = model.setdefault("meta", {})
+ meta.update(
+ {
+ key: value
+ for key, value in stash_by_dataset[dataset.name].items()
+ if key not in _PROTECTED_MODEL_KEYS
+ }
+ )
+ if not meta:
+ del model["meta"]
+ models_by_dataset[dataset.name] = model
+ columns_by_dataset[dataset.name] = columns
+
+ for metric in semantic_model.metrics or []:
+ self._convert_metric(
+ metric,
+ [dataset.name for dataset in datasets],
+ models_by_dataset,
+ columns_by_dataset,
+ references_by_dataset,
+ issues,
+ )
+
+ for dataset_name, joins in joins_by_dataset.items():
+ models_by_dataset[dataset_name].setdefault("meta", {})["joins"] = joins
+
+ return [(dataset, models_by_dataset[dataset.name]) for dataset in datasets]
+
+ def _plan_joins(
+ self,
+ semantic_model: OssieSemanticModel,
+ model_name_by_dataset: Dict[str, str],
+ issues: List[ConverterIssue],
+ ) -> Tuple[Dict[str, List[Dict[str, Any]]], Dict[str, JoinReferences]]:
+ joins_by_dataset: Dict[str, List[Dict[str, Any]]] = {}
+ references_by_dataset: Dict[str, JoinReferences] = {}
+ joined_pairs: Set[Tuple[str, str]] = set()
+ for relationship in semantic_model.relationships or []:
+ from_model_name = model_name_by_dataset.get(relationship.from_dataset)
+ to_model_name = model_name_by_dataset.get(relationship.to)
+ if from_model_name is None or to_model_name is None:
+ continue
+ if len(relationship.from_columns) != len(relationship.to_columns):
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.RELATIONSHIP_COLUMNS_MISMATCHED,
+ element_name=relationship.name,
+ )
+ )
+ continue
+ extension_data = _lightdash_extension_data(relationship, issues)
+ # Lightdash rejects a second join to the same table without an
+ # alias. An alias from the extension is restored. Otherwise the
+ # relationship name is the alias for every repeat of a dataset
+ # pair.
+ pair = (relationship.from_dataset, relationship.to)
+ alias = extension_data.get("alias")
+ if alias is None and pair in joined_pairs:
+ alias = relationship.name
+ joined_pairs.add(pair)
+ join_reference = alias or to_model_name
+ sql_on = " AND ".join(
+ f"${{{from_model_name}.{from_column}}} = ${{{join_reference}.{to_column}}}"
+ for from_column, to_column in zip(
+ relationship.from_columns, relationship.to_columns
+ )
+ )
+ # An Ossie relationship always runs from the many side to the one
+ # side. A Lightdash `relationship` from the extension overrides it
+ # below.
+ join: Dict[str, Any] = {"join": to_model_name}
+ if alias:
+ join["alias"] = alias
+ join["sql_on"] = sql_on
+ join["relationship"] = "many-to-one"
+ join.update(
+ {
+ key: value
+ for key, value in extension_data.items()
+ if key not in _PROTECTED_JOIN_KEYS
+ }
+ )
+ joins_by_dataset.setdefault(relationship.from_dataset, []).append(join)
+ references_by_dataset.setdefault(relationship.from_dataset, {}).setdefault(
+ relationship.to, join_reference
+ )
+ return joins_by_dataset, references_by_dataset
+
+ def _convert_dataset(
+ self,
+ dataset: OssieDataset,
+ model_name: str,
+ dataset_names: Set[str],
+ references: JoinReferences,
+ issues: List[ConverterIssue],
+ ) -> tuple:
+ columns_by_name: Dict[str, Dict[str, Any]] = {}
+ for field in dataset.fields or []:
+ column: Dict[str, Any] = {"name": field.name}
+ if field.description:
+ column["description"] = field.description
+
+ dimension: Dict[str, Any] = {}
+ if field.dimension is None:
+ # Every Lightdash column is a dimension. A measure-only Ossie
+ # field becomes a hidden one.
+ dimension["hidden"] = True
+ if field.label:
+ dimension["label"] = field.label
+ ai_hint = _ai_hint(field.ai_context)
+ if ai_hint is not None:
+ dimension["ai_hint"] = ai_hint
+ lightdash_type = datatype_to_lightdash_type(field.datatype)
+ if lightdash_type is not None:
+ dimension["type"] = lightdash_type
+ elif field.dimension is not None and field.dimension.is_time:
+ # There is no datatype to translate, and the field is declared
+ # as a time axis. `date` is the closest Lightdash type.
+ dimension["type"] = "date"
+ if (
+ field.dimension is not None
+ and field.dimension.is_time
+ and not is_temporal(field.datatype)
+ and field.datatype is not None
+ ):
+ # A non-temporal datatype with a time-axis role (for example,
+ # a year stored as Integer) has no Lightdash equivalent.
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.TIME_ROLE_NOT_REPRESENTABLE,
+ element_name=field.name,
+ )
+ )
+ if (
+ field.dimension is not None
+ and field.dimension.is_time is False
+ and is_temporal(field.datatype)
+ ):
+ # The field is explicitly removed from the time axis.
+ # Lightdash's marker for that is `time_intervals: OFF`.
+ dimension["time_intervals"] = "OFF"
+ expression = self._pick_expression(field.expression, field.name, issues)
+ if expression and expression != field.name:
+ unjoined = referenced_datasets(expression, dataset_names) - {
+ dataset.name,
+ *references,
+ }
+ if unjoined:
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.FIELD_REFERENCE_UNJOINED,
+ element_name=field.name,
+ )
+ )
+ dimension["sql"] = ossie_sql_to_lightdash(
+ expression, dataset.name, references
+ )
+ field_data = _lightdash_extension_data(field, issues)
+ dimension.update(
+ {
+ key: value
+ for key, value in field_data.items()
+ if key not in _PROTECTED_DIMENSION_KEYS
+ }
+ )
+ # A dimension with no attributes is Lightdash's default: no meta.
+ if dimension:
+ column["meta"] = {"dimension": dimension}
+ column_meta = field_data.get("column_meta")
+ if isinstance(column_meta, dict) and column_meta:
+ column.setdefault("meta", {}).update(
+ {
+ key: value
+ for key, value in column_meta.items()
+ if key not in ("dimension", "metrics")
+ }
+ )
+ columns_by_name[field.name] = column
+
+ model: Dict[str, Any] = {"name": model_name}
+ if dataset.description:
+ model["description"] = dataset.description
+ meta: Dict[str, Any] = {}
+ if dataset.primary_key:
+ keys = list(dataset.primary_key)
+ meta["primary_key"] = keys[0] if len(keys) == 1 else keys
+ ai_hint = _ai_hint(dataset.ai_context)
+ if ai_hint is not None:
+ meta["ai_hint"] = ai_hint
+ if meta:
+ model["meta"] = meta
+ model["columns"] = list(columns_by_name.values())
+ return model, columns_by_name
+
+ def _convert_metric(
+ self,
+ metric: OssieMetric,
+ dataset_names: List[str],
+ models_by_dataset: Dict[str, Dict[str, Any]],
+ columns_by_dataset: Dict[str, Dict[str, Dict[str, Any]]],
+ references_by_dataset: Dict[str, JoinReferences],
+ issues: List[ConverterIssue],
+ ) -> None:
+ expression = self._pick_expression(metric.expression, metric.name, issues)
+ extension_data = _lightdash_extension_data(metric, issues)
+
+ target_dataset = self._resolve_target_dataset(
Review Comment:
`_resolve_target_dataset` picks the first dataset referenced in the expression and only falls back to the model stored in the LIGHTDASH extension when the expression references no dataset at all.
That breaks round tripping.
For instance, take a metric defined on `orders` with `sql: ${customers.region_id}`. On import it becomes `COUNT(DISTINCT customers.region_id)` and the extension records `model: orders`. On export only `customers` is referenced, so the metric moves to `customers` and is rewritten to `${TABLE}.region_id`. It then lives on a different model, grain and explore, and `lightdash compile` computes a different value, with no warning.
I suggest, when the stashed model is valid and every dataset the metric references is reachable from it through the joins, to use the stashed model. We could use the "first referenced dataset" heuristic only when there is no extension or the stashed model is invalid.
A round-trip test (Lightdash -> Ossie -> Lightdash) with a cross-model metric would catch this.
##########
lightdash/src/ossie_lightdash/expression_utils.py:
##########
@@ -0,0 +1,317 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+"""Expression helpers shared by both conversion directions.
+
+Lightdash SQL snippets reference the current model as ``${TABLE}.column``,
+sibling fields as ``${column}`` or ``${metric}``, joined models as
+``${other_table.column}`` and project parameters or user attributes as
+``${lightdash.…}`` or ``${ld.…}``. Ossie expressions reference columns as
+``dataset.column``. These helpers translate between the two forms and
+recognize the aggregation shapes that map to Lightdash's typed metrics.
+"""
+
+import re
+from dataclasses import dataclass, field
+from typing import Callable, Dict, List, Optional
+
+import sqlglot
+from sqlglot import exp
+
+_SQLGLOT_DIALECTS = {
+ "BIGQUERY": "bigquery",
+ "SNOWFLAKE": "snowflake",
+ "DATABRICKS": "databricks",
+}
+
+_REFERENCE_RE = re.compile(r"\$\{([^}]+)\}")
+_NON_PORTABLE_REFERENCE_RE = re.compile(r"\$\{(?:lightdash|ld)\.[^}]*\}")
+# Lightdash evaluates Liquid tags, and the bare `ld.parameters.x`,
+# `ld.query.filters`, and `ld.user.x` references inside them, at query time.
+_NON_PORTABLE_SYNTAX_RE = re.compile(
+ r"\{%|\{\{|(?<![\w.])(?:lightdash|ld)\.(?:parameters|query|user)\."
+)
+_COLUMN_REFERENCE_RE = re.compile(r"^[A-Za-z_]\w*(?:\.\w+)?$")
+
+# Lightdash metric types that the Ossie expression encodes as an aggregation.
+# Any other type exports as a `number` metric with raw SQL.
+_AGGREGATE_FUNCTIONS = {
+ "sum": "SUM",
+ "min": "MIN",
+ "max": "MAX",
+ "average": "AVG",
+ "median": "MEDIAN",
+ "count": "COUNT",
+}
+_DISTINCT_AGGREGATE_FUNCTIONS = {
+ "count_distinct": "COUNT",
+ "sum_distinct": "SUM",
+ "average_distinct": "AVG",
+}
+AGGREGATE_TYPES = frozenset(
+ {*_AGGREGATE_FUNCTIONS, *_DISTINCT_AGGREGATE_FUNCTIONS, "percentile"}
+)
+
+_FUNCTION_TO_TYPE = {
+ "SUM": "sum",
+ "MIN": "min",
+ "MAX": "max",
+ "AVG": "average",
+ "AVERAGE": "average",
+ "MEDIAN": "median",
+ "COUNT": "count",
+}
+_DISTINCT_FUNCTION_TO_TYPE = {
+ "COUNT": "count_distinct",
+ "SUM": "sum_distinct",
+ "AVG": "average_distinct",
+ "AVERAGE": "average_distinct",
+}
+
+_CALL_RE = re.compile(r"^\s*(?P<func>[A-Za-z_]+)\s*\((?P<body>.*)\)\s*$", re.DOTALL)
+_DISTINCT_RE = re.compile(r"^DISTINCT\s+(?P<inner>.+)$", re.IGNORECASE | re.DOTALL)
+_PERCENTILE_RE = re.compile(
Review Comment:
`_PERCENTILE_RE` is anchored only by a trailing `\)\s*$`, so it never checks that the parentheses are balanced. This expression is accepted as a single percentile:
```
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY a) + PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY b)
```
The captured inner part is `a) + PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY b`. Export then emits a `type: percentile, percentile: 50` metric with broker `sql`. The other aggregations are protected by `_is_single_call_body`, but the percentile branch skips that guard.
I suggest to run the percentile match through the same single-call check, or parse out the balanced `PERCENTILE_CONT(...)` and `WITHIN GROUP (...)` groups explicitly. We could add a test with the compound expression above and expect it to fall back to a custom `sql` metric or raise an issue.
##########
lightdash/src/ossie_lightdash/ossie_to_lightdash.py:
##########
@@ -0,0 +1,676 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+"""Converts an Ossie document into Lightdash semantic definitions.
+
+``convert`` produces a dictionary in the shape of a dbt ``schema.yml``, whose
+``meta`` blocks hold Lightdash dimensions, metrics, and joins, for merging
+into a dbt project that Lightdash reads. ``convert_models`` produces native
+Lightdash model files (``type: model``, ``sql_from``, typed dimensions),
+which ``lightdash deploy`` reads directly. Lightdash presentation attributes
+that have no Ossie vocabulary round-trip through ``custom_extensions``
+entries with ``vendor_name: LIGHTDASH``. Their keys are merged into the
+generated definitions and win for presentation attributes. Structural keys
+(``sql`` and ``label`` on dimensions, ``sql`` and ``description`` on metrics,
+``join`` and ``sql_on`` on joins) are protected, so they can't override the
+definition derived from Ossie.
+"""
+
+import json
+import re
+from typing import Any, Dict, List, Optional, Set, Tuple
+
+from ossie import (
+ OssieDataset,
+ OssieDialect,
+ OssieDocument,
+ OssieExpression,
+ OssieMetric,
+ OssieSemanticModel,
+)
+
+from ossie_lightdash.converter_issues import (
+ ConverterIssue,
+ ConverterIssueType,
+ ConverterResult,
+)
+from ossie_lightdash.datatype_utils import datatype_to_lightdash_type, is_temporal
+from ossie_lightdash.expression_utils import (
+ is_column_reference,
+ ossie_sql_to_lightdash,
+ parse_aggregation,
+ qualifier_of,
+ referenced_datasets,
+ strip_qualifier,
+)
+
+LIGHTDASH_VENDOR_NAME = "LIGHTDASH"
+
+# Ossie vocabulary owns the structural keys, and the import never writes them
+# to the extension. Dropping them here keeps a hand-written extension from
+# overriding the definition derived from Ossie. ``type`` stays overridable on
+# a metric whose expression is not a recognized aggregation, because that is
+# how a type an expression can't express (``boolean``, ``string``, and so on)
+# reaches Lightdash.
+_PROTECTED_DIMENSION_KEYS = {"sql", "label", "ai_hint", "hidden", "column_meta"}
+_PROTECTED_METRIC_KEYS = {"sql", "description", "ai_hint", "name", "model"}
+_PROTECTED_AGGREGATION_KEYS = _PROTECTED_METRIC_KEYS | {"type", "percentile"}
+_PROTECTED_JOIN_KEYS = {"join", "sql_on", "alias"}
+# Dataset extension keys that map to Ossie vocabulary or are handled separately.
+_PROTECTED_MODEL_KEYS = {"joins", "metrics", "primary_key", "ai_hint", "name", "type", "sql_from"}
+# Order of the top-level keys in a Lightdash model file. Any other key (model
+# meta from the extension) follows in source order.
+_MODEL_KEY_ORDER = ("type", "name", "label", "description", "sql_from", "primary_key", "ai_hint")
+_DIMENSION_KEY_ORDER = ("name", "type", "label", "description", "sql", "hidden")
+
+# The joins a dataset declares, keyed by the joined dataset. The value is the
+# name Lightdash SQL uses to reference it: the joined model, or its alias. When
+# a dataset is joined more than once, the first join wins.
+JoinReferences = Dict[str, str]
+
+
+def _lightdash_extension_data(element: Any, issues: List[ConverterIssue]) -> Dict[str, Any]:
+ """Gets the ``LIGHTDASH`` extension data of an Ossie element, or an empty mapping."""
+ data: Dict[str, Any] = {}
+ for extension in element.custom_extensions or []:
+ # The vendor name is LIGHTDASH. Documents written before it was
+ # registered used the lowercase name.
+ if extension.vendor_name.upper() == LIGHTDASH_VENDOR_NAME:
+ try:
+ data.update(json.loads(extension.data))
+ except (TypeError, ValueError):
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.EXTENSION_DATA_INVALID,
+ element_name=getattr(element, "name", "<unnamed>"),
+ )
+ )
+ else:
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.FOREIGN_EXTENSION_IGNORED,
+ element_name=getattr(element, "name", "<unnamed>"),
+ )
+ )
+ return data
+
+
+def _ai_hint(ai_context: Any) -> Any:
+ """Converts an Ossie `ai_context` to a Lightdash `ai_hint`. One line stays
+ a string, a multi-line instruction becomes a list, and the synonyms and
+ examples of the structured form become extra hints."""
+ if ai_context is None:
+ return None
+ if isinstance(ai_context, str):
+ hints = ai_context.split("\n")
+ else:
+ hints = (ai_context.instructions or "").split("\n")
+ if ai_context.synonyms:
+ hints.append("Also known as: " + ", ".join(ai_context.synonyms))
+ if ai_context.examples:
+ hints.append("Example questions: " + "; ".join(ai_context.examples))
+ hints = [hint for hint in hints if hint]
+ if not hints:
+ return None
+ return hints[0] if len(hints) == 1 else hints
+
+
+def _ordered(entries: Dict[str, Any], order: Tuple[str, ...]) -> Dict[str, Any]:
+ """Reorders ``entries`` so the keys in ``order`` come first. The rest keep their order."""
+ return {
+ **{key: entries[key] for key in order if key in entries},
+ **{key: value for key, value in entries.items() if key not in order},
+ }
+
+
+def _to_lightdash_model(
+ dataset: OssieDataset, model: Dict[str, Any], issues: List[ConverterIssue]
+) -> Dict[str, Any]:
+ """Reshapes a dbt model with Lightdash meta into a Lightdash model file."""
+ meta = dict(model.get("meta") or {})
+ out: Dict[str, Any] = {"type": "model", "name": model["name"]}
+ if model.get("description"):
+ out["description"] = model["description"]
+ out["sql_from"] = dataset.source
+ joins = meta.pop("joins", None)
+ model_metrics = meta.pop("metrics", None)
+ out.update(meta)
+ if joins:
+ out["joins"] = joins
+ if model_metrics:
+ out["metrics"] = model_metrics
+
+ dimensions: List[Dict[str, Any]] = []
+ for column in model.get("columns") or []:
+ column_meta = column.get("meta") or {}
+ dimension = dict(column_meta.get("dimension") or {})
+ dimension["name"] = column["name"]
+ if column.get("description") and "description" not in dimension:
+ dimension["description"] = column["description"]
+ if not dimension.get("type"):
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.DIMENSION_TYPE_DEFAULTED,
+ element_name=f"{model['name']}.{column['name']}",
+ )
+ )
+ dimension["type"] = "string"
+ if not dimension.get("sql"):
+ dimension["sql"] = f"${{TABLE}}.{column['name']}"
+ if column_meta.get("metrics"):
+ dimension["metrics"] = column_meta["metrics"]
+ if column_meta.get("additional_dimensions"):
+ dimension["additional_dimensions"] = column_meta["additional_dimensions"]
+ if any(key not in ("dimension", "metrics", "additional_dimensions") for key in column_meta):
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.COLUMN_META_NOT_REPRESENTABLE,
+ element_name=f"{model['name']}.{column['name']}",
+ )
+ )
+ dimensions.append(_ordered(dimension, _DIMENSION_KEY_ORDER))
+ out["dimensions"] = dimensions
+ return _ordered(out, _MODEL_KEY_ORDER)
+
+
+def _nest_meta_under_config(node: Dict[str, Any]) -> None:
+ """Moves a node's ``meta`` under ``config``, the placement dbt 1.10 and later use."""
+ meta = node.pop("meta", None)
+ if meta:
+ node["config"] = {"meta": meta}
+
+
+_MODEL_NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
+_SOURCE_IDENTIFIER = r'(?:[A-Za-z_][A-Za-z0-9_$]*|"(?:""|[^"])+"|`(?:``|[^`])+`|\[(?:\]\]|[^\]])+\])'
+_SOURCE_PATH_RE = re.compile(rf"{_SOURCE_IDENTIFIER}(?:\s*\.\s*{_SOURCE_IDENTIFIER})*")
+
+
+def _model_name_for(dataset: OssieDataset) -> str:
+ """Derives the model name: a simple source's table name, otherwise the dataset name.
+
+ Raises:
+ ValueError: If neither forms a valid model name.
+ """
+ source = dataset.source.strip()
+ # BigQuery can quote the whole project.dataset.table path with backticks.
+ if re.fullmatch(r"`[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+`", source):
+ source = source[1:-1]
+ candidate = source.rsplit(".", 1)[-1]
+ elif _SOURCE_PATH_RE.fullmatch(source):
+ candidate = re.findall(_SOURCE_IDENTIFIER, source)[-1]
+ if candidate[0] in ('"', '`', '['):
+ candidate = candidate[1:-1]
+ else:
+ candidate = dataset.name
+ if not _MODEL_NAME_RE.fullmatch(candidate):
+ candidate = dataset.name
+ if not _MODEL_NAME_RE.fullmatch(candidate):
+ raise ValueError(
+ f"Dataset {dataset.name!r} has no safe Lightdash model name; use a dataset "
+ "name starting with a letter or underscore, followed by letters, digits or underscores."
+ )
+ return candidate
+
+
+class OssieToLightdashConverter:
+ """Converts an ``OssieDocument`` into Lightdash definitions.
+
+ ``dialect`` is the expression dialect to prefer, the project's warehouse.
+ ``OSSIE_SQL_2026`` and ``ANSI_SQL`` are the fallbacks. For an expression
+ that offers none of these, the converter takes the first dialect offered
+ and records a ``DIALECT_UNAVAILABLE`` issue.
+ """
+
+ def __init__(
+ self,
+ dialect: OssieDialect = OssieDialect.ANSI_SQL,
+ *,
+ meta_under_config: bool = False,
+ ) -> None:
+ self._dialect = dialect
+ self._meta_under_config = meta_under_config
+
+ def convert(self, document: OssieDocument) -> ConverterResult[Dict[str, Any]]:
+ """Converts the document into a dbt ``schema.yml`` dictionary with Lightdash ``meta``."""
+ issues: List[ConverterIssue] = []
+ models = [model for _, model in self._convert_semantic_model(document, issues)]
+ if self._meta_under_config:
+ for model in models:
+ _nest_meta_under_config(model)
+ for column in model.get("columns") or []:
+ _nest_meta_under_config(column)
+ return ConverterResult(output={"version": 2, "models": models}, issues=issues)
+
+ def convert_models(self, document: OssieDocument) -> ConverterResult[List[Dict[str, Any]]]:
+ """Converts the document into Lightdash model files, one dictionary per dataset.
+
+ The model-file format has a place for everything the dbt format keeps
+ in the extension: ``sql_from`` is the dataset's ``source`` verbatim,
+ model meta becomes top-level keys, and every dimension has its own
+ ``type`` and ``sql``.
+ """
+ issues: List[ConverterIssue] = []
+ models: List[Dict[str, Any]] = []
+ for dataset, model in self._convert_semantic_model(document, issues):
+ models.append(_to_lightdash_model(dataset, model, issues))
+ return ConverterResult(output=models, issues=issues)
+
+ def _pick_expression(
+ self, expression: OssieExpression, element_name: str, issues: List[ConverterIssue]
+ ) -> str:
+ by_dialect = {
+ dialect_expression.dialect: dialect_expression.expression
+ for dialect_expression in expression.dialects
+ }
+ for dialect in (self._dialect, OssieDialect.OSSIE_SQL_2026, OssieDialect.ANSI_SQL):
+ if dialect in by_dialect:
+ return by_dialect[dialect]
+ if not expression.dialects:
+ return ""
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.DIALECT_UNAVAILABLE,
+ element_name=element_name,
+ )
+ )
+ return expression.dialects[0].expression
+
+ def _convert_semantic_model(
+ self, semantic_model: OssieSemanticModel, issues: List[ConverterIssue]
+ ) -> List[Tuple[OssieDataset, Dict[str, Any]]]:
+ datasets = semantic_model.datasets or []
+ dataset_names = {dataset.name for dataset in datasets}
+ model_name_by_dataset: Dict[str, str] = {}
+ dataset_by_model_name: Dict[str, str] = {}
+ for dataset in datasets:
+ name = _model_name_for(dataset)
+ # Also reject names that differ only in case, for case-insensitive
+ # file systems.
+ previous = dataset_by_model_name.get(name.casefold())
+ if previous is not None:
+ raise ValueError(
+ f"Datasets {previous!r} and {dataset.name!r} both export to "
+ f"Lightdash model {name!r}; model names must be unique (ignoring case)."
+ )
+ if dataset.name in model_name_by_dataset:
+ raise ValueError(f"Duplicate dataset name: {dataset.name!r}")
+ dataset_by_model_name[name.casefold()] = dataset.name
+ model_name_by_dataset[dataset.name] = name
+
+ # Joins are planned first, because field and metric expressions can
+ # reference other datasets only through the joins their own dataset
+ # declares.
+ joins_by_dataset, references_by_dataset = self._plan_joins(
+ semantic_model, model_name_by_dataset, issues
+ )
+
+ models_by_dataset: Dict[str, Dict[str, Any]] = {}
+ columns_by_dataset: Dict[str, Dict[str, Dict[str, Any]]] = {}
+ stash_by_dataset: Dict[str, Dict[str, Any]] = {}
+ for dataset in datasets:
+ stash = _lightdash_extension_data(dataset, issues)
+ stash_by_dataset[dataset.name] = stash
+ # A join kept in the extension (chained, expression, extra
+ # conditions) is restored verbatim. It replaces the generated join
+ # to the same target and alias, and its target becomes
+ # referenceable.
+ joins = joins_by_dataset.setdefault(dataset.name, [])
+ references = references_by_dataset.setdefault(dataset.name, {})
+ for stashed_join in stash.get("joins") or []:
+ if not isinstance(stashed_join, dict) or not isinstance(stashed_join.get("join"), str):
+ continue
+ key = (stashed_join.get("join"), stashed_join.get("alias"))
+ for index, join in enumerate(joins):
+ if (join.get("join"), join.get("alias")) == key:
+ joins[index] = stashed_join
+ break
+ else:
+ joins.append(stashed_join)
+ # `references` is keyed by Ossie dataset name, the way field
+ # and metric expressions name a dataset. The join names the
+ # Lightdash model, which can differ: dataset `customer_ds`
+ # over source `public.customer` is model `customer`. A join
+ # to a model outside the document is keyed by the model name,
+ # so an expression that names it still resolves.
+ joined_model = stashed_join["join"]
+ joined_dataset = dataset_by_model_name.get(joined_model.casefold(), joined_model)
+ references.setdefault(
+ joined_dataset, stashed_join.get("alias") or joined_model
+ )
+ if not joins:
+ del joins_by_dataset[dataset.name]
+
+ for dataset in datasets:
+ model, columns = self._convert_dataset(
+ dataset,
+ model_name_by_dataset[dataset.name],
+ dataset_names,
+ references_by_dataset.get(dataset.name, {}),
+ issues,
+ )
+ meta = model.setdefault("meta", {})
+ meta.update(
+ {
+ key: value
+ for key, value in stash_by_dataset[dataset.name].items()
+ if key not in _PROTECTED_MODEL_KEYS
+ }
+ )
+ if not meta:
+ del model["meta"]
+ models_by_dataset[dataset.name] = model
+ columns_by_dataset[dataset.name] = columns
+
+ for metric in semantic_model.metrics or []:
+ self._convert_metric(
+ metric,
+ [dataset.name for dataset in datasets],
+ models_by_dataset,
+ columns_by_dataset,
+ references_by_dataset,
+ issues,
+ )
+
+ for dataset_name, joins in joins_by_dataset.items():
+ models_by_dataset[dataset_name].setdefault("meta", {})["joins"] = joins
+
+ return [(dataset, models_by_dataset[dataset.name]) for dataset in datasets]
+
+ def _plan_joins(
+ self,
+ semantic_model: OssieSemanticModel,
+ model_name_by_dataset: Dict[str, str],
+ issues: List[ConverterIssue],
+ ) -> Tuple[Dict[str, List[Dict[str, Any]]], Dict[str, JoinReferences]]:
+ joins_by_dataset: Dict[str, List[Dict[str, Any]]] = {}
+ references_by_dataset: Dict[str, JoinReferences] = {}
+ joined_pairs: Set[Tuple[str, str]] = set()
+ for relationship in semantic_model.relationships or []:
+ from_model_name = model_name_by_dataset.get(relationship.from_dataset)
+ to_model_name = model_name_by_dataset.get(relationship.to)
+ if from_model_name is None or to_model_name is None:
+ continue
+ if len(relationship.from_columns) != len(relationship.to_columns):
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.RELATIONSHIP_COLUMNS_MISMATCHED,
+ element_name=relationship.name,
+ )
+ )
+ continue
+ extension_data = _lightdash_extension_data(relationship, issues)
+ # Lightdash rejects a second join to the same table without an
+ # alias. An alias from the extension is restored. Otherwise the
+ # relationship name is the alias for every repeat of a dataset
+ # pair.
+ pair = (relationship.from_dataset, relationship.to)
+ alias = extension_data.get("alias")
+ if alias is None and pair in joined_pairs:
+ alias = relationship.name
+ joined_pairs.add(pair)
+ join_reference = alias or to_model_name
+ sql_on = " AND ".join(
+ f"${{{from_model_name}.{from_column}}} = ${{{join_reference}.{to_column}}}"
+ for from_column, to_column in zip(
+ relationship.from_columns, relationship.to_columns
+ )
+ )
+ # An Ossie relationship always runs from the many side to the one
+ # side. A Lightdash `relationship` from the extension overrides it
+ # below.
+ join: Dict[str, Any] = {"join": to_model_name}
+ if alias:
+ join["alias"] = alias
+ join["sql_on"] = sql_on
+ join["relationship"] = "many-to-one"
+ join.update(
+ {
+ key: value
+ for key, value in extension_data.items()
+ if key not in _PROTECTED_JOIN_KEYS
+ }
+ )
+ joins_by_dataset.setdefault(relationship.from_dataset, []).append(join)
+ references_by_dataset.setdefault(relationship.from_dataset, {}).setdefault(
+ relationship.to, join_reference
+ )
+ return joins_by_dataset, references_by_dataset
+
+ def _convert_dataset(
+ self,
+ dataset: OssieDataset,
+ model_name: str,
+ dataset_names: Set[str],
+ references: JoinReferences,
+ issues: List[ConverterIssue],
+ ) -> tuple:
+ columns_by_name: Dict[str, Dict[str, Any]] = {}
+ for field in dataset.fields or []:
+ column: Dict[str, Any] = {"name": field.name}
+ if field.description:
+ column["description"] = field.description
+
+ dimension: Dict[str, Any] = {}
+ if field.dimension is None:
+ # Every Lightdash column is a dimension. A measure-only Ossie
+ # field becomes a hidden one.
+ dimension["hidden"] = True
+ if field.label:
+ dimension["label"] = field.label
+ ai_hint = _ai_hint(field.ai_context)
+ if ai_hint is not None:
+ dimension["ai_hint"] = ai_hint
+ lightdash_type = datatype_to_lightdash_type(field.datatype)
+ if lightdash_type is not None:
+ dimension["type"] = lightdash_type
+ elif field.dimension is not None and field.dimension.is_time:
+ # There is no datatype to translate, and the field is declared
+ # as a time axis. `date` is the closest Lightdash type.
+ dimension["type"] = "date"
+ if (
+ field.dimension is not None
+ and field.dimension.is_time
+ and not is_temporal(field.datatype)
+ and field.datatype is not None
+ ):
+ # A non-temporal datatype with a time-axis role (for example,
+ # a year stored as Integer) has no Lightdash equivalent.
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.TIME_ROLE_NOT_REPRESENTABLE,
+ element_name=field.name,
+ )
+ )
+ if (
+ field.dimension is not None
+ and field.dimension.is_time is False
+ and is_temporal(field.datatype)
+ ):
+ # The field is explicitly removed from the time axis.
+ # Lightdash's marker for that is `time_intervals: OFF`.
+ dimension["time_intervals"] = "OFF"
+ expression = self._pick_expression(field.expression, field.name, issues)
+ if expression and expression != field.name:
+ unjoined = referenced_datasets(expression, dataset_names) - {
+ dataset.name,
+ *references,
+ }
+ if unjoined:
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.FIELD_REFERENCE_UNJOINED,
+ element_name=field.name,
+ )
+ )
+ dimension["sql"] = ossie_sql_to_lightdash(
+ expression, dataset.name, references
+ )
+ field_data = _lightdash_extension_data(field, issues)
+ dimension.update(
+ {
+ key: value
+ for key, value in field_data.items()
+ if key not in _PROTECTED_DIMENSION_KEYS
+ }
+ )
+ # A dimension with no attributes is Lightdash's default: no meta.
+ if dimension:
+ column["meta"] = {"dimension": dimension}
+ column_meta = field_data.get("column_meta")
+ if isinstance(column_meta, dict) and column_meta:
+ column.setdefault("meta", {}).update(
+ {
+ key: value
+ for key, value in column_meta.items()
+ if key not in ("dimension", "metrics")
+ }
+ )
+ columns_by_name[field.name] = column
+
+ model: Dict[str, Any] = {"name": model_name}
+ if dataset.description:
+ model["description"] = dataset.description
+ meta: Dict[str, Any] = {}
+ if dataset.primary_key:
+ keys = list(dataset.primary_key)
+ meta["primary_key"] = keys[0] if len(keys) == 1 else keys
+ ai_hint = _ai_hint(dataset.ai_context)
+ if ai_hint is not None:
+ meta["ai_hint"] = ai_hint
+ if meta:
+ model["meta"] = meta
+ model["columns"] = list(columns_by_name.values())
+ return model, columns_by_name
+
+ def _convert_metric(
+ self,
+ metric: OssieMetric,
+ dataset_names: List[str],
+ models_by_dataset: Dict[str, Dict[str, Any]],
+ columns_by_dataset: Dict[str, Dict[str, Dict[str, Any]]],
+ references_by_dataset: Dict[str, JoinReferences],
+ issues: List[ConverterIssue],
+ ) -> None:
+ expression = self._pick_expression(metric.expression, metric.name, issues)
+ extension_data = _lightdash_extension_data(metric, issues)
+
+ target_dataset = self._resolve_target_dataset(
+ expression, dataset_names, references_by_dataset
+ )
+ # An expression that names no dataset can still be placed when the
+ # extension records which model it came from.
+ stashed_model = extension_data.get("model")
+ if target_dataset is None and stashed_model in dataset_names:
+ if not referenced_datasets(expression, set(dataset_names)):
+ target_dataset = stashed_model
+ if target_dataset is None:
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.CROSS_DATASET_METRIC_DROPPED,
+ element_name=metric.name,
+ )
+ )
+ return
+ references = references_by_dataset.get(target_dataset, {})
+
+ definition: Dict[str, Any] = {}
+ if metric.description:
+ definition["description"] = metric.description
+ ai_hint = _ai_hint(metric.ai_context)
+ if ai_hint is not None:
+ definition["ai_hint"] = ai_hint
+
+ # A single aggregation becomes a typed metric: on the column when the
+ # operand is one of the dataset's columns, otherwise on the model with
+ # the operand as `sql`. Any other expression becomes a `number` metric
+ # with raw SQL.
+ target_column: Optional[str] = None
+ parsed = parse_aggregation(expression)
+ if parsed is not None:
+ definition["type"] = parsed.lightdash_type
+ inner = parsed.inner
+ if (
+ is_column_reference(inner)
+ and qualifier_of(inner) in (None, target_dataset)
+ and strip_qualifier(inner) in columns_by_dataset[target_dataset]
+ ):
+ target_column = strip_qualifier(inner)
+ else:
+ definition["sql"] = ossie_sql_to_lightdash(inner, target_dataset, references)
+ if parsed.percentile is not None:
+ definition["percentile"] = parsed.percentile
+ protected = _PROTECTED_AGGREGATION_KEYS
+ else:
+ definition["type"] = extension_data.get("type", "number")
+ definition["sql"] = ossie_sql_to_lightdash(expression, target_dataset, references)
+ protected = _PROTECTED_METRIC_KEYS
+
+ definition.update(
+ {
+ key: value
+ for key, value in extension_data.items()
+ if key not in protected
+ }
+ )
+
+ # The Lightdash name is the one from the extension, else the Ossie
+ # name with the `<model>_` field-ID prefix removed, else the Ossie
+ # name as is.
+ lightdash_name = extension_data.get("name")
+ if not isinstance(lightdash_name, str) or not lightdash_name:
+ prefix = f"{target_dataset}_"
+ lightdash_name = (
+ metric.name[len(prefix):]
+ if metric.name.startswith(prefix) and len(metric.name) > len(prefix)
+ else metric.name
+ )
+
+ if target_column is not None:
Review Comment:
`metrics[lightdash_name] = definition` has no collision check. Two Ossie metrics can resolve to the same Lightdash name.
For example, on dataset `orders`, `revenue` and `orders_revenue` both become `revenue` once the `orders_` prefix is stripped.
A column level metric and a model level metric can collide the same way. The first one is overwritten and no `ConverterIssue` is raised, so the metric disappears from the output.
I suggest to check `lightdash_name in metrics` before assigning. On a collision, either keep the unstripped name or record a `ConverterIssue` with a specific code (for example `METRIC_NAME_COLLISION`) naming both source metrics.
We could add a test with the `revenue` / `orders_revenue` pair.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ossie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add lightdash converter [ossie-converters]
Posted by "jbonofre (via GitHub)" <gi...@apache.org>.
jbonofre commented on code in PR #7:
URL: https://github.com/apache/ossie-converters/pull/7#discussion_r4342397802
##########
lightdash/src/ossie_lightdash/catalog.py:
##########
@@ -0,0 +1,113 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+"""Column types from a dbt ``catalog.json``.
+
+``dbt docs generate`` records the warehouse's real type for every column of
+every model. Lightdash learns most dimension types from the warehouse rather
+than from YAML, so a Lightdash project usually has few authored types; the
+catalog fills the gaps with the physical type reduced to Ossie's logical
+vocabulary.
+"""
+
+import json
+import re
+from pathlib import Path
+from typing import Dict, Optional
+
+from ossie import OssieDataType
+
+# Column types keyed by model name, then by lower-cased column name.
+Catalog = Dict[str, Dict[str, str]]
+
+_TYPE_RE = re.compile(r"^\s*([A-Za-z_][A-Za-z_0-9 ]*?)\s*(?:\(\s*(\d+)\s*(?:,\s*(\d+))?\s*\))?\s*$")
+
+_EXACT = {
+ "INT": OssieDataType.INTEGER,
+ "INTEGER": OssieDataType.INTEGER,
+ "INT64": OssieDataType.INTEGER,
+ "BIGINT": OssieDataType.INTEGER,
+ "SMALLINT": OssieDataType.INTEGER,
+ "TINYINT": OssieDataType.INTEGER,
+ "INT2": OssieDataType.INTEGER,
+ "INT4": OssieDataType.INTEGER,
+ "INT8": OssieDataType.INTEGER,
+ "FLOAT": OssieDataType.FLOAT,
+ "FLOAT4": OssieDataType.FLOAT,
+ "FLOAT8": OssieDataType.FLOAT,
+ "FLOAT64": OssieDataType.FLOAT,
+ "DOUBLE": OssieDataType.FLOAT,
+ "DOUBLE PRECISION": OssieDataType.FLOAT,
+ "REAL": OssieDataType.FLOAT,
+ "STRING": OssieDataType.STRING,
+ "VARCHAR": OssieDataType.STRING,
+ "NVARCHAR": OssieDataType.STRING,
+ "CHAR": OssieDataType.STRING,
+ "CHARACTER": OssieDataType.STRING,
+ "CHARACTER VARYING": OssieDataType.STRING,
+ "TEXT": OssieDataType.STRING,
+ "BOOL": OssieDataType.BOOLEAN,
+ "BOOLEAN": OssieDataType.BOOLEAN,
+ "DATE": OssieDataType.DATE,
+ "DATETIME": OssieDataType.DATE_TIME,
+ "TIMESTAMP": OssieDataType.DATE_TIME,
+ "TIMESTAMP_NTZ": OssieDataType.DATE_TIME,
+ "TIMESTAMP WITHOUT TIME ZONE": OssieDataType.DATE_TIME,
+ "TIMESTAMPTZ": OssieDataType.DATE_TIME_TZ,
+ "TIMESTAMP_TZ": OssieDataType.DATE_TIME_TZ,
+ "TIMESTAMP_LTZ": OssieDataType.DATE_TIME_TZ,
+ "TIMESTAMP WITH TIME ZONE": OssieDataType.DATE_TIME_TZ,
+ "TIME": OssieDataType.TIME,
+}
+# Exact-decimal families: integral when the scale is 0 (or, for NUMBER, when
+# Snowflake's default NUMBER(38,0) is spelled without arguments).
+_DECIMAL_FAMILY = {"NUMERIC", "BIGNUMERIC", "DECIMAL", "NUMBER"}
+
+
+def warehouse_type_to_datatype(warehouse_type: str) -> Optional[OssieDataType]:
+ """Reduce a physical column type to an Ossie datatype, or None when the
+ type is outside the portable vocabulary (arrays, structs, JSON, ...)."""
+ match = _TYPE_RE.match(warehouse_type or "")
+ if match is None:
+ return None
+ base = " ".join(match.group(1).upper().split())
+ scale = match.group(3)
+ if base in _DECIMAL_FAMILY:
+ if scale is not None:
+ return OssieDataType.INTEGER if int(scale) == 0 else OssieDataType.DECIMAL
+ return OssieDataType.INTEGER if base == "NUMBER" else OssieDataType.DECIMAL
+ return _EXACT.get(base)
+
+
+def load_catalog(path: Path) -> Catalog:
+ """Read a dbt ``catalog.json`` into ``{model: {column: type}}``.
+
+ Models and seeds are keyed by their dbt name (the last segment of the
+ node's unique id); column names are lower-cased because warehouses differ
+ in how they report case.
+ """
+ document = json.loads(Path(path).read_text(encoding="utf-8"))
+ catalog: Catalog = {}
+ for unique_id, node in (document.get("nodes") or {}).items():
+ kind = unique_id.split(".", 1)[0]
+ if kind not in ("model", "seed"):
+ continue
+ name = unique_id.rsplit(".", 1)[-1]
Review Comment:
`name = unique_id.rsplit(".", 1)[-1]` takes the last dotted segment of the `unique_id`. For a versioned model (`model.pkg.orders.v2`) that gives `v2`, so `orders` never matches and you get a spurious `CATALOG_MODEL_MISSING`.
Two packages with the same model name (`model.a.users`, `model.b.users`) also overwrite each other's column types.
Please key on `node["name"]` (or `node["metadata"]["name"]`) instead, and add a test with a versioned model and a cross-package name clash.
##########
lightdash/src/ossie_lightdash/cli.py:
##########
@@ -0,0 +1,320 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+
+"""Command line interface for the Ossie <> Lightdash converter."""
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import List, Optional
+
+import yaml
+from pydantic import ValidationError
+
+from ossie import OssieDialect, OssieDocument
+from ossie_lightdash.catalog import load_catalog
+from ossie_lightdash.converter_issues import ISSUE_EXPLANATIONS, ConversionError
+from ossie_lightdash.dbt_project import load_schema_with_skips
+from ossie_lightdash.lightdash_to_ossie import LightdashToOssieConverter
+from ossie_lightdash.ossie_to_lightdash import OssieToLightdashConverter
+
+
+def _read_document(path: Path) -> OssieDocument:
+ """The Ossie document at ``path``, or a ``ConversionError`` that says
+ where it stops being one (the first schema violation, by location)."""
+ text = path.read_text(encoding="utf-8")
+ try:
+ if path.suffix == ".json":
+ return OssieDocument.model_validate_json(text)
+ return OssieDocument.model_validate(yaml.safe_load(text))
+ except yaml.YAMLError as exc:
+ raise ConversionError(f"{path}: not valid YAML: {exc}") from exc
+ except ValidationError as exc:
+ first = exc.errors()[0]
+ location = ".".join(str(part) for part in first["loc"]) or "document"
+ count = exc.error_count()
+ more = f" (and {count - 1} more)" if count > 1 else ""
+ raise ConversionError(
+ f"{path} is not a valid Ossie document: {location}: {first['msg']}{more}"
+ ) from exc
+
+
+# Ossie dialects that name a Lightdash warehouse type.
+_WAREHOUSE_BY_DIALECT = {
+ OssieDialect.BIGQUERY: "bigquery",
+ OssieDialect.SNOWFLAKE: "snowflake",
+ OssieDialect.DATABRICKS: "databricks",
+}
+
+
+_PLACEHOLDER = "CHANGE_ME"
+
+
+def _existing_warehouse_type(config: Path) -> Optional[str]:
+ """warehouse.type of an existing config; None when there is no config or
+ no readable type in it."""
+ if not config.exists():
+ return None
+ try:
+ document = yaml.safe_load(config.read_text(encoding="utf-8")) or {}
+ except yaml.YAMLError:
+ return None
+ warehouse = document.get("warehouse") if isinstance(document, dict) else None
+ if isinstance(warehouse, dict) and isinstance(warehouse.get("type"), str):
+ return warehouse["type"]
+ return None
+
+
+def _write_lightdash_project(
+ models, output: Path, *, name: str, warehouse: Optional[str]
+) -> None:
+ """Write one model file per dataset plus a starter lightdash.config.yml.
+
+ Files go to ``<output>/lightdash/models/<model>.yml``, the layout
+ ``lightdash deploy`` looks for; an existing config is left alone.
+ """
+ models_dir = output / "lightdash" / "models"
+ models_dir.mkdir(parents=True, exist_ok=True)
+ for model in models:
+ (models_dir / f"{model['name']}.yml").write_text(
+ yaml.safe_dump(model, sort_keys=False, allow_unicode=True), encoding="utf-8"
+ )
+ # The config is rewritten while it still carries the placeholder and kept
+ # once a real warehouse type is in it, whether we or the user put it there.
+ config = output / "lightdash.config.yml"
+ existing = _existing_warehouse_type(config)
+ if existing is not None and existing != _PLACEHOLDER:
+ print(f"{config}: kept (warehouse.type is {existing}).", file=sys.stderr)
+ return
+ config.write_text(
+ yaml.safe_dump(
+ {
+ "name": name,
+ "version": "1.0",
+ "warehouse": {"type": warehouse or _PLACEHOLDER},
+ },
+ sort_keys=False,
+ ),
+ encoding="utf-8",
+ )
+ if warehouse is None:
+ print(
+ f"{config}: warehouse.type is {_PLACEHOLDER}; pass --warehouse, or a "
+ "--dialect Lightdash knows (BIGQUERY, SNOWFLAKE, DATABRICKS), and "
+ "re-run. lightdash compile will refuse the placeholder.",
+ file=sys.stderr,
+ )
+
+
+def _add_io_arguments(parser: argparse.ArgumentParser, input_help: str, output_help: str) -> None:
+ """``-i/--input`` and ``-o/--output`` like the other converters; the two
+ positionals are still accepted."""
+ parser.add_argument("-v", "--verbose", action="store_true", help="list every affected element, not just the first few per issue type")
+ parser.add_argument("-i", "--input", dest="input_flag", metavar="INPUT", type=Path, help=input_help)
+ parser.add_argument("-o", "--output", dest="output_flag", metavar="OUTPUT", type=Path, help=output_help)
+ parser.add_argument("input", nargs="?", type=Path, help=argparse.SUPPRESS)
+ parser.add_argument("output", nargs="?", type=Path, help=argparse.SUPPRESS)
+
+
+def _resolve_io(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
+ args.input = args.input_flag or args.input
+ args.output = args.output_flag or args.output
+ if args.input is None or args.output is None:
+ parser.error("both --input and --output are required")
+ if not args.input.exists():
+ parser.error(f"input not found: {args.input}")
+
+
+_SHOWN_PER_TYPE = 8
+_WRAP = 88
+
+
+def _wrap(names, indent: str = " ") -> str:
+ lines, line = [], indent
+ for name in names:
+ piece = name + ", "
+ if len(line) + len(piece) > _WRAP and line.strip():
+ lines.append(line.rstrip(", "))
+ line = indent
+ line += piece
+ lines.append(line.rstrip(", "))
+ return "\n".join(lines)
+
+
+def _print_issues(issues, verbose: bool = False) -> None:
+ """A short block per issue type: header with the count, the explanation,
+ then the affected elements (the first few, or all of them with
+ ``verbose``)."""
+ by_type: "dict" = {}
+ for issue in issues:
+ by_type.setdefault(issue.issue_type, []).append(issue.element_name)
+ for issue_type, elements in by_type.items():
+ unique = list(dict.fromkeys(elements))
+ noun = "element" if len(unique) == 1 else "elements"
+ print(f"{issue_type.value} ({len(unique)} {noun})", file=sys.stderr)
+ print(f" {ISSUE_EXPLANATIONS.get(issue_type, '')}", file=sys.stderr)
+ shown = unique if verbose else unique[:_SHOWN_PER_TYPE]
+ print(_wrap(shown), file=sys.stderr)
+ if len(unique) > len(shown):
+ print(f" ... and {len(unique) - len(shown)} more", file=sys.stderr)
+ print(file=sys.stderr)
+ if issues:
+ hint = "" if verbose else " Pass --verbose to list every element."
+ print(f"{len(issues)} issue(s); everything else converted cleanly.{hint}", file=sys.stderr)
+
+
+def main(argv: Optional[List[str]] = None) -> int:
+ parser = argparse.ArgumentParser(prog="ossie-lightdash")
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ export_parser = subparsers.add_parser(
+ "export",
+ help="Ossie document (.json/.yaml) -> Lightdash model files, or a dbt schema.yml",
+ )
+ _add_io_arguments(
+ export_parser,
+ "Ossie document (.json or .yaml)",
+ "project directory (lightdash-yml) or schema file (dbt-meta)",
+ )
+ export_parser.add_argument(
+ "--format",
+ choices=["lightdash-yml", "dbt-meta"],
+ default="lightdash-yml",
+ help="lightdash-yml: Lightdash's dbt-free model files, deployable as they are "
+ "(default); dbt-meta: one dbt schema.yml with Lightdash meta blocks",
+ )
+ export_parser.add_argument(
+ "--warehouse",
+ default=None,
+ help="warehouse.type for the generated lightdash.config.yml "
+ "(default: derived from --dialect when possible)",
+ )
+ export_parser.add_argument(
+ "--dialect",
+ choices=[dialect.name for dialect in OssieDialect],
+ default=OssieDialect.ANSI_SQL.name,
+ help="preferred expression dialect (falls back to OSSIE_SQL_2026, then ANSI_SQL)",
+ )
+ export_parser.add_argument(
+ "--meta-under-config",
+ action="store_true",
+ help="write Lightdash meta under `config:` (dbt 1.10+) instead of top-level `meta:`",
+ )
+
+ import_parser = subparsers.add_parser(
+ "import",
+ help="Lightdash dbt schema.yml, or a dbt project directory -> Ossie document (.json/.yaml)",
+ )
+ _add_io_arguments(
+ import_parser,
+ "a dbt schema file, or a directory walked for models: and seeds:",
+ "Ossie document to write (.json or .yaml)",
+ )
+ import_parser.add_argument("--database", default=None)
+ import_parser.add_argument("--schema", default=None)
+ import_parser.add_argument(
+ "--semantic-model-name", default="lightdash_semantic_model"
+ )
+ import_parser.add_argument(
+ "--dialect",
+ choices=[dialect.name for dialect in OssieDialect],
+ default=OssieDialect.ANSI_SQL.name,
+ help="dialect the Lightdash SQL is written in (the project's warehouse)",
+ )
+ import_parser.add_argument(
+ "--catalog",
+ type=Path,
+ default=None,
+ help="dbt target/catalog.json (from `dbt docs generate`): warehouse column "
+ "types fill in datatypes for columns without an authored type",
+ )
+
+ args = parser.parse_args(argv)
+ _resolve_io(export_parser if args.command == "export" else import_parser, args)
+
+ if args.command == "export":
+ dialect = OssieDialect[args.dialect]
+ try:
+ document = _read_document(args.input)
+ converter = OssieToLightdashConverter(dialect, meta_under_config=args.meta_under_config)
+ result = (
+ converter.convert_models(document)
+ if args.format == "lightdash-yml"
+ else converter.convert(document)
+ )
+ except ValueError as exc:
+ export_parser.error(str(exc))
+ if args.format == "lightdash-yml":
+ _write_lightdash_project(
+ result.output,
+ args.output,
+ name=document.name,
+ warehouse=args.warehouse or _WAREHOUSE_BY_DIALECT.get(dialect),
+ )
+ summary = (
+ f"Wrote {len(result.output)} model file(s) to {args.output / 'lightdash' / 'models'}"
+ f" and {args.output / 'lightdash.config.yml'}; run `lightdash compile` there."
+ )
+ else:
+ args.output.write_text(
+ yaml.safe_dump(result.output, sort_keys=False, allow_unicode=True),
+ encoding="utf-8",
+ )
+ summary = f"Wrote {len(result.output['models'])} model(s) to {args.output}."
+ else:
+ try:
+ schema_yml, skipped = load_schema_with_skips(args.input)
+ except yaml.YAMLError as exc:
+ import_parser.error(f"{args.input}: not valid YAML: {exc}")
+ for file in skipped:
+ print(f"Skipped {file}: not valid YAML (a template or Jinja-only file?)", file=sys.stderr)
+ try:
+ result = LightdashToOssieConverter(OssieDialect[args.dialect]).convert(
+ schema_yml,
+ database=args.database,
+ schema=args.schema,
+ semantic_model_name=args.semantic_model_name,
+ catalog=load_catalog(args.catalog) if args.catalog else None,
Review Comment:
`load_catalog(args.catalog)` runs inside a `try` that only catches `ConversionError`, and `load_catalog` calls `json.loads(Path(path).read_text())` directly.
A missing file, invalid JSON or a `nodes` of the wrong shape ends in a raw traceback instead of the `import_parser.error(...)` path.
Either wrap the call in `load_catalog` and raise `ConversionError`, or catch `OSError`, `ValueError` and `AttributeError` here.
##########
lightdash/src/ossie_lightdash/expression_utils.py:
##########
@@ -0,0 +1,305 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+"""Expression helpers shared by both conversion directions.
+
+Lightdash SQL snippets reference the current model as ``${TABLE}.column``,
+sibling fields as ``${column}`` or ``${metric}``, joined models as
+``${other_table.column}`` and project parameters or user attributes as
+``${lightdash.…}`` / ``${ld.…}``. Ossie expressions reference columns as
+``dataset.column``. These helpers translate between the two spellings and
+recognise the aggregation shapes that map onto Lightdash's typed metrics.
+"""
+
+import re
+from dataclasses import dataclass, field
+from typing import Callable, Dict, List, Optional
+
+import sqlglot
+from sqlglot import exp
+
+_SQLGLOT_DIALECTS = {
+ "BIGQUERY": "bigquery",
+ "SNOWFLAKE": "snowflake",
+ "DATABRICKS": "databricks",
+}
+
+_REFERENCE_RE = re.compile(r"\$\{([^}]+)\}")
+_NON_PORTABLE_REFERENCE_RE = re.compile(r"\$\{(?:lightdash|ld)\.[^}]*\}")
+# Liquid tags and bare `ld.parameters.x` / `ld.query.filters` / `ld.user.x`
+# references inside them are evaluated by Lightdash at query time.
+_NON_PORTABLE_SYNTAX_RE = re.compile(
+ r"\{%|\{\{|(?<![\w.])(?:lightdash|ld)\.(?:parameters|query|user)\."
+)
+_COLUMN_REFERENCE_RE = re.compile(r"^[A-Za-z_]\w*(?:\.\w+)?$")
+
+# Lightdash metric types that are encoded as an aggregation in the Ossie
+# expression. Anything else is exported as a `number` metric with raw SQL.
+_AGGREGATE_FUNCTIONS = {
+ "sum": "SUM",
+ "min": "MIN",
+ "max": "MAX",
+ "average": "AVG",
+ "median": "MEDIAN",
+ "count": "COUNT",
+}
+_DISTINCT_AGGREGATE_FUNCTIONS = {
+ "count_distinct": "COUNT",
+ "sum_distinct": "SUM",
+ "average_distinct": "AVG",
+}
+AGGREGATE_TYPES = frozenset(
+ {*_AGGREGATE_FUNCTIONS, *_DISTINCT_AGGREGATE_FUNCTIONS, "percentile"}
+)
+
+_FUNCTION_TO_TYPE = {
+ "SUM": "sum",
+ "MIN": "min",
+ "MAX": "max",
+ "AVG": "average",
+ "AVERAGE": "average",
+ "MEDIAN": "median",
+ "COUNT": "count",
+}
+_DISTINCT_FUNCTION_TO_TYPE = {
+ "COUNT": "count_distinct",
+ "SUM": "sum_distinct",
+ "AVG": "average_distinct",
+ "AVERAGE": "average_distinct",
+}
+
+_CALL_RE = re.compile(r"^\s*(?P<func>[A-Za-z_]+)\s*\((?P<body>.*)\)\s*$", re.DOTALL)
+_DISTINCT_RE = re.compile(r"^DISTINCT\s+(?P<inner>.+)$", re.IGNORECASE | re.DOTALL)
+_PERCENTILE_RE = re.compile(
+ r"^\s*PERCENTILE_CONT\s*\(\s*(?P<fraction>[0-9]*\.?[0-9]+)\s*\)\s*"
+ r"WITHIN\s+GROUP\s*\(\s*ORDER\s+BY\s+(?P<inner>.+?)\s*\)\s*$",
+ re.IGNORECASE | re.DOTALL,
+)
+
+
+@dataclass(frozen=True)
+class ParsedAggregation:
+ lightdash_type: str
+ inner: str
+ percentile: Optional[float] = None
+
+
+def _is_single_call_body(body: str) -> bool:
+ """True when the parentheses in ``body`` are balanced, i.e. the outer
+ parentheses around it belong to one function call."""
+ depth = 0
+ for char in body:
+ if char == "(":
+ depth += 1
+ elif char == ")":
+ depth -= 1
+ if depth < 0:
+ return False
+ return depth == 0
+
+
+def parse_aggregation(expression: str) -> Optional[ParsedAggregation]:
+ """Recognise an expression that is exactly one aggregation over an operand.
+
+ ``SUM(x)``, ``COUNT(DISTINCT x)``, ``SUM(DISTINCT x)`` and
+ ``PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY x)`` map onto Lightdash's typed
+ metrics; the operand may be a bare column reference or any expression.
+ Returns None for anything else (``COUNT(*)``, arithmetic between
+ aggregations, unknown functions).
+ """
+ percentile_match = _PERCENTILE_RE.match(expression)
+ if percentile_match:
+ percentile = float(percentile_match.group("fraction")) * 100
+ if percentile.is_integer():
+ percentile = int(percentile)
+ return ParsedAggregation(
+ "percentile", percentile_match.group("inner").strip(), percentile
+ )
+
+ match = _CALL_RE.match(expression)
+ if match is None or not _is_single_call_body(match.group("body")):
+ return None
+ function = match.group("func").upper()
+ inner = match.group("body").strip()
+ distinct = _DISTINCT_RE.match(inner)
+ if distinct:
+ lightdash_type = _DISTINCT_FUNCTION_TO_TYPE.get(function)
+ inner = distinct.group("inner").strip()
+ else:
+ lightdash_type = _FUNCTION_TO_TYPE.get(function)
+ if lightdash_type is None or not inner or inner == "*":
+ return None
+ return ParsedAggregation(lightdash_type, inner)
+
+
+def build_aggregation(
+ lightdash_type: str, inner: str, percentile: Optional[float] = None
+) -> Optional[str]:
+ """Build the Ossie expression for a typed Lightdash metric over ``inner``.
+
+ Returns None for metric types that are not aggregations (``number``,
+ ``string``, ``boolean``, ...).
+ """
+ if lightdash_type == "percentile":
+ fraction = (50 if percentile is None else percentile) / 100
+ return f"PERCENTILE_CONT({fraction:g}) WITHIN GROUP (ORDER BY {inner})"
+ if lightdash_type in _DISTINCT_AGGREGATE_FUNCTIONS:
+ return f"{_DISTINCT_AGGREGATE_FUNCTIONS[lightdash_type]}(DISTINCT {inner})"
+ function = _AGGREGATE_FUNCTIONS.get(lightdash_type)
+ if function is None:
+ return None
+ return f"{function}({inner})"
+
+
+def is_column_reference(expression: str) -> bool:
+ """True for a bare ``column`` or ``qualifier.column`` reference."""
+ return _COLUMN_REFERENCE_RE.match(expression) is not None
+
+
+def strip_qualifier(column_ref: str) -> str:
+ """Return the bare column name of a possibly ``qualifier.column`` reference."""
+ return column_ref.rsplit(".", 1)[-1]
+
+
+def qualifier_of(column_ref: str) -> Optional[str]:
+ """Return the qualifier of a ``qualifier.column`` reference, if present."""
+ if "." in column_ref:
+ return column_ref.rsplit(".", 1)[0]
+ return None
+
+
+def ossie_sql_to_lightdash(
+ expression: str, dataset: str, references: Optional[Dict[str, str]] = None
+) -> str:
+ """Rewrite Ossie column references into Lightdash references.
+
+ ``dataset.column`` becomes ``${TABLE}.column``; a dataset in ``references``
+ (joined from ``dataset``) becomes ``${<join reference>.column}``, where the
+ join reference is the joined model's name or its alias.
+ """
+ names = {dataset: None, **(references or {})}
Review Comment:
`name = {dataset: None, **(references or {})}` lets `references` win over the dataset's own `None (${TABLE})` mapping. For a self-join (`from=employees, to=employees`) `references["employees"]` is set, so the model's own columns become `${alias.col}` and get computed from the joined copy.
I suggest to reverse the order to `{**(references or {}), dataset: None}`.
##########
lightdash/src/ossie_lightdash/ossie_to_lightdash.py:
##########
@@ -0,0 +1,651 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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.
+"""Convert an Ossie document into Lightdash semantic definitions.
+
+``convert`` produces a dbt ``schema.yml``-shaped dictionary whose ``meta``
+blocks carry Lightdash dimensions, metrics and joins, ready to be merged into
+a dbt project that Lightdash reads. ``convert_models`` produces Lightdash's
+own dbt-free model files (``type: model``, ``sql_from``, typed dimensions),
+which ``lightdash deploy`` reads directly. Lightdash-specific presentation attributes that
+have no Ossie vocabulary round-trip through ``custom_extensions`` entries with
+``vendor_name: LIGHTDASH``; their keys are overlaid onto the generated
+definitions and win for presentation attributes, while structural keys
+(``sql``/``label`` on dimensions, ``sql``/``description`` on metrics,
+``join``/``sql_on`` on joins) are protected so they can never override the
+Ossie-derived definition.
+"""
+
+import json
+import re
+from typing import Any, Dict, List, Optional, Set, Tuple
+
+from ossie import (
+ OssieDataset,
+ OssieDialect,
+ OssieDocument,
+ OssieExpression,
+ OssieMetric,
+ OssieSemanticModel,
+)
+
+from ossie_lightdash.converter_issues import (
+ ConverterIssue,
+ ConverterIssueType,
+ ConverterResult,
+)
+from ossie_lightdash.datatype_utils import datatype_to_lightdash_type, is_temporal
+from ossie_lightdash.expression_utils import (
+ is_column_reference,
+ ossie_sql_to_lightdash,
+ parse_aggregation,
+ qualifier_of,
+ referenced_datasets,
+ strip_qualifier,
+)
+
+LIGHTDASH_VENDOR_NAME = "LIGHTDASH"
+
+# Structural keys are owned by Ossie vocabulary (the import direction never puts
+# them into the extension); dropping them here keeps a hand-authored extension
+# from overriding the Ossie-derived definition. ``type`` stays overridable on
+# metrics whose expression is not a recognised aggregation: it is the channel
+# for types an expression cannot express (``boolean``, ``string``, ...).
+_PROTECTED_DIMENSION_KEYS = {"sql", "label", "ai_hint", "hidden", "column_meta"}
+_PROTECTED_METRIC_KEYS = {"sql", "description", "ai_hint", "name", "model"}
+_PROTECTED_AGGREGATION_KEYS = _PROTECTED_METRIC_KEYS | {"type", "percentile"}
+_PROTECTED_JOIN_KEYS = {"join", "sql_on", "alias"}
+# Dataset-level stash keys that map to Ossie vocabulary or are handled apart.
+_PROTECTED_MODEL_KEYS = {"joins", "metrics", "primary_key", "ai_hint", "name", "type", "sql_from"}
+# Order of the top-level keys in a Lightdash model file; anything else
+# (stashed model meta) follows in source order.
+_MODEL_KEY_ORDER = ("type", "name", "label", "description", "sql_from", "primary_key", "ai_hint")
+_DIMENSION_KEY_ORDER = ("name", "type", "label", "description", "sql", "hidden")
+
+# Joins a dataset declares, keyed by the joined dataset: the name Lightdash SQL
+# uses to reference it (the joined model, or its alias). The first join to a
+# dataset wins when it is joined more than once.
+JoinReferences = Dict[str, str]
+
+
+def _lightdash_extension_data(element: Any, issues: List[ConverterIssue]) -> Dict[str, Any]:
+ """Return the ``lightdash`` vendor extension data of an Ossie element, if any."""
+ data: Dict[str, Any] = {}
+ for extension in element.custom_extensions or []:
+ # The registered token is LIGHTDASH; documents written before the
+ # registration used the lowercase name.
+ if extension.vendor_name.upper() == LIGHTDASH_VENDOR_NAME:
+ try:
+ data.update(json.loads(extension.data))
+ except (TypeError, ValueError):
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.EXTENSION_DATA_INVALID,
+ element_name=getattr(element, "name", "<unnamed>"),
+ )
+ )
+ else:
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.FOREIGN_EXTENSION_IGNORED,
+ element_name=getattr(element, "name", "<unnamed>"),
+ )
+ )
+ return data
+
+
+def _ai_hint(ai_context: Any) -> Any:
+ """Ossie `ai_context` as a Lightdash `ai_hint`: one line stays a string, a
+ multi-line instruction becomes a list, and synonyms and examples of the
+ structured form are rendered as extra hints."""
+ if ai_context is None:
+ return None
+ if isinstance(ai_context, str):
+ hints = ai_context.split("\n")
+ else:
+ hints = (ai_context.instructions or "").split("\n")
+ if ai_context.synonyms:
+ hints.append("Also known as: " + ", ".join(ai_context.synonyms))
+ if ai_context.examples:
+ hints.append("Example questions: " + "; ".join(ai_context.examples))
+ hints = [hint for hint in hints if hint]
+ if not hints:
+ return None
+ return hints[0] if len(hints) == 1 else hints
+
+
+def _ordered(entries: Dict[str, Any], order: Tuple[str, ...]) -> Dict[str, Any]:
+ """Return ``entries`` with the keys in ``order`` first, the rest as they came."""
+ return {
+ **{key: entries[key] for key in order if key in entries},
+ **{key: value for key, value in entries.items() if key not in order},
+ }
+
+
+def _to_lightdash_model(
+ dataset: OssieDataset, model: Dict[str, Any], issues: List[ConverterIssue]
+) -> Dict[str, Any]:
+ """Reshape a dbt-flavoured model into a Lightdash model file."""
+ meta = dict(model.get("meta") or {})
+ out: Dict[str, Any] = {"type": "model", "name": model["name"]}
+ if model.get("description"):
+ out["description"] = model["description"]
+ out["sql_from"] = dataset.source
+ joins = meta.pop("joins", None)
+ model_metrics = meta.pop("metrics", None)
+ out.update(meta)
+ if joins:
+ out["joins"] = joins
+ if model_metrics:
+ out["metrics"] = model_metrics
+
+ dimensions: List[Dict[str, Any]] = []
+ for column in model.get("columns") or []:
+ column_meta = column.get("meta") or {}
+ dimension = dict(column_meta.get("dimension") or {})
+ dimension["name"] = column["name"]
+ if column.get("description") and "description" not in dimension:
+ dimension["description"] = column["description"]
+ if not dimension.get("type"):
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.DIMENSION_TYPE_DEFAULTED,
+ element_name=f"{model['name']}.{column['name']}",
+ )
+ )
+ dimension["type"] = "string"
+ if not dimension.get("sql"):
+ dimension["sql"] = f"${{TABLE}}.{column['name']}"
+ if column_meta.get("metrics"):
+ dimension["metrics"] = column_meta["metrics"]
+ if column_meta.get("additional_dimensions"):
+ dimension["additional_dimensions"] = column_meta["additional_dimensions"]
+ if any(key not in ("dimension", "metrics", "additional_dimensions") for key in column_meta):
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.COLUMN_META_NOT_REPRESENTABLE,
+ element_name=f"{model['name']}.{column['name']}",
+ )
+ )
+ dimensions.append(_ordered(dimension, _DIMENSION_KEY_ORDER))
+ out["dimensions"] = dimensions
+ return _ordered(out, _MODEL_KEY_ORDER)
+
+
+def _nest_meta_under_config(node: Dict[str, Any]) -> None:
+ """Move a node's ``meta`` under ``config`` (the dbt 1.10+ placement)."""
+ meta = node.pop("meta", None)
+ if meta:
+ node["config"] = {"meta": meta}
+
+
+_MODEL_NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
+_SOURCE_IDENTIFIER = r'(?:[A-Za-z_][A-Za-z0-9_$]*|"(?:""|[^"])+"|`(?:``|[^`])+`|\[(?:\]\]|[^\]])+\])'
+_SOURCE_PATH_RE = re.compile(rf"{_SOURCE_IDENTIFIER}(?:\s*\.\s*{_SOURCE_IDENTIFIER})*")
+
+
+def _model_name_for(dataset: OssieDataset) -> str:
+ """Use a simple source's table name, otherwise its logical dataset name."""
+ source = dataset.source.strip()
+ # BigQuery may quote the entire project.dataset.table path with backticks.
+ if re.fullmatch(r"`[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+`", source):
+ source = source[1:-1]
+ candidate = source.rsplit(".", 1)[-1]
+ elif _SOURCE_PATH_RE.fullmatch(source):
+ candidate = re.findall(_SOURCE_IDENTIFIER, source)[-1]
+ if candidate[0] in ('"', '`', '['):
+ candidate = candidate[1:-1]
+ else:
+ candidate = dataset.name
+ if not _MODEL_NAME_RE.fullmatch(candidate):
+ candidate = dataset.name
+ if not _MODEL_NAME_RE.fullmatch(candidate):
+ raise ValueError(
+ f"Dataset {dataset.name!r} has no safe Lightdash model name; use a dataset "
+ "name starting with a letter or underscore, followed by letters, digits or underscores."
+ )
+ return candidate
+
+
+class OssieToLightdashConverter:
+ """Converts an OssieDocument into a Lightdash-flavoured dbt schema.yml dict.
+
+ ``dialect`` is the expression dialect to prefer (the project's warehouse);
+ ``OSSIE_SQL_2026`` and ``ANSI_SQL`` are the fallbacks. An expression offering
+ none of these is taken from its first dialect with a ``DIALECT_UNAVAILABLE`` issue.
+ """
+
+ def __init__(
+ self,
+ dialect: OssieDialect = OssieDialect.ANSI_SQL,
+ *,
+ meta_under_config: bool = False,
+ ) -> None:
+ self._dialect = dialect
+ self._meta_under_config = meta_under_config
+
+ def convert(self, document: OssieDocument) -> ConverterResult[Dict[str, Any]]:
+ """Ossie document → dbt ``schema.yml`` dict with Lightdash ``meta``."""
+ issues: List[ConverterIssue] = []
+ models = [model for _, model in self._convert_semantic_model(document, issues)]
+ if self._meta_under_config:
+ for model in models:
+ _nest_meta_under_config(model)
+ for column in model.get("columns") or []:
+ _nest_meta_under_config(column)
+ return ConverterResult(output={"version": 2, "models": models}, issues=issues)
+
+ def convert_models(self, document: OssieDocument) -> ConverterResult[List[Dict[str, Any]]]:
+ """Ossie document → Lightdash model files (one dict per dataset).
+
+ The dbt-free format has a home for everything the dbt flavour has to
+ stash: ``sql_from`` is the dataset's ``source`` verbatim, model meta
+ becomes top-level keys, and every dimension carries its own ``type``
+ and ``sql``.
+ """
+ issues: List[ConverterIssue] = []
+ models: List[Dict[str, Any]] = []
+ for dataset, model in self._convert_semantic_model(document, issues):
+ models.append(_to_lightdash_model(dataset, model, issues))
+ return ConverterResult(output=models, issues=issues)
+
+ def _pick_expression(
+ self, expression: OssieExpression, element_name: str, issues: List[ConverterIssue]
+ ) -> str:
+ by_dialect = {
+ dialect_expression.dialect: dialect_expression.expression
+ for dialect_expression in expression.dialects
+ }
+ for dialect in (self._dialect, OssieDialect.OSSIE_SQL_2026, OssieDialect.ANSI_SQL):
+ if dialect in by_dialect:
+ return by_dialect[dialect]
+ if not expression.dialects:
+ return ""
+ issues.append(
+ ConverterIssue(
+ issue_type=ConverterIssueType.DIALECT_UNAVAILABLE,
+ element_name=element_name,
+ )
+ )
+ return expression.dialects[0].expression
+
+ def _convert_semantic_model(
+ self, semantic_model: OssieSemanticModel, issues: List[ConverterIssue]
+ ) -> List[Tuple[OssieDataset, Dict[str, Any]]]:
+ datasets = semantic_model.datasets or []
+ dataset_names = {dataset.name for dataset in datasets}
+ model_name_by_dataset: Dict[str, str] = {}
+ dataset_by_model_name: Dict[str, str] = {}
+ for dataset in datasets:
+ name = _model_name_for(dataset)
+ # Also reject case-only collisions on case-insensitive filesystems.
+ previous = dataset_by_model_name.get(name.casefold())
+ if previous is not None:
+ raise ValueError(
+ f"Datasets {previous!r} and {dataset.name!r} both export to "
+ f"Lightdash model {name!r}; model names must be unique (ignoring case)."
+ )
+ if dataset.name in model_name_by_dataset:
+ raise ValueError(f"Duplicate dataset name: {dataset.name!r}")
+ dataset_by_model_name[name.casefold()] = dataset.name
+ model_name_by_dataset[dataset.name] = name
+
+ # Joins are planned first: field and metric expressions may reference
+ # other datasets only through the joins their own dataset declares.
+ joins_by_dataset, references_by_dataset = self._plan_joins(
+ semantic_model, model_name_by_dataset, issues
+ )
+
+ models_by_dataset: Dict[str, Dict[str, Any]] = {}
+ columns_by_dataset: Dict[str, Dict[str, Dict[str, Any]]] = {}
+ stash_by_dataset: Dict[str, Dict[str, Any]] = {}
+ for dataset in datasets:
+ stash = _lightdash_extension_data(dataset, issues)
+ stash_by_dataset[dataset.name] = stash
+ # A stashed join (chained, expression, extra conditions) is
+ # restored verbatim, replacing the generated join to the same
+ # target and alias, and its target becomes referenceable.
+ joins = joins_by_dataset.setdefault(dataset.name, [])
+ references = references_by_dataset.setdefault(dataset.name, {})
+ for stashed_join in stash.get("joins") or []:
+ if not isinstance(stashed_join, dict) or not stashed_join.get("join"):
+ continue
+ key = (stashed_join.get("join"), stashed_join.get("alias"))
+ for index, join in enumerate(joins):
+ if (join.get("join"), join.get("alias")) == key:
+ joins[index] = stashed_join
+ break
+ else:
+ joins.append(stashed_join)
+ references.setdefault(
Review Comment:
`references` is built per Ossie dataset name, but this line registers the stashed join under `stashed_join["join"]`, which is the Lightdash model name.
When a dataset's name differs from its model name (`customers_ds`-> `customers`), the later `referenced_datasets(...) - references` check raises a false `FIELD_REFERENCE_UNJOINED`.
`ossie_sql_to_lightdash` also leaves `customer_ds.col` unrewritten and cross-dataset metrics get dropped.
Can we map the model name back to the Ossie dataset name before inserting, and add a test where the two names differ?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ossie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add lightdash converter [ossie-converters]
Posted by "jbonofre (via GitHub) via issues" <is...@ossie.apache.org>.
jbonofre merged PR #7:
URL: https://github.com/apache/ossie-converters/pull/7
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ossie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add lightdash converter [ossie-converters]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #7:
URL: https://github.com/apache/ossie-converters/pull/7#issuecomment-6321504636
Thank you for your first contribution to Apache Ossie (incubating)!
A committer will review your PR. In the meantime, please ensure:
- All CI checks pass
- ASF license headers are present on new source files
- Tests cover new functionality
No ICLA is required to contribute. If you are elected as a committer in the future, you will need an [Individual Contributor License Agreement (ICLA)](https://www.apache.org/licenses/contributor-agreements.html) on file with the ASF.
**Questions?** Ask in the PR comments or join us on [Slack](https://join.slack.com/t/apache-ossie/shared_invite/zt-42zw4rflt-Gpve8_NFJq7AsdAQTY~SCg).
We appreciate your contribution!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ossie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add lightdash converter [ossie-converters]
Posted by "owlas (via GitHub) via issues" <is...@ossie.apache.org>.
owlas commented on PR #7:
URL: https://github.com/apache/ossie-converters/pull/7#issuecomment-6661221843
Hey @jbonofre just came here to explain the new changes i put on top but you already picked it up!!! Great job, let me know if you need anything else from us 🦘
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ossie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add lightdash converter [ossie-converters]
Posted by "jbonofre (via GitHub) via issues" <is...@ossie.apache.org>.
jbonofre commented on PR #7:
URL: https://github.com/apache/ossie-converters/pull/7#issuecomment-6663311845
@owlas thank you so much! Much appreciated. I think we are good now 😄 🦘
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@ossie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org