diff --git a/docs/how/breaking-changes.md b/docs/how/breaking-changes.md index f97b9ee03c603..62141550f09e5 100644 --- a/docs/how/breaking-changes.md +++ b/docs/how/breaking-changes.md @@ -87,6 +87,7 @@ Requirements: - [#20842](https://github.com/datahub-project/datahub/pull/20842) **(Ingestion / Power BI)** Column-level lineage now follows the same `dataset_type_mapping` filter as table-level lineage, in both `metadata_api_mode` settings. If you narrowed `dataset_type_mapping` to fewer platforms than the default, a Power BI column no longer gets a lineage edge to a column of an upstream table that the mapping excludes; before, the column edge was emitted even though the table edge was not. Duplicate column-level edges, which were emitted once per upstream table of a Power BI table, are also removed. **Action:** none unless you relied on column lineage to platforms you left out of `dataset_type_mapping`; add those platforms to the mapping to keep it. The dropped edges disappear on the next run. - [#20876](https://github.com/datahub-project/datahub/pull/20876) **(Ingestion / Power BI)** Column-level lineage no longer links a warehouse column to a Power BI _calculated column_ (a column defined by a DAX expression) of the same name, in both `admin_scan` and `workspace_apis` modes; such columns are computed inside the semantic model and the previous edge pointed at a column the warehouse never feeds. For semantic models read through `metadata_api_mode: workspace_apis`, column lineage now follows each column's TMDL `sourceColumn`, so a field renamed in the model points at its real upstream column instead of a same-named one. **Action:** none unless you relied on those edges; the dropped edges disappear on the next run with stateful ingestion. +- [#20884](https://github.com/datahub-project/datahub/pull/20884) **(Ingestion / Power BI)** A semantic-model table (or Dataflow Gen2 entity) that reads a Microsoft Fabric Lakehouse or Warehouse through its SQL analytics endpoint (an M query calling `Sql.Database(".datawarehouse.fabric.microsoft.com", ...)`) now gets its upstream lineage edge on the OneLake table (`fabric-onelake` platform, the URN the OneLake connector emits) instead of a generic SQL Server (`mssql`) dataset. This applies in both `metadata_api_mode` settings, because the admin scan also lists the workspace's Lakehouses and Warehouses. The edge is rewritten in place on the next run; no entity is deleted, but the old `mssql` dataset the edge pointed at no longer receives lineage from Power BI. Endpoints that cannot be matched to a Lakehouse or Warehouse of the same workspace keep their `mssql` edge and are reported as warnings. The OneLake edge is kept even if you narrowed `dataset_type_mapping` to leave out SQL Server, the same as DirectLake lineage, so a table that had no upstream edge under such a mapping now gets one. **Action:** none, unless something relied on the `mssql` upstream of such tables; in that case map the workspace id in `server_to_platform_instance` and ingest the Fabric items with the OneLake connector so the new edge lands on an existing dataset. - [#21219](https://github.com/datahub-project/datahub/pull/21219) **(Ingestion / Qlik Sense)** On Qlik Sense Enterprise, QVD datasets are now placed in `Folder` containers that follow their file path (server or share, then each folder), and are browsed under those folders instead of the path split at its dots. Their URNs, schemas and lineage are unchanged. **Action:** update any bookmark or saved browse path that pointed at the old QVD hierarchy. diff --git a/metadata-ingestion/docs/sources/powerbi/powerbi_pre.md b/metadata-ingestion/docs/sources/powerbi/powerbi_pre.md index 4011ffcc2555d..e067eea8f45a7 100644 --- a/metadata-ingestion/docs/sources/powerbi/powerbi_pre.md +++ b/metadata-ingestion/docs/sources/powerbi/powerbi_pre.md @@ -94,6 +94,8 @@ No Microsoft Entra application permissions need to change: both API families are What `workspace_apis` mode ingests: workspaces, dashboards, tiles, reports, report pages, datasets with tables, columns, measures and their descriptions, M expressions, table and column lineage (including DirectLake lineage to Fabric Lakehouses and Warehouses), paginated-report dataset bindings, and owners derived from workspace roles. With `extract_report_field_usage` enabled, a Power BI report (not a paginated report, which never gets field usage or filters) whose definition is fetched and parsed gets, on each page chart, the model fields its visuals read, and its report-level and page-level filters as `filters` / `filterCount` properties on the report and its pages, with the filtered fields added to the page's `inputFields`; a report whose definition is refused or cannot be parsed gets neither its filters nor their fields. `filters` holds at most 50 entries: `filterCount` is the full count and `filtersTruncated: true` marks a shortened list. A rendered condition is cut to 500 characters and lists at most 20 `In` values, and a condition shape the connector does not recognize is kept as its raw JSON cut to 200 characters, so `filters` is a summary, not the complete filter definition. A filter's rendered condition includes the literal values it compares against (for example the selected categories or thresholds), so treat these properties as potentially containing business data. +**Fabric Lakehouse and Warehouse lineage.** The connector lists each workspace's Fabric items and registers the SQL analytics endpoint of every Lakehouse (one `GET lakehouses/{id}` call per lakehouse) and Warehouse (a warehouse is its own endpoint). A semantic-model table that reads one of them, either in DirectLake mode or through an Import/DirectQuery `Sql.Database(".datawarehouse.fabric.microsoft.com", ...)` query (a table navigation or a native `[Query=...]`), gets upstream lineage to the OneLake table (`fabric-onelake` platform, the same URN the OneLake connector emits) instead of a generic `mssql` one. The `Sql.Database` mapping applies in both metadata modes, since the admin scan also lists the workspace's Lakehouses and Warehouses. Map the workspace id in `server_to_platform_instance` to set the OneLake `platform_instance` and `env`. These OneLake edges are not subject to `dataset_type_mapping`, same as DirectLake lineage, so narrowing that mapping never turns such an edge into none; Dataflow Gen2 entities get the same mapping. The URNs match the OneLake connector's when that source runs with `convert_urns_to_lowercase: true` or this one with `convert_lineage_urns_to_lowercase: false` (by default Power BI lowercases the whole lineage URN while the OneLake connector keeps schema and table casing). A `Sql.Database` query may name the endpoint by id or by the item's display name. In `workspace_apis` mode a display name only matches on the workspace's own endpoint host; the admin scan reports no host, so there a display name matches the workspace's item on any host. A query naming an endpoint that is not among the workspace's items (for example a lakehouse in a workspace outside your workspace patterns) keeps its generic `mssql` edge and is reported as a `Fabric Endpoint Not Resolved` warning, and a display name shared by several items is reported as `Fabric Endpoint Name Ambiguous`. A `Sql.Databases` navigation, a navigation without an `Item`, or an endpoint behind a dataset parameter the connector could not resolve (the server argument is a parameter missing from the dataset) is not mapped: the first two are reported as `Fabric Endpoint M Shape Unsupported`, the last falls through to the generic SQL Server handling. Datamarts, mirrored databases and SQL databases are not covered: the OneLake connector does not ingest their tables, so no edge is emitted for them. + In both metadata API modes a calculated column (one defined by a DAX expression) gets no column-level edge to the upstream table. In `workspace_apis` mode or with `enrich_from_item_definitions`, column lineage additionally follows each column's TMDL `sourceColumn`, so a field renamed in the model still points at the right column of the upstream table; a calculated table always gets table-level lineage from the model tables its DAX reads, and a measure that reads columns of other tables always gets column-level edges from them. Set `extract_dax_reference_lineage: true` to also derive lineage from the rest of the DAX: a calculated column gets column-level edges from the columns and measures its expression reads, and a measure that references another measure gets an edge from it. Edges are only emitted to tables and fields that exist in the parsed model. A DAX reference that does not resolve is counted in the report and surfaced as a `DAX Reference Not Resolved` warning. DAX is only read from TMDL definitions, so this applies to `workspace_apis` mode or `enrich_from_item_definitions`; without the flag only the table-qualified references of measures and the tables read by calculated tables are checked. Enabling the flag makes the connector write `upstreamLineage` on tables that previously had none (for example a measures-only table whose measures read each other), which replaces any upstreams authored for those tables in the UI. The flag requires `extract_column_level_lineage`. Set `extract_model_properties: true` to also ingest the model properties the TMDL definition carries. Each schema field gets `isPartOfKey` from `isKey`, `nullable` from an explicit `isNullable` (an explicit `isNullable: false` is the same as the aspect's default), and a JSON object in its `jsonProps` with the rest: `isHidden` (only written when true), `formatString`, `displayFolder`, `dataCategory`, `sortByColumn` and `summarizeBy` (omitted when it is the Desktop default `none`) for columns, and `isHidden`, `formatString`, `displayFolder` and `hasKpi` for measures. Each table's custom properties gain `storageMode` (`Import`, `DirectQuery`, `Dual`, `DirectLake` or `Push`), `partitionCount`, `incrementalRefresh: true` with the `refreshPolicy.rollingWindowGranularity`, `refreshPolicy.rollingWindowPeriods`, `refreshPolicy.incrementalGranularity` and `refreshPolicy.incrementalPeriods` settings when the table has a refresh policy, the row-level-security roles that filter the table as `rlsRoles` (a JSON list of `{role, filter}`) with `rlsRoleCount`, and every dataset parameter as `parameter.` with its current value cut to 1000 characters. The RLS `filter` is the role's DAX exactly as authored, so it can contain hard-coded user names or emails if the model's author wrote them into the filter; a role filtering a table that is not in the model is reported as an `RLS Filter Table Not Found` warning. A parameter whose name contains `secret`, `token`, `password`, `pwd`, `pass`, `credential`, `key`, `auth`, `connection`, `sas`, `signature`, `cert`, `private`, `jwt` or `bearer` (substring match, so over-masking is the safe direction), or that has `pat` as a whole word (`PAT`, `GitHubPAT`, `my_pat`, but not `FilePath` or `Pattern`), is emitted with the value `***`. Role members are identities and are never ingested; a role file that cannot be parsed is reported as a `TMDL Role Not Parsed` warning and does not fail the model. The flag requires `extract_dataset_schema`. diff --git a/metadata-ingestion/src/datahub/ingestion/source/powerbi/config.py b/metadata-ingestion/src/datahub/ingestion/source/powerbi/config.py index dd2b9c28a9fb8..89d959fe79ad3 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/powerbi/config.py +++ b/metadata-ingestion/src/datahub/ingestion/source/powerbi/config.py @@ -457,6 +457,24 @@ class PowerBiDashboardSourceReport(StaleEntityRemovalSourceReport): fabric_report_definitions_denied: int = 0 dataset_parameters_failed: int = 0 fabric_lro_timeouts: int = 0 + # Fabric SQL analytics endpoints registered from the item listing: a + # warehouse is its own endpoint, a lakehouse's comes from its properties. + fabric_warehouse_endpoints_registered: int = 0 + fabric_lakehouse_endpoints_registered: int = 0 + # Lakehouses whose properties call failed, so their endpoint is unknown; + # DirectLake tables over them lose only the OneLake edge. + fabric_lakehouse_endpoints_unresolved: int = 0 + # Distinct (table, endpoint, schema, table name) Sql.Database references + # over a Fabric endpoint host, not per emission: swapped for OneLake + # edges, naming an endpoint that is not among the workspace's items + # (mssql edge kept), or naming a display name shared by several items. + fabric_endpoint_references_resolved: int = 0 + fabric_endpoint_references_unresolved: int = 0 + fabric_endpoint_references_ambiguous: int = 0 + # Fabric endpoint queries in a shape not mapped to OneLake (Sql.Databases + # navigation, a navigation without Item, an unqualified native-query + # table); per table. + fabric_endpoint_m_shapes_unsupported: int = 0 tmdl_tables_parsed: int = 0 tmdl_parts_failed: int = 0 tmdl_parts_incomplete: int = 0 diff --git a/metadata-ingestion/src/datahub/ingestion/source/powerbi/m_query/data_classes.py b/metadata-ingestion/src/datahub/ingestion/source/powerbi/m_query/data_classes.py index 4d3b8222fe544..56fb0d1637afb 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/powerbi/m_query/data_classes.py +++ b/metadata-ingestion/src/datahub/ingestion/source/powerbi/m_query/data_classes.py @@ -71,6 +71,11 @@ class ReferencedTable: class DataPlatformTable: data_platform_pair: DataPlatformPair urn: str + # Set when the mapper swapped an mssql edge for the OneLake table behind + # a Fabric SQL analytics endpoint; such an edge is kept even when + # dataset_type_mapping was narrowed, like DirectLake lineage, so a + # narrowed mapping never turns an existing edge into none. + from_fabric_endpoint: bool = False @dataclass(frozen=True) @@ -85,6 +90,23 @@ class DataflowReference: entity: str +@dataclass(frozen=True) +class FabricSqlEndpointReference: + """A ``Sql.Database`` navigation whose server is a Fabric SQL analytics + endpoint host. ``database`` is what the query named: the endpoint id (as + DirectLake's shared expression does) or the item's display name (as Power + BI Desktop writes it). Only the mapper, which knows the workspace's + Fabric items, can turn it into the OneLake table it reads; until then the + lineage carries the table under the generic MSSQL platform at + ``mssql_urn``.""" + + server: str + database: str + schema_name: Optional[str] + table_name: str + mssql_urn: str + + @dataclass class Lineage: upstreams: List[DataPlatformTable] @@ -94,6 +116,9 @@ class Lineage: # lineage applies renames to the query's output names inside parse_custom_sql. downstream_names_are_powerbi_fields: bool = True dataflow_references: List[DataflowReference] = field(default_factory=list) + fabric_endpoint_references: List[FabricSqlEndpointReference] = field( + default_factory=list + ) @staticmethod def empty() -> "Lineage": diff --git a/metadata-ingestion/src/datahub/ingestion/source/powerbi/m_query/pattern_handler.py b/metadata-ingestion/src/datahub/ingestion/source/powerbi/m_query/pattern_handler.py index 899aeb416deb0..fbcb074a8d596 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/powerbi/m_query/pattern_handler.py +++ b/metadata-ingestion/src/datahub/ingestion/source/powerbi/m_query/pattern_handler.py @@ -1,3 +1,4 @@ +import dataclasses import logging import re from abc import ABC, abstractmethod @@ -39,6 +40,7 @@ DataAccessFunctionDetail, DataflowReference, DataPlatformTable, + FabricSqlEndpointReference, FunctionName, IdentifierAccessor, Lineage, @@ -71,6 +73,48 @@ SupportedDataPlatform.GOOGLE_BIGQUERY.value.datahub_data_platform_name ) +# Host suffix of every Fabric SQL analytics endpoint (lakehouse, warehouse); +# the ``Sql.Database`` server argument of a query over one ends with it. +FABRIC_SQL_ENDPOINT_HOST_SUFFIX = ".datawarehouse.fabric.microsoft.com" +# Record keys of the ``Source{[Schema=..., Item=...]}`` navigation step. +_ACCESSOR_KEY_SCHEMA = "Schema" +_ACCESSOR_KEY_ITEM = "Item" + + +def is_fabric_sql_endpoint_host(server: Optional[str]) -> bool: + """False for an unresolved server parameter (None / empty), so such a + query falls through to the generic MSSQL handling unannounced.""" + if not server: + return False + return server.strip().lower().endswith(FABRIC_SQL_ENDPOINT_HOST_SUFFIX) + + +# Segments of the mssql dataset name a native query resolves to; any platform +# instance prefix sits before them. +_MSSQL_QUALIFIED_NAME_PARTS = 3 + + +def _split_mssql_qualified_name( + name: str, platform_instance: Optional[str] +) -> Optional[Tuple[str, str, str]]: + """``(database, schema, table)`` from an mssql dataset name. + + The name is ``[instance.]database.schema.table`` with the parts joined by + unescaped dots, so the platform instance the URN was built with is + stripped first; the first two remaining segments are then the database + and schema, and the rest is the table, which keeps a bracketed table + name containing a dot (``[v1.data]``) whole. None when fewer than three + segments remain.""" + if platform_instance: + prefix = f"{platform_instance.lower()}." + if name.lower().startswith(prefix): + name = name[len(prefix) :] + parts = name.split(".") + if len(parts) < _MSSQL_QUALIFIED_NAME_PARTS: + return None + return parts[0], parts[1], ".".join(parts[2:]) + + # First enum entry wins when multiple PowerBI names share a DataHub platform # (e.g. Databricks / DatabricksMultiCloud both map to "databricks"). _DATAHUB_PLATFORM_TO_PAIR: Dict[str, DataPlatformPair] = {} @@ -436,11 +480,9 @@ def apply_table_rename_columns( logic=info.logic, ) ) - return Lineage( - upstreams=lineage.upstreams, - column_lineage=updated, - downstream_names_are_powerbi_fields=lineage.downstream_names_are_powerbi_fields, - ) + # replace() keeps the reference lists (dataflow, Fabric SQL endpoint) that a + # field-by-field rebuild would drop, which disabled the OneLake swap. + return dataclasses.replace(lineage, column_lineage=updated) def make_urn( @@ -1825,7 +1867,7 @@ def create_lineage( if query: if self.config.enable_advance_lineage_sql_construct is False: # Use previous parser to generate URN to keep backward compatibility - return Lineage( + lineage = Lineage( upstreams=self.create_urn_using_old_parser( query=query, db_name=database, @@ -1833,17 +1875,100 @@ def create_lineage( ), column_lineage=[], ) + else: + lineage = self.parse_custom_sql( + query=query, + database=database, + server=server, + schema=MSSqlLineage.DEFAULT_SCHEMA, + ) + if is_fabric_sql_endpoint_host(server): + self._add_fabric_endpoint_references_from_urns(lineage, server) + return lineage - return self.parse_custom_sql( - query=query, - database=database, + # It is a regular case of MS-SQL + logger.debug("Handling with regular case") + lineage = self.two_level_access_pattern(data_access_func_detail) + if is_fabric_sql_endpoint_host(server): + self._add_fabric_endpoint_reference_from_navigation( + lineage, server, database, data_access_func_detail.identifier_accessor + ) + return lineage + + def _add_fabric_endpoint_reference_from_navigation( + self, + lineage: Lineage, + server: str, + database: str, + accessor: Optional[IdentifierAccessor], + ) -> None: + """``Source{[Schema=..., Item=...]}`` over a Fabric endpoint: the + endpoint is a TDS view over OneLake tables, so the mapper swaps the + MSSQL edge for the OneLake one once it knows the item.""" + table_name = accessor.items.get(_ACCESSOR_KEY_ITEM) if accessor else None + if not table_name: + self._report_fabric_endpoint_shape_unsupported( + server, "the navigation step has no Item" + ) + return + if not lineage.upstreams: + self._report_fabric_endpoint_shape_unsupported( + server, "the navigation step resolved no table" + ) + return + lineage.fabric_endpoint_references.append( + FabricSqlEndpointReference( server=server, - schema=MSSqlLineage.DEFAULT_SCHEMA, + database=database, + schema_name=accessor.items.get(_ACCESSOR_KEY_SCHEMA) + if accessor + else None, + table_name=table_name, + mssql_urn=lineage.upstreams[0].urn, ) + ) - # It is a regular case of MS-SQL - logger.debug("Handling with regular case") - return self.two_level_access_pattern(data_access_func_detail) + def _add_fabric_endpoint_references_from_urns( + self, lineage: Lineage, server: str + ) -> None: + """A native query (``[Query=...]``) over a Fabric endpoint: one + reference per table the SQL parser resolved, read back from the + mssql URN as ``[instance.]database.schema.table``.""" + platform_instance = self.platform_instance_resolver.get_platform_instance( + PowerBIPlatformDetail( + data_platform_pair=self.get_platform_pair(), + data_platform_server=server, + ) + ).platform_instance + for upstream in lineage.upstreams: + parts = _split_mssql_qualified_name( + DatasetUrn.from_string(upstream.urn).name, platform_instance + ) + if parts is None: + self._report_fabric_endpoint_shape_unsupported( + server, f"the query table {upstream.urn} is not database-qualified" + ) + continue + database_name, schema_name, table_name = parts + lineage.fabric_endpoint_references.append( + FabricSqlEndpointReference( + server=server, + database=database_name, + schema_name=schema_name, + table_name=table_name, + mssql_urn=upstream.urn, + ) + ) + + def _report_fabric_endpoint_shape_unsupported( + self, server: str, reason: str + ) -> None: + self.reporter.fabric_endpoint_m_shapes_unsupported += 1 + self.reporter.warning( + title="Fabric Endpoint M Shape Unsupported", + message="A query reads a Fabric SQL analytics endpoint in a shape the connector cannot map to a OneLake table; the table keeps a generic mssql upstream (or none) instead.", + context=f"table={self.table.full_name}, server={server}, reason={reason}", + ) class MSSqlMultiDatabaseLineage(AbstractLineage): @@ -1872,6 +1997,14 @@ def create_lineage( if server is None: logger.debug("Server not found in MSSQL Sql.Databases data access function") return Lineage.empty() + if is_fabric_sql_endpoint_host(server): + # Sql.Databases(host){[Name=...]} is not mapped to OneLake yet. + self.reporter.fabric_endpoint_m_shapes_unsupported += 1 + self.reporter.warning( + title="Fabric Endpoint M Shape Unsupported", + message="A Sql.Databases navigation reads a Fabric SQL analytics endpoint; only Sql.Database queries are mapped to OneLake tables, so this table keeps a generic mssql upstream.", + context=f"table={self.table.full_name}, server={server}", + ) # Second is database name db_name = accessor.items.get("Name") diff --git a/metadata-ingestion/src/datahub/ingestion/source/powerbi/powerbi.py b/metadata-ingestion/src/datahub/ingestion/source/powerbi/powerbi.py index 870773c88a239..e018b9c399b8c 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/powerbi/powerbi.py +++ b/metadata-ingestion/src/datahub/ingestion/source/powerbi/powerbi.py @@ -6,7 +6,7 @@ import functools import json import logging -from dataclasses import dataclass, field as dataclass_field +from dataclasses import dataclass, field from datetime import datetime from typing import Callable, Dict, Iterable, List, Optional, Set, Tuple, Union from urllib.parse import quote @@ -17,6 +17,7 @@ import datahub.emitter.mce_builder as builder import datahub.ingestion.source.powerbi.m_query.data_classes import datahub.ingestion.source.powerbi.rest_api_wrapper.data_classes as powerbi_data_classes +from datahub.configuration.source_common import PlatformDetail from datahub.emitter.mcp import MetadataChangeProposalWrapper from datahub.emitter.mcp_builder import ContainerKey, gen_containers from datahub.ingestion.api.common import PipelineContext @@ -144,7 +145,7 @@ ViewPropertiesClass, ) from datahub.metadata.urns import ChartUrn, DatasetUrn -from datahub.sql_parsing.sqlglot_lineage import ColumnLineageInfo +from datahub.sql_parsing.sqlglot_lineage import ColumnLineageInfo, ColumnRef from datahub.utilities.dedup_list import deduplicate_list from datahub.utilities.file_backed_collections import FileBackedDict from datahub.utilities.urns.urn_iter import lowercase_dataset_urn @@ -456,7 +457,17 @@ class ResolvedInputFields: unresolved: int = 0 # Datasets the resolved fields belong to, in first-seen order; a visual's # table-level inputs are exactly these, never the whole model. - dataset_urns: List[str] = dataclass_field(default_factory=list) + dataset_urns: List[str] = field(default_factory=list) + + +@dataclass +class FabricEndpointMatch: + """Lakehouse / Warehouse ids behind the endpoint a Sql.Database query + named; empty when none matched, ambiguous when a display name matched + more than one item.""" + + item_ids: List[str] = field(default_factory=list) + ambiguous: bool = False def _in_iterator( @@ -496,6 +507,11 @@ def __init__( # (table urn, dataflow id, entity) references already counted, so a # model mapped several times (report + tile) is reported once. self.__counted_dataflow_references: Set[Tuple[str, str, str]] = set() + # (table urn, endpoint, schema, source table) Sql.Database references + # over Fabric endpoints already counted, for the same reason. + self.__counted_fabric_endpoint_references: Set[ + Tuple[str, str, Optional[str], str] + ] = set() self.workspace_key: Optional[ContainerKey] = None # Refresh Operations are decided once per dataset and emitted on each # of its tables, so counters and warnings fire per dataset. @@ -743,17 +759,7 @@ def extract_directlake_lineage( logger.debug(f"No source expression for DirectLake table {table.full_name}") return mcps - # Resolve platform instance using server_to_platform_instance mapping - # Mapping: workspace_id -> (platform_instance, env) - # The platform_instance typically represents the Fabric tenant identifier, - # matching how the OneLake connector uses platform_instance to group workspaces by tenant. - # Falls back to None if no mapping is found. - platform_detail = self.__dataplatform_instance_resolver.get_platform_instance( - PowerBIPlatformDetail( - data_platform_pair=SupportedDataPlatform.FABRIC_ONELAKE.value, - data_platform_server=workspace.id, # Use workspace ID as the mapping key - ) - ) + platform_detail = self._onelake_platform_detail(workspace) # Resolve item ids for lineage URN. For SQLAnalyticsEndpoint we use physical_item_ids # (from relations.dependentOnArtifactId) so lineage URNs match the OneLake connector; @@ -779,7 +785,7 @@ def extract_directlake_lineage( item_id=item_id, table_name=table.source_expression, schema_name=table.source_schema, # Can be None for schemas-disabled lakehouses - env=platform_detail.env or self.__config.env, + env=platform_detail.env, platform_instance=platform_detail.platform_instance, # None if not mapped ) upstream_urn = self.lineage_urn_to_lowercase(upstream_urn) @@ -847,6 +853,8 @@ def extract_lineage( f"PowerBI virtual table {table.full_name} and it's upstream dataplatform tables = {upstream_lineage}" ) + self._resolve_fabric_endpoint_references(upstream_lineage, workspace, ds_urn) + self._add_upstreams_from_m_lineage( upstream_lineage, ds_urn, upstream, cll_lineage, column_lineage=True ) @@ -908,6 +916,190 @@ def extract_lineage( return mcps + def _resolve_fabric_endpoint_references( + self, + upstream_lineage: List[ + datahub.ingestion.source.powerbi.m_query.data_classes.Lineage + ], + workspace: powerbi_data_classes.Workspace, + ds_urn: str, + ) -> None: + """Swap each ``Sql.Database`` upstream over a Fabric SQL analytics + endpoint for the OneLake table(s) behind it, so the edge lands on the + same URN the OneLake connector emits instead of a generic ``mssql`` + one. An endpoint that is not among the workspace's Fabric items (a + lakehouse in another workspace, or one whose properties were refused) + keeps the ``mssql`` edge the connector always emitted and is + reported, since only the OneLake edge is lost.""" + for lineage in upstream_lineage: + for reference in lineage.fabric_endpoint_references: + reference_key = ( + ds_urn, + reference.database.lower(), + reference.schema_name, + reference.table_name, + ) + first_sighting = ( + reference_key not in self.__counted_fabric_endpoint_references + ) + self.__counted_fabric_endpoint_references.add(reference_key) + match = self._fabric_endpoint_match(workspace, reference) + if match.ambiguous: + if not first_sighting: + continue + self.__reporter.fabric_endpoint_references_ambiguous += 1 + self._warn_fabric_endpoint_reference( + title="Fabric Endpoint Name Ambiguous", + message="A Sql.Database query names a Fabric SQL analytics endpoint by display name, and several Lakehouses or Warehouses of the workspace share that name; the table keeps a generic mssql upstream instead of guessing the OneLake table.", + reference=reference, + workspace=workspace, + ds_urn=ds_urn, + ) + continue + if not match.item_ids: + if not first_sighting: + continue + self.__reporter.fabric_endpoint_references_unresolved += 1 + self._warn_fabric_endpoint_reference( + title="Fabric Endpoint Not Resolved", + message="A Sql.Database query reads a Fabric SQL analytics endpoint that is not a Lakehouse or Warehouse of its workspace (for example an item in a workspace outside the workspace patterns, or one whose properties could not be fetched); the table keeps a generic mssql upstream instead of the OneLake table.", + reference=reference, + workspace=workspace, + ds_urn=ds_urn, + ) + continue + if first_sighting: + self.__reporter.fabric_endpoint_references_resolved += 1 + platform_detail = self._onelake_platform_detail(workspace) + onelake_urns = [ + make_onelake_urn( + workspace_id=workspace.id, + item_id=item_id, + table_name=reference.table_name, + schema_name=reference.schema_name, + env=platform_detail.env, + platform_instance=platform_detail.platform_instance, + ) + for item_id in match.item_ids + ] + self._replace_upstream_urn(lineage, reference.mssql_urn, onelake_urns) + + def _onelake_platform_detail( + self, workspace: powerbi_data_classes.Workspace + ) -> PlatformDetail: + """platform_instance and env of OneLake URNs come only from + server_to_platform_instance keyed by the workspace id (the OneLake + connector groups workspaces by tenant the same way); the env falls + back to the mapping's own default, not the Power BI env.""" + return self.__dataplatform_instance_resolver.get_platform_instance( + PowerBIPlatformDetail( + data_platform_pair=SupportedDataPlatform.FABRIC_ONELAKE.value, + data_platform_server=workspace.id, + ) + ) + + def _warn_fabric_endpoint_reference( + self, + title: str, + message: str, + reference: datahub.ingestion.source.powerbi.m_query.data_classes.FabricSqlEndpointReference, + workspace: powerbi_data_classes.Workspace, + ds_urn: str, + ) -> None: + self.__reporter.warning( + title=title, + message=message, + context=( + f"table={ds_urn}, workspace={workspace.name}, " + f"server={reference.server}, database={reference.database}, " + f"source={reference.schema_name}.{reference.table_name}" + ), + ) + + @staticmethod + def _fabric_endpoint_match( + workspace: powerbi_data_classes.Workspace, + reference: datahub.ingestion.source.powerbi.m_query.data_classes.FabricSqlEndpointReference, + ) -> FabricEndpointMatch: + """The OneLake item(s) behind the endpoint a ``Sql.Database`` query + named: by endpoint id first (as DirectLake's shared expression + writes it), else by item display name (as Power BI Desktop writes + it). A name shared by several items is ambiguous rather than a + guess. Display names are only unique within a workspace, so when the + workspace's endpoint host is known a name only matches on that host: + a query on another workspace's endpoint is left unresolved.""" + key = reference.database.strip().lower() + by_id = [a for a in workspace.fabric_artifacts.values() if a.id.lower() == key] + if by_id: + return FabricEndpointMatch(item_ids=Mapper._physical_item_ids(by_id)) + hosts = workspace.fabric_sql_endpoint_hosts + if hosts and reference.server.strip().lower() not in hosts: + return FabricEndpointMatch(item_ids=[]) + by_name = [ + a for a in workspace.fabric_artifacts.values() if a.name.lower() == key + ] + item_ids = Mapper._physical_item_ids(by_name) + return FabricEndpointMatch(item_ids=item_ids, ambiguous=len(item_ids) > 1) + + @staticmethod + def _physical_item_ids( + artifacts: List[powerbi_data_classes.FabricArtifact], + ) -> List[str]: + """Distinct Lakehouse / Warehouse ids the artifacts stand for: an + endpoint artifact contributes its physical items, any other its own + id.""" + item_ids: List[str] = [] + for artifact in artifacts: + candidates = ( + artifact.physical_item_ids or [] + if artifact.artifact_type == FABRIC_ARTIFACT_SQL_ANALYTICS_ENDPOINT + else [artifact.id] + ) + for item_id in candidates: + if item_id.lower() not in {i.lower() for i in item_ids}: + item_ids.append(item_id) + return item_ids + + @staticmethod + def _replace_upstream_urn( + lineage: datahub.ingestion.source.powerbi.m_query.data_classes.Lineage, + old_urn: str, + new_urns: List[str], + ) -> None: + onelake_pair = SupportedDataPlatform.FABRIC_ONELAKE.value + upstreams: List[ + datahub.ingestion.source.powerbi.m_query.data_classes.DataPlatformTable + ] = [] + for upstream in lineage.upstreams: + if upstream.urn != old_urn: + upstreams.append(upstream) + continue + upstreams.extend( + datahub.ingestion.source.powerbi.m_query.data_classes.DataPlatformTable( + data_platform_pair=onelake_pair, + urn=urn, + from_fabric_endpoint=True, + ) + for urn in new_urns + ) + lineage.upstreams = upstreams + column_lineage: List[ColumnLineageInfo] = [] + for cll in lineage.column_lineage: + column_refs: List[ColumnRef] = [] + for column_ref in cll.upstreams: + if column_ref.table != old_urn: + column_refs.append(column_ref) + continue + column_refs.extend( + ColumnRef(table=urn, column=column_ref.column) for urn in new_urns + ) + column_lineage.append( + ColumnLineageInfo( + downstream=cll.downstream, upstreams=column_refs, logic=cll.logic + ) + ) + lineage.column_lineage = column_lineage + def _add_upstreams_from_m_lineage( self, upstream_lineage: List[ @@ -927,7 +1119,12 @@ def _add_upstreams_from_m_lineage( platform_name = ( upstream_dpt.data_platform_pair.powerbi_data_platform_name ) - if not self.__config.is_platform_in_dataset_type_mapping(platform_name): + if ( + not upstream_dpt.from_fabric_endpoint + and not self.__config.is_platform_in_dataset_type_mapping( + platform_name + ) + ): logger.debug( f"Skipping upstream table for {ds_urn}. The platform {platform_name} is not part of dataset_type_mapping", ) @@ -1066,10 +1263,13 @@ def extract_dataflow_entity_lineage( entity: powerbi_data_classes.DataflowQuery, ds_urn: str, bindings: Dict[str, str], + workspace: powerbi_data_classes.Workspace, ) -> List[MetadataChangeProposalWrapper]: """Upstream lineage of one dataflow entity. *bindings* holds the mashup's parseable queries; wrapping them in one let lets a query - that references another query resolve to that query's source.""" + that references another query resolve to that query's source. + *workspace* supplies the Fabric items a Sql.Database query over an + endpoint host is mapped to, as for semantic-model tables.""" if entity.name not in bindings: return [] table = powerbi_data_classes.Table( @@ -1084,6 +1284,7 @@ def extract_dataflow_entity_lineage( ctx=self.__ctx, config=self.__config, ) + self._resolve_fabric_endpoint_references(upstream_lineage, workspace, ds_urn) upstream: List[UpstreamClass] = [] cll_lineage: List[FineGrainedLineage] = [] # Dataflow entities carry no schema, so there is nothing for a @@ -1161,7 +1362,9 @@ def _dataflow_entity_mcps( ) if self.__config.extract_lineage: mcps.extend( - self.extract_dataflow_entity_lineage(dataflow, entity, ds_urn, bindings) + self.extract_dataflow_entity_lineage( + dataflow, entity, ds_urn, bindings, workspace + ) ) return mcps diff --git a/metadata-ingestion/src/datahub/ingestion/source/powerbi/rest_api_wrapper/data_classes.py b/metadata-ingestion/src/datahub/ingestion/source/powerbi/rest_api_wrapper/data_classes.py index 1a0189430b6b1..6f8671b3dd8a9 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/powerbi/rest_api_wrapper/data_classes.py +++ b/metadata-ingestion/src/datahub/ingestion/source/powerbi/rest_api_wrapper/data_classes.py @@ -3,7 +3,7 @@ import logging from dataclasses import dataclass, field from enum import Enum -from typing import Any, Callable, Dict, List, Literal, Optional, Union +from typing import Any, Callable, Dict, List, Literal, Optional, Set, Union from datahub.emitter.mcp_builder import ContainerKey from datahub.ingestion.source.common.subtypes import BIAssetSubTypes @@ -99,6 +99,9 @@ class Workspace: fabric_artifacts: Dict[str, "FabricArtifact"] = field( default_factory=dict ) # key = artifact id + # Lowercased SQL analytics endpoint hosts of this workspace, read from + # lakehouse properties in workspace_apis mode; empty when unknown. + fabric_sql_endpoint_hosts: Set[str] = field(default_factory=set) # Dataflow Gen2 items; populated only with extract_dataflows in # workspace_apis mode. dataflows: Dict[str, "Dataflow"] = field(default_factory=dict) # key = dataflow id diff --git a/metadata-ingestion/src/datahub/ingestion/source/powerbi/rest_api_wrapper/fabric_resolver.py b/metadata-ingestion/src/datahub/ingestion/source/powerbi/rest_api_wrapper/fabric_resolver.py index b1ac92f59eee9..d57a938a3bb76 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/powerbi/rest_api_wrapper/fabric_resolver.py +++ b/metadata-ingestion/src/datahub/ingestion/source/powerbi/rest_api_wrapper/fabric_resolver.py @@ -68,6 +68,7 @@ KEY_FORMAT = "format" KEY_PROPERTIES = "properties" KEY_SQL_ENDPOINT_PROPERTIES = "sqlEndpointProperties" +KEY_CONNECTION_STRING = "connectionString" KEY_WORKSPACE_ID = "workspaceId" KEY_ERROR = "error" KEY_ERROR_CODE = "errorCode" @@ -107,6 +108,15 @@ def is_unsupported_item_error(e: Exception) -> bool: return False +@dataclass +class LakehouseSqlEndpoint: + """A lakehouse's SQL analytics endpoint: its id and the host clients + connect to (shared by every endpoint of the workspace).""" + + id: str + connection_string: Optional[str] = None + + @dataclass class FabricItem: id: str @@ -273,18 +283,41 @@ def list_items( ) return items - def get_lakehouse_sql_endpoint_id( + def get_lakehouse_sql_endpoint( self, workspace_id: str, lakehouse_id: str - ) -> Optional[str]: - """The SQL analytics endpoint id a DirectLake model's shared expression - points at (``Sql.Database(server, )``).""" + ) -> Optional[LakehouseSqlEndpoint]: + """The SQL analytics endpoint a DirectLake model's shared expression + points at (``Sql.Database(server, )``); None when the + lakehouse reports none yet.""" body = self._get( f"{self._base_url}/workspaces/{workspace_id}/lakehouses/{lakehouse_id}" ) properties = body.get(KEY_PROPERTIES) or {} endpoint = properties.get(KEY_SQL_ENDPOINT_PROPERTIES) or {} endpoint_id = endpoint.get(Constant.ID) - return endpoint_id if isinstance(endpoint_id, str) and endpoint_id else None + if not isinstance(endpoint_id, str) or not endpoint_id: + return None + connection_string = endpoint.get(KEY_CONNECTION_STRING) + return LakehouseSqlEndpoint( + id=endpoint_id, + connection_string=connection_string + if isinstance(connection_string, str) and connection_string + else None, + ) + + def get_warehouse_connection_string( + self, workspace_id: str, warehouse_id: str + ) -> Optional[str]: + """The SQL endpoint host of a warehouse's workspace (every endpoint of + a workspace shares it); None when the properties name none.""" + body = self._get( + f"{self._base_url}/workspaces/{workspace_id}/warehouses/{warehouse_id}" + ) + properties = body.get(KEY_PROPERTIES) or {} + connection_string = properties.get(KEY_CONNECTION_STRING) + if isinstance(connection_string, str) and connection_string: + return connection_string + return None def get_item_definition( self, diff --git a/metadata-ingestion/src/datahub/ingestion/source/powerbi/rest_api_wrapper/powerbi_api.py b/metadata-ingestion/src/datahub/ingestion/source/powerbi/rest_api_wrapper/powerbi_api.py index 51349314eb3d0..628fc02f7a1a7 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/powerbi/rest_api_wrapper/powerbi_api.py +++ b/metadata-ingestion/src/datahub/ingestion/source/powerbi/rest_api_wrapper/powerbi_api.py @@ -85,6 +85,7 @@ FabricItem, FabricLroTimeoutError, ItemDefinition, + LakehouseSqlEndpoint, is_unsupported_item_error, ) from datahub.ingestion.source.powerbi.rest_api_wrapper.report_definition_parser import ( @@ -1626,11 +1627,18 @@ def _fabric_artifacts_from_items( ) -> Dict[str, FabricArtifact]: """Lakehouse / Warehouse items plus their SQL analytics endpoints. - A DirectLake model's shared expression names the SQL endpoint id, not - the lakehouse, so each endpoint is registered as a SQLAnalyticsEndpoint + A DirectLake model's shared expression (and a ``Sql.Database`` query + over the endpoint host) names the SQL endpoint id, not the lakehouse, + so each lakehouse endpoint is registered as a SQLAnalyticsEndpoint artifact whose physical_item_ids point at the lakehouse; the existing DirectLake lineage path then resolves it exactly as it does for scan - results. A warehouse's endpoint id is the warehouse id itself. + results. A warehouse's endpoint id is the warehouse id itself, so the + Warehouse artifact doubles as its endpoint, as in scan results. + + Datamarts, mirrored databases and SQL databases are left out on + purpose: the OneLake connector does not ingest their tables, so an + edge to them would point at a dataset that does not exist (a datamart + also exposes no endpoint id to a service principal). """ artifacts: Dict[str, FabricArtifact] = {} for item in items: @@ -1641,10 +1649,15 @@ def _fabric_artifacts_from_items( artifact_type=FABRIC_ARTIFACT_LAKEHOUSE, workspace_id=workspace.id, ) - endpoint_id = self._lakehouse_sql_endpoint_id(workspace, item) - if endpoint_id: - artifacts[endpoint_id] = FabricArtifact( - id=endpoint_id, + endpoint = self._lakehouse_sql_endpoint(workspace, item) + if endpoint is not None: + self.reporter.fabric_lakehouse_endpoints_registered += 1 + if endpoint.connection_string: + workspace.fabric_sql_endpoint_hosts.add( + endpoint.connection_string.strip().lower() + ) + artifacts[endpoint.id] = FabricArtifact( + id=endpoint.id, name=item.display_name, artifact_type=FABRIC_ARTIFACT_SQL_ANALYTICS_ENDPOINT, workspace_id=workspace.id, @@ -1652,12 +1665,14 @@ def _fabric_artifacts_from_items( physical_item_ids=[item.id], ) elif item.type == FABRIC_ITEM_WAREHOUSE: + self.reporter.fabric_warehouse_endpoints_registered += 1 artifacts[item.id] = FabricArtifact( id=item.id, name=item.display_name, artifact_type=FABRIC_ARTIFACT_WAREHOUSE, workspace_id=workspace.id, ) + self._record_warehouse_endpoint_host(workspace, items) for item in items: if item.type == FABRIC_ITEM_SQL_ENDPOINT and item.id not in artifacts: # Endpoint whose lakehouse is not in this workspace listing (or @@ -1670,24 +1685,63 @@ def _fabric_artifacts_from_items( ) return artifacts - def _lakehouse_sql_endpoint_id( + def _record_warehouse_endpoint_host( + self, workspace: Workspace, items: List[FabricItem] + ) -> None: + """Every endpoint of a workspace shares one host, so a lakehouse's + already recorded it; a workspace with only warehouses needs one + warehouse properties call. Without a host, Sql.Database queries that + name an item by display name match on any host, as before.""" + if workspace.fabric_sql_endpoint_hosts: + return + warehouse = next((i for i in items if i.type == FABRIC_ITEM_WAREHOUSE), None) + if warehouse is None: + return + try: + host = self._require_fabric_resolver().get_warehouse_connection_string( + workspace_id=workspace.id, warehouse_id=warehouse.id + ) + except Exception as e: + self.log_http_error( + message=f"Unable to fetch warehouse {warehouse.id} properties" + ) + self.reporter.warning( + title="Fabric Endpoint Host Unknown", + message="Warehouse properties could not be fetched, so Sql.Database queries that name an item by display name are matched without checking the endpoint host; a query on another workspace's endpoint naming a same-named item may link to this workspace's item.", + context=f"workspace={workspace.name}, warehouse={warehouse.display_name} id={warehouse.id}", + exc=e, + ) + return + if host: + workspace.fabric_sql_endpoint_hosts.add(host.strip().lower()) + + def _lakehouse_sql_endpoint( self, workspace: Workspace, item: FabricItem - ) -> Optional[str]: + ) -> Optional[LakehouseSqlEndpoint]: try: - return self._require_fabric_resolver().get_lakehouse_sql_endpoint_id( + endpoint = self._require_fabric_resolver().get_lakehouse_sql_endpoint( workspace_id=workspace.id, lakehouse_id=item.id ) except Exception as e: self.log_http_error( message=f"Unable to fetch lakehouse {item.id} properties" ) + self.reporter.fabric_lakehouse_endpoints_unresolved += 1 self.reporter.warning( - title="Lakehouse SQL Endpoint Not Resolved", - message="Lakehouse properties could not be fetched; DirectLake tables over it will have no lineage.", + title="Fabric Endpoint Not Resolved", + message="Lakehouse properties could not be fetched, so its SQL analytics endpoint id is unknown; DirectLake tables and Sql.Database queries that name the endpoint by id will have no OneLake lineage (queries that name the lakehouse by display name still resolve).", context=f"workspace={workspace.name}, lakehouse={item.display_name} id={item.id}", exc=e, ) return None + if endpoint is None: + self.reporter.fabric_lakehouse_endpoints_unresolved += 1 + self.reporter.warning( + title="Fabric Endpoint Not Resolved", + message="Lakehouse properties name no SQL analytics endpoint (it may still be provisioning); DirectLake tables and Sql.Database queries that name the endpoint by id will have no OneLake lineage.", + context=f"workspace={workspace.name}, lakehouse={item.display_name} id={item.id}", + ) + return endpoint @staticmethod def _entity_partition_source( diff --git a/metadata-ingestion/tests/integration/powerbi/golden_test_workspace_apis_field_usage.json b/metadata-ingestion/tests/integration/powerbi/golden_test_workspace_apis_field_usage.json index f455ad670144c..2c1a4e3a49824 100644 --- a/metadata-ingestion/tests/integration/powerbi/golden_test_workspace_apis_field_usage.json +++ b/metadata-ingestion/tests/integration/powerbi/golden_test_workspace_apis_field_usage.json @@ -3640,6 +3640,406 @@ "lastRunId": "no-run-id-provided" } }, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "viewProperties", + "aspect": { + "json": { + "materialized": false, + "viewLogic": "let\n Source = Sql.Database(\"my-fabric-endpoint.datawarehouse.fabric.microsoft.com\", \"Claims_Warehouse\"),\n dbo_claims_by_state = Source{[Schema=\"dbo\",Item=\"claims_by_state\"]}[Data]\nin\n dbo_claims_by_state", + "viewLanguage": "m_query" + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "schemaMetadata", + "aspect": { + "json": { + "schemaName": "claims_by_state", + "platform": "urn:li:dataPlatform:powerbi", + "version": 0, + "created": { + "time": 0, + "actor": "urn:li:corpuser:unknown" + }, + "lastModified": { + "time": 0, + "actor": "urn:li:corpuser:unknown" + }, + "hash": "", + "platformSchema": { + "com.linkedin.schema.OtherSchema": { + "rawSchema": "" + } + }, + "fields": [ + { + "fieldPath": "state", + "nullable": false, + "type": { + "type": { + "com.linkedin.schema.StringType": {} + } + }, + "nativeDataType": "String", + "recursive": false, + "isPartOfKey": false + }, + { + "fieldPath": "claim_count", + "nullable": false, + "type": { + "type": { + "com.linkedin.schema.NumberType": {} + } + }, + "nativeDataType": "Int64", + "recursive": false, + "isPartOfKey": false + } + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "datasetProperties", + "aspect": { + "json": { + "customProperties": { + "datasetId": "2B3C4D5E-6F7A-4B8C-9D0E-1F2A3B4C5D6E" + }, + "externalUrl": "https://app.powerbi.com/groups/64ED5CAD-7C10-4684-8180-826122881108/datasets/2B3C4D5E-6F7A-4B8C-9D0E-1F2A3B4C5D6E/details", + "name": "claims_by_state", + "description": "Import table read from the warehouse through its SQL analytics endpoint.", + "tags": [] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "status", + "aspect": { + "json": { + "removed": false + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "subTypes", + "aspect": { + "json": { + "typeNames": [ + "Table" + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "dataPlatformInstance", + "aspect": { + "json": { + "platform": "urn:li:dataPlatform:powerbi" + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "upstreamLineage", + "aspect": { + "json": { + "upstreams": [ + { + "auditStamp": { + "time": 0, + "actor": "urn:li:corpuser:unknown" + }, + "dataset": "urn:li:dataset:(urn:li:dataPlatform:fabric-onelake,64ed5cad-7c10-4684-8180-826122881108.9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d.dbo.claims_by_state,PROD)", + "type": "TRANSFORMED" + } + ], + "fineGrainedLineages": [ + { + "upstreamType": "FIELD_SET", + "upstreams": [ + "urn:li:schemaField:(urn:li:dataset:(urn:li:dataPlatform:fabric-onelake,64ed5cad-7c10-4684-8180-826122881108.9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d.dbo.claims_by_state,PROD),state)" + ], + "downstreamType": "FIELD", + "downstreams": [ + "urn:li:schemaField:(urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV),state)" + ], + "confidenceScore": 1.0 + }, + { + "upstreamType": "FIELD_SET", + "upstreams": [ + "urn:li:schemaField:(urn:li:dataset:(urn:li:dataPlatform:fabric-onelake,64ed5cad-7c10-4684-8180-826122881108.9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d.dbo.claims_by_state,PROD),claim_count)" + ], + "downstreamType": "FIELD", + "downstreams": [ + "urn:li:schemaField:(urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV),claim_count)" + ], + "confidenceScore": 1.0 + } + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "browsePathsV2", + "aspect": { + "json": { + "path": [ + { + "id": "demo-workspace", + "urn": "urn:li:container:a4ed52f9abd3ff9cc34960c0c41f72e9" + }, + { + "id": "Policy Warehouse Model" + } + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "schemaMetadata", + "aspect": { + "json": { + "schemaName": "policy_summary", + "platform": "urn:li:dataPlatform:powerbi", + "version": 0, + "created": { + "time": 0, + "actor": "urn:li:corpuser:unknown" + }, + "lastModified": { + "time": 0, + "actor": "urn:li:corpuser:unknown" + }, + "hash": "", + "platformSchema": { + "com.linkedin.schema.OtherSchema": { + "rawSchema": "" + } + }, + "fields": [ + { + "fieldPath": "policy_id", + "nullable": false, + "type": { + "type": { + "com.linkedin.schema.NumberType": {} + } + }, + "nativeDataType": "Int64", + "recursive": false, + "isPartOfKey": false + }, + { + "fieldPath": "premium", + "nullable": false, + "type": { + "type": { + "com.linkedin.schema.NumberType": {} + } + }, + "nativeDataType": "Double", + "recursive": false, + "isPartOfKey": false + } + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "datasetProperties", + "aspect": { + "json": { + "customProperties": { + "datasetId": "2B3C4D5E-6F7A-4B8C-9D0E-1F2A3B4C5D6E" + }, + "externalUrl": "https://app.powerbi.com/groups/64ED5CAD-7C10-4684-8180-826122881108/datasets/2B3C4D5E-6F7A-4B8C-9D0E-1F2A3B4C5D6E/details", + "name": "policy_summary", + "description": "DirectLake table over the warehouse 'policy_summary' table.", + "tags": [] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "status", + "aspect": { + "json": { + "removed": false + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "subTypes", + "aspect": { + "json": { + "typeNames": [ + "Table" + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "dataPlatformInstance", + "aspect": { + "json": { + "platform": "urn:li:dataPlatform:powerbi" + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "upstreamLineage", + "aspect": { + "json": { + "upstreams": [ + { + "auditStamp": { + "time": 0, + "actor": "urn:li:corpuser:unknown" + }, + "dataset": "urn:li:dataset:(urn:li:dataPlatform:fabric-onelake,64ed5cad-7c10-4684-8180-826122881108.9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d.dbo.policy_summary,PROD)", + "type": "TRANSFORMED" + } + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "browsePathsV2", + "aspect": { + "json": { + "path": [ + { + "id": "demo-workspace", + "urn": "urn:li:container:a4ed52f9abd3ff9cc34960c0c41f72e9" + }, + { + "id": "Policy Warehouse Model" + } + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, { "entityType": "dashboard", "entityUrn": "urn:li:dashboard:(powerbi,dashboards.7D668CAD-8FFC-4505-9215-655BCA5BEBAE)", diff --git a/metadata-ingestion/tests/integration/powerbi/golden_test_workspace_apis_ingest.json b/metadata-ingestion/tests/integration/powerbi/golden_test_workspace_apis_ingest.json index a8c9f31c76937..bbb3e6bd73135 100644 --- a/metadata-ingestion/tests/integration/powerbi/golden_test_workspace_apis_ingest.json +++ b/metadata-ingestion/tests/integration/powerbi/golden_test_workspace_apis_ingest.json @@ -5643,6 +5643,412 @@ "lastRunId": "no-run-id-provided" } }, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "viewProperties", + "aspect": { + "json": { + "materialized": false, + "viewLogic": "let\n Source = Sql.Database(\"my-fabric-endpoint.datawarehouse.fabric.microsoft.com\", \"Claims_Warehouse\"),\n dbo_claims_by_state = Source{[Schema=\"dbo\",Item=\"claims_by_state\"]}[Data]\nin\n dbo_claims_by_state", + "viewLanguage": "m_query" + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "schemaMetadata", + "aspect": { + "json": { + "schemaName": "claims_by_state", + "platform": "urn:li:dataPlatform:powerbi", + "version": 0, + "created": { + "time": 0, + "actor": "urn:li:corpuser:unknown" + }, + "lastModified": { + "time": 0, + "actor": "urn:li:corpuser:unknown" + }, + "hash": "", + "platformSchema": { + "com.linkedin.schema.OtherSchema": { + "rawSchema": "" + } + }, + "fields": [ + { + "fieldPath": "state", + "nullable": false, + "type": { + "type": { + "com.linkedin.schema.StringType": {} + } + }, + "nativeDataType": "String", + "recursive": false, + "isPartOfKey": false + }, + { + "fieldPath": "claim_count", + "nullable": false, + "type": { + "type": { + "com.linkedin.schema.NumberType": {} + } + }, + "nativeDataType": "Int64", + "recursive": false, + "isPartOfKey": false, + "jsonProps": "{\"summarizeBy\": \"sum\"}" + } + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "datasetProperties", + "aspect": { + "json": { + "customProperties": { + "datasetId": "2B3C4D5E-6F7A-4B8C-9D0E-1F2A3B4C5D6E", + "storageMode": "Import", + "partitionCount": "1" + }, + "externalUrl": "https://app.powerbi.com/groups/64ED5CAD-7C10-4684-8180-826122881108/datasets/2B3C4D5E-6F7A-4B8C-9D0E-1F2A3B4C5D6E/details", + "name": "claims_by_state", + "description": "Import table read from the warehouse through its SQL analytics endpoint.", + "tags": [] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "status", + "aspect": { + "json": { + "removed": false + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "subTypes", + "aspect": { + "json": { + "typeNames": [ + "Table" + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "dataPlatformInstance", + "aspect": { + "json": { + "platform": "urn:li:dataPlatform:powerbi" + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "upstreamLineage", + "aspect": { + "json": { + "upstreams": [ + { + "auditStamp": { + "time": 0, + "actor": "urn:li:corpuser:unknown" + }, + "dataset": "urn:li:dataset:(urn:li:dataPlatform:fabric-onelake,64ed5cad-7c10-4684-8180-826122881108.9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d.dbo.claims_by_state,PROD)", + "type": "TRANSFORMED" + } + ], + "fineGrainedLineages": [ + { + "upstreamType": "FIELD_SET", + "upstreams": [ + "urn:li:schemaField:(urn:li:dataset:(urn:li:dataPlatform:fabric-onelake,64ed5cad-7c10-4684-8180-826122881108.9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d.dbo.claims_by_state,PROD),state)" + ], + "downstreamType": "FIELD", + "downstreams": [ + "urn:li:schemaField:(urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV),state)" + ], + "confidenceScore": 1.0 + }, + { + "upstreamType": "FIELD_SET", + "upstreams": [ + "urn:li:schemaField:(urn:li:dataset:(urn:li:dataPlatform:fabric-onelake,64ed5cad-7c10-4684-8180-826122881108.9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d.dbo.claims_by_state,PROD),claim_count)" + ], + "downstreamType": "FIELD", + "downstreams": [ + "urn:li:schemaField:(urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV),claim_count)" + ], + "confidenceScore": 1.0 + } + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.claims_by_state,DEV)", + "changeType": "UPSERT", + "aspectName": "browsePathsV2", + "aspect": { + "json": { + "path": [ + { + "id": "demo-workspace", + "urn": "urn:li:container:a4ed52f9abd3ff9cc34960c0c41f72e9" + }, + { + "id": "Policy Warehouse Model" + } + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "schemaMetadata", + "aspect": { + "json": { + "schemaName": "policy_summary", + "platform": "urn:li:dataPlatform:powerbi", + "version": 0, + "created": { + "time": 0, + "actor": "urn:li:corpuser:unknown" + }, + "lastModified": { + "time": 0, + "actor": "urn:li:corpuser:unknown" + }, + "hash": "", + "platformSchema": { + "com.linkedin.schema.OtherSchema": { + "rawSchema": "" + } + }, + "fields": [ + { + "fieldPath": "policy_id", + "nullable": false, + "type": { + "type": { + "com.linkedin.schema.NumberType": {} + } + }, + "nativeDataType": "Int64", + "recursive": false, + "isPartOfKey": false + }, + { + "fieldPath": "premium", + "nullable": false, + "type": { + "type": { + "com.linkedin.schema.NumberType": {} + } + }, + "nativeDataType": "Double", + "recursive": false, + "isPartOfKey": false, + "jsonProps": "{\"summarizeBy\": \"sum\"}" + } + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "datasetProperties", + "aspect": { + "json": { + "customProperties": { + "datasetId": "2B3C4D5E-6F7A-4B8C-9D0E-1F2A3B4C5D6E", + "storageMode": "DirectLake", + "partitionCount": "1" + }, + "externalUrl": "https://app.powerbi.com/groups/64ED5CAD-7C10-4684-8180-826122881108/datasets/2B3C4D5E-6F7A-4B8C-9D0E-1F2A3B4C5D6E/details", + "name": "policy_summary", + "description": "DirectLake table over the warehouse 'policy_summary' table.", + "tags": [] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "status", + "aspect": { + "json": { + "removed": false + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "subTypes", + "aspect": { + "json": { + "typeNames": [ + "Table" + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "dataPlatformInstance", + "aspect": { + "json": { + "platform": "urn:li:dataPlatform:powerbi" + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "upstreamLineage", + "aspect": { + "json": { + "upstreams": [ + { + "auditStamp": { + "time": 0, + "actor": "urn:li:corpuser:unknown" + }, + "dataset": "urn:li:dataset:(urn:li:dataPlatform:fabric-onelake,64ed5cad-7c10-4684-8180-826122881108.9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d.dbo.policy_summary,PROD)", + "type": "TRANSFORMED" + } + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, +{ + "entityType": "dataset", + "entityUrn": "urn:li:dataset:(urn:li:dataPlatform:powerbi,Policy_Warehouse_Model.policy_summary,DEV)", + "changeType": "UPSERT", + "aspectName": "browsePathsV2", + "aspect": { + "json": { + "path": [ + { + "id": "demo-workspace", + "urn": "urn:li:container:a4ed52f9abd3ff9cc34960c0c41f72e9" + }, + { + "id": "Policy Warehouse Model" + } + ] + } + }, + "systemMetadata": { + "lastObserved": 1643871600000, + "runId": "powerbi-test", + "lastRunId": "no-run-id-provided" + } +}, { "entityType": "dashboard", "entityUrn": "urn:li:dashboard:(powerbi,dashboards.7D668CAD-8FFC-4505-9215-655BCA5BEBAE)", diff --git a/metadata-ingestion/tests/integration/powerbi/mock_data/fabric_definitions/warehouse_model/definition/expressions.tmdl b/metadata-ingestion/tests/integration/powerbi/mock_data/fabric_definitions/warehouse_model/definition/expressions.tmdl new file mode 100644 index 0000000000000..f571b5e3b2632 --- /dev/null +++ b/metadata-ingestion/tests/integration/powerbi/mock_data/fabric_definitions/warehouse_model/definition/expressions.tmdl @@ -0,0 +1,8 @@ +expression WarehouseQuery = + let + database = Sql.Database("my-fabric-endpoint.datawarehouse.fabric.microsoft.com", "9A8B7C6D-5E4F-4A3B-8C2D-1E0F9A8B7C6D") + in + database + lineageTag: 00000020-1111-4222-8333-000000000020 + + annotation PBI_IncludeFutureArtifacts = False diff --git a/metadata-ingestion/tests/integration/powerbi/mock_data/fabric_definitions/warehouse_model/definition/tables/claims_by_state.tmdl b/metadata-ingestion/tests/integration/powerbi/mock_data/fabric_definitions/warehouse_model/definition/tables/claims_by_state.tmdl new file mode 100644 index 0000000000000..c249fef11cc50 --- /dev/null +++ b/metadata-ingestion/tests/integration/powerbi/mock_data/fabric_definitions/warehouse_model/definition/tables/claims_by_state.tmdl @@ -0,0 +1,24 @@ +/// Import table read from the warehouse through its SQL analytics endpoint. +table claims_by_state + lineageTag: 00000024-1111-4222-8333-000000000024 + + column state + dataType: string + lineageTag: 00000025-1111-4222-8333-000000000025 + summarizeBy: none + sourceColumn: state + + column claim_count + dataType: int64 + lineageTag: 00000026-1111-4222-8333-000000000026 + summarizeBy: sum + sourceColumn: claim_count + + partition claims_by_state = m + mode: import + source = + let + Source = Sql.Database("my-fabric-endpoint.datawarehouse.fabric.microsoft.com", "Claims_Warehouse"), + dbo_claims_by_state = Source{[Schema="dbo",Item="claims_by_state"]}[Data] + in + dbo_claims_by_state diff --git a/metadata-ingestion/tests/integration/powerbi/mock_data/fabric_definitions/warehouse_model/definition/tables/policy_summary.tmdl b/metadata-ingestion/tests/integration/powerbi/mock_data/fabric_definitions/warehouse_model/definition/tables/policy_summary.tmdl new file mode 100644 index 0000000000000..1f500bdd044e9 --- /dev/null +++ b/metadata-ingestion/tests/integration/powerbi/mock_data/fabric_definitions/warehouse_model/definition/tables/policy_summary.tmdl @@ -0,0 +1,27 @@ +/// DirectLake table over the warehouse 'policy_summary' table. +table policy_summary + lineageTag: 00000021-1111-4222-8333-000000000021 + sourceLineageTag: [dbo].[policy_summary] + + column policy_id + dataType: int64 + sourceProviderType: bigint + lineageTag: 00000022-1111-4222-8333-000000000022 + sourceLineageTag: policy_id + summarizeBy: none + sourceColumn: policy_id + + column premium + dataType: double + sourceProviderType: float + lineageTag: 00000023-1111-4222-8333-000000000023 + sourceLineageTag: premium + summarizeBy: sum + sourceColumn: premium + + partition policy_summary = entity + mode: directLake + source + entityName: policy_summary + schemaName: dbo + expressionSource: WarehouseQuery diff --git a/metadata-ingestion/tests/integration/powerbi/test_workspace_apis_mode.py b/metadata-ingestion/tests/integration/powerbi/test_workspace_apis_mode.py index cedffb62e86b2..39c95146aadc8 100644 --- a/metadata-ingestion/tests/integration/powerbi/test_workspace_apis_mode.py +++ b/metadata-ingestion/tests/integration/powerbi/test_workspace_apis_mode.py @@ -37,6 +37,10 @@ DIRECTLAKE_MODEL_ID = "7A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D" LAKEHOUSE_ID = "3C4D5E6F-7A8B-4C9D-8E0F-1A2B3C4D5E6F" SQL_ENDPOINT_ID = "6F2E7D8C-9B0A-4C1D-8E2F-3A4B5C6D7E8F" +# Its SQL analytics endpoint id is the warehouse id; the warehouse model's +# shared expression names it by id, its import table by display name. +WAREHOUSE_ID = "9A8B7C6D-5E4F-4A3B-8C2D-1E0F9A8B7C6D" +WAREHOUSE_MODEL_ID = "2B3C4D5E-6F7A-4B8C-9D0E-1F2A3B4C5D6E" REPORT_ID = "584cf13a-1485-41c2-a514-b1bb66fff163" # Second workspace of the default group listing; it hosts a composite model # whose remote tables read the first workspace's Insurance Model. @@ -97,6 +101,11 @@ def workspace_apis_mock_data(fixtures: Path) -> Dict[str, Dict[str, Any]]: "name": "Claims DirectLake Model", "configuredBy": "User1@foo.com", }, + { + "id": WAREHOUSE_MODEL_ID, + "name": "Policy Warehouse Model", + "configuredBy": "User1@foo.com", + }, ] }, }, @@ -105,6 +114,21 @@ def workspace_apis_mock_data(fixtures: Path) -> Dict[str, Dict[str, Any]]: "status_code": 200, "json": {"value": []}, }, + f"{PBI}/groups/{WORKSPACE_ID}/datasets/{WAREHOUSE_MODEL_ID}/parameters": { + "method": "GET", + "status_code": 200, + "json": {"value": []}, + }, + f"{PBI}/groups/{WORKSPACE_ID}/datasets/{WAREHOUSE_MODEL_ID}/refreshes": { + "method": "GET", + "status_code": 200, + "json": {"value": []}, + }, + f"{PBI}/groups/{WORKSPACE_ID}/datasets/{WAREHOUSE_MODEL_ID}/refreshSchedule": { + "method": "GET", + "status_code": 404, + "json": {"error": {"code": "ItemNotFound"}}, + }, f"{PBI}/groups/{WORKSPACE_ID}/datasets/{IMPORT_MODEL_ID}/refreshes": { "method": "GET", "status_code": 200, @@ -251,6 +275,18 @@ def workspace_apis_mock_data(fixtures: Path) -> Dict[str, Dict[str, Any]]: "displayName": "Claims DirectLake Model", "workspaceId": WORKSPACE_ID, }, + { + "id": WAREHOUSE_ID, + "type": "Warehouse", + "displayName": "Claims_Warehouse", + "workspaceId": WORKSPACE_ID, + }, + { + "id": WAREHOUSE_MODEL_ID, + "type": "SemanticModel", + "displayName": "Policy Warehouse Model", + "workspaceId": WORKSPACE_ID, + }, { "id": REPORT_ID, "type": "Report", @@ -287,6 +323,13 @@ def workspace_apis_mock_data(fixtures: Path) -> Dict[str, Dict[str, Any]]: "status_code": 200, "json": definition_response(fixtures / "insurance_model", "TMDL"), }, + # A warehouse is its own SQL analytics endpoint: no properties call + # is made for it, so none is mocked. + f"{FABRIC}/workspaces/{WORKSPACE_ID}/semanticModels/{WAREHOUSE_MODEL_ID}/getDefinition": { + "method": "POST", + "status_code": 200, + "json": definition_response(fixtures / "warehouse_model", "TMDL"), + }, f"{FABRIC}/workspaces/{WORKSPACE_ID}/reports/{REPORT_ID}/getDefinition": { "method": "POST", "status_code": 200, @@ -495,10 +538,18 @@ def test_workspace_apis_ingest_with_enrichment( report = pipeline.source.get_report() assert isinstance(report, PowerBiDashboardSourceReport) - assert report.fabric_definitions_fetched == 4 # three models + one report + assert report.fabric_definitions_fetched == 5 # four models + one report assert report.fabric_definitions_failed == 0 - assert report.tmdl_tables_parsed == 9 + assert report.tmdl_tables_parsed == 11 assert report.relationships_parsed == 2 + assert report.fabric_lakehouse_endpoints_registered == 1 + assert report.fabric_warehouse_endpoints_registered == 1 + # The warehouse model's import table reads the warehouse endpoint by + # display name; its DirectLake table goes through the shared expression. + assert report.fabric_endpoint_references_resolved == 1 + assert report.fabric_endpoint_references_unresolved == 0 + assert report.fabric_lakehouse_endpoints_unresolved == 0 + assert report.fabric_endpoint_m_shapes_unsupported == 0 assert report.dataflow_definitions_fetched == 1 assert report.dataflows_fetched == 1 assert report.dataflow_entities_parsed == 2 @@ -514,8 +565,9 @@ def test_workspace_apis_ingest_with_enrichment( assert report.dataset_parameters_emitted == 2 # Fields with at least one non-default property; `summarizeBy: none` and # bare calculated columns do not count. 16 in the insurance model (one on - # its dataflow-backed table) plus 5 in the composite executive model. - assert report.model_fields_with_properties == 21 + # its dataflow-backed table), 5 in the composite executive model and 2 in + # the warehouse model. + assert report.model_fields_with_properties == 23 assert report.rls_filters_unresolved == 0 with open(output_path) as f: mcps = json.load(f) @@ -550,7 +602,8 @@ def test_workspace_apis_ingest_with_enrichment( # fail on `NotInModel[Ghost]` once more. assert report.report_visual_field_references_resolved == 8 assert report.report_visual_field_references_unresolved == 1 - assert report.refresh_history_fetched == 3 + # The warehouse model's refresh listing is empty but still fetched. + assert report.refresh_history_fetched == 4 # Only the fixture's `'Budget'[Amount]` points outside the model; it is # counted once although its dataset is mapped twice (workspace, report). assert report.dax_references_unresolved == 1 @@ -595,8 +648,8 @@ def test_workspace_apis_ingest_with_enrichment( assert report.datasets_not_refreshable == 0 assert report.refresh_schedule_fetched == 1 assert report.refresh_schedule_not_supported == 0 - # The DirectLake and the composite model have no schedule. - assert report.refresh_schedule_not_configured == 2 + # The DirectLake, composite and warehouse models have no schedule. + assert report.refresh_schedule_not_configured == 3 assert report.refresh_schedule_failed == 0 # One report-level, one page-level and two visual-level filters. assert report.report_filters_parsed == 4 @@ -798,7 +851,8 @@ def test_forbidden_model_fails_run_but_keeps_other_models( report = pipeline.source.get_report() assert isinstance(report, PowerBiDashboardSourceReport) assert report.fabric_definitions_failed == 1 - assert report.fabric_definitions_fetched == 2 + # import + warehouse models, plus the second workspace's composite model + assert report.fabric_definitions_fetched == 3 # A 403 zeroes out that model's tables, so the run is red, not green. assert [f.title for f in report.failures] == ["Fabric API Permission Denied"] diff --git a/metadata-ingestion/tests/unit/powerbi/test_fabric_endpoint_lineage.py b/metadata-ingestion/tests/unit/powerbi/test_fabric_endpoint_lineage.py new file mode 100644 index 0000000000000..95705305f4ae1 --- /dev/null +++ b/metadata-ingestion/tests/unit/powerbi/test_fabric_endpoint_lineage.py @@ -0,0 +1,532 @@ +"""Sql.Database queries over a Fabric SQL analytics endpoint host resolve to +the OneLake table behind the endpoint (Mapper.extract_lineage).""" + +from typing import Any, Dict, List, Optional + +from datahub.ingestion.api.common import PipelineContext +from datahub.ingestion.source.powerbi.config import ( + PowerBiDashboardSourceConfig, + PowerBiDashboardSourceReport, +) +from datahub.ingestion.source.powerbi.dataplatform_instance_resolver import ( + create_dataplatform_instance_resolver, +) +from datahub.ingestion.source.powerbi.m_query.pattern_handler import ( + FABRIC_SQL_ENDPOINT_HOST_SUFFIX, +) +from datahub.ingestion.source.powerbi.powerbi import Mapper +from datahub.ingestion.source.powerbi.rest_api_wrapper.data_classes import ( + Column, + Dataflow, + DataflowQuery, + FabricArtifact, + PowerBIDataset, + Table, + Workspace, +) +from datahub.metadata.schema_classes import StringTypeClass, UpstreamLineageClass + +WORKSPACE_ID = "ff23fbe3-7418-42f8-a675-9f10eb2b78cb" +WAREHOUSE_ID = "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d" +LAKEHOUSE_ID = "3c4d5e6f-7a8b-4c9d-8e0f-1a2b3c4d5e6f" +SQL_ENDPOINT_ID = "6f2e7d8c-9b0a-4c1d-8e2f-3a4b5c6d7e8f" +ENDPOINT_HOST = f"my-fabric-endpoint{FABRIC_SQL_ENDPOINT_HOST_SUFFIX}" +DS_URN = ( + "urn:li:dataset:(urn:li:dataPlatform:powerbi,TestWorkspace.TestDataset.claims,PROD)" +) +NAVIGATION = 'Source{[Schema="dbo",Item="claims"]}[Data]' + + +def _m_query( + server: str, + database: str, + navigation: str = NAVIGATION, + record: str = "", +) -> str: + return ( + "let\n" + f' Source = Sql.Database("{server}", "{database}"{record}),\n' + f" dbo_claims = {navigation}\n" + "in\n" + " dbo_claims" + ) + + +def _mapper(**config_overrides: Any) -> Mapper: + config = PowerBiDashboardSourceConfig( + tenant_id="test-tenant-id", + client_id="test-client-id", + client_secret="test-client-secret", + extract_lineage=True, + extract_column_level_lineage=True, + **config_overrides, + ) + return Mapper( + ctx=PipelineContext(run_id="test-run-id"), + config=config, + reporter=PowerBiDashboardSourceReport(), + dataplatform_instance_resolver=create_dataplatform_instance_resolver(config), + ) + + +def _report(mapper: Mapper) -> PowerBiDashboardSourceReport: + return mapper._Mapper__reporter # type: ignore[attr-defined] + + +def _workspace(artifacts: Optional[List[FabricArtifact]] = None) -> Workspace: + return Workspace( + id=WORKSPACE_ID, + name="TestWorkspace", + type="Workspace", + webUrl=None, + datasets={}, + dashboards={}, + reports={}, + report_endorsements={}, + dashboard_endorsements={}, + scan_result={}, + independent_datasets={}, + app=None, + fabric_artifacts={a.id: a for a in artifacts or []}, + ) + + +def _warehouse( + item_id: str = WAREHOUSE_ID, name: str = "Claims_Warehouse" +) -> FabricArtifact: + return FabricArtifact( + id=item_id, + name=name, + artifact_type="Warehouse", + workspace_id=WORKSPACE_ID, + ) + + +def _lakehouse_with_endpoint(name: str = "Claims_Lakehouse") -> List[FabricArtifact]: + return [ + FabricArtifact( + id=LAKEHOUSE_ID, + name=name, + artifact_type="Lakehouse", + workspace_id=WORKSPACE_ID, + ), + FabricArtifact( + id=SQL_ENDPOINT_ID, + name=name, + artifact_type="SQLAnalyticsEndpoint", + workspace_id=WORKSPACE_ID, + physical_item_ids=[LAKEHOUSE_ID], + ), + ] + + +def _table(expression: str) -> Table: + dataset = PowerBIDataset( + id="ds-123", + name="TestDataset", + description="Test dataset", + webUrl=None, + workspace_id=WORKSPACE_ID, + workspace_name="TestWorkspace", + parameters={}, + tables=[], + tags=[], + configuredBy=None, + ) + table = Table( + name="claims", + full_name="TestWorkspace.TestDataset.claims", + expression=expression, + storage_mode="Import", + columns=[ + Column( + name="claim_id", + dataType="String", + isHidden=False, + datahubDataType=StringTypeClass(), + ) + ], + ) + table.dataset = dataset + return table + + +def _lineage(mapper: Mapper, workspace: Workspace, expression: str) -> Dict[str, Any]: + mcps = mapper.extract_lineage(_table(expression), DS_URN, workspace) + if not mcps: + return {"upstreams": [], "column_upstreams": []} + assert len(mcps) == 1 + aspect = mcps[0].aspect + assert isinstance(aspect, UpstreamLineageClass) + return { + "upstreams": [u.dataset for u in aspect.upstreams], + "column_upstreams": [ + u for f in aspect.fineGrainedLineages or [] for u in f.upstreams or [] + ], + } + + +def _onelake_urn( + item_id: str, + platform_instance: str = "", + env: str = "PROD", + table: str = "dbo.claims", +) -> str: + prefix = f"{platform_instance}." if platform_instance else "" + return f"urn:li:dataset:(urn:li:dataPlatform:fabric-onelake,{prefix}{WORKSPACE_ID}.{item_id}.{table},{env})" + + +MSSQL_OTHER = ( + "urn:li:dataset:(urn:li:dataPlatform:mssql,other_lakehouse.dbo.claims,PROD)" +) + + +def test_warehouse_endpoint_by_id_resolves_to_onelake_table() -> None: + mapper = _mapper() + lineage = _lineage( + mapper, _workspace([_warehouse()]), _m_query(ENDPOINT_HOST, WAREHOUSE_ID) + ) + + assert lineage["upstreams"] == [_onelake_urn(WAREHOUSE_ID)] + assert lineage["column_upstreams"] == [ + f"urn:li:schemaField:({_onelake_urn(WAREHOUSE_ID)},claim_id)" + ] + report = _report(mapper) + assert report.fabric_endpoint_references_resolved == 1 + assert report.fabric_endpoint_references_unresolved == 0 + assert report.warnings == [] + + +def test_lakehouse_endpoint_by_display_name_resolves_to_lakehouse_table() -> None: + mapper = _mapper() + # Power BI Desktop writes the item's display name as the database; the + # endpoint artifact maps it back to the lakehouse the OneLake URN needs. + lineage = _lineage( + mapper, + _workspace(_lakehouse_with_endpoint()), + _m_query(ENDPOINT_HOST, "claims_lakehouse"), + ) + + assert lineage["upstreams"] == [_onelake_urn(LAKEHOUSE_ID)] + report = _report(mapper) + assert report.fabric_endpoint_references_resolved == 1 + assert report.fabric_endpoint_references_unresolved == 0 + assert report.fabric_endpoint_references_ambiguous == 0 + assert report.fabric_endpoint_m_shapes_unsupported == 0 + assert report.warnings == [] + + +def test_display_name_with_spaces_and_mixed_case_matches() -> None: + mapper = _mapper() + lineage = _lineage( + mapper, + _workspace([_warehouse(name="Sales Warehouse 2024")]), + _m_query(ENDPOINT_HOST, "sales WAREHOUSE 2024"), + ) + + assert lineage["upstreams"] == [_onelake_urn(WAREHOUSE_ID)] + + +def test_region_prefixed_endpoint_host_is_recognised() -> None: + mapper = _mapper() + host = f"abc123-def456.z01{FABRIC_SQL_ENDPOINT_HOST_SUFFIX}" + lineage = _lineage(mapper, _workspace([_warehouse()]), _m_query(host, WAREHOUSE_ID)) + + assert lineage["upstreams"] == [_onelake_urn(WAREHOUSE_ID)] + + +def test_missing_schema_defaults_to_dbo() -> None: + mapper = _mapper() + lineage = _lineage( + mapper, + _workspace([_warehouse()]), + _m_query( + ENDPOINT_HOST, WAREHOUSE_ID, navigation='Source{[Item="claims"]}[Data]' + ), + ) + + assert lineage["upstreams"] == [_onelake_urn(WAREHOUSE_ID)] + + +def test_missing_item_keeps_mssql_edge_and_reports_shape() -> None: + mapper = _mapper() + lineage = _lineage( + mapper, + _workspace([_warehouse()]), + _m_query( + ENDPOINT_HOST, WAREHOUSE_ID, navigation='Source{[Schema="dbo"]}[Data]' + ), + ) + + assert not any("fabric-onelake" in urn for urn in lineage["upstreams"]) + assert all("mssql" in urn for urn in lineage["upstreams"]) + report = _report(mapper) + assert report.fabric_endpoint_m_shapes_unsupported == 1 + assert report.fabric_endpoint_references_resolved == 0 + assert "Fabric Endpoint M Shape Unsupported" in {w.title for w in report.warnings} + + +def test_native_query_tables_are_swapped() -> None: + mapper = _mapper() + lineage = _lineage( + mapper, + _workspace([_warehouse()]), + _m_query( + ENDPOINT_HOST, + "Claims_Warehouse", + navigation="Source", + record=', [Query="SELECT claim_id FROM dbo.claims"]', + ), + ) + + assert lineage["upstreams"] == [_onelake_urn(WAREHOUSE_ID)] + assert lineage["column_upstreams"] == [ + f"urn:li:schemaField:({_onelake_urn(WAREHOUSE_ID)},claim_id)" + ] + report = _report(mapper) + assert report.fabric_endpoint_references_resolved == 1 + assert report.warnings == [] + + +def test_sql_databases_navigation_keeps_mssql_edge_and_reports_shape() -> None: + mapper = _mapper() + expression = ( + "let\n" + f' Source = Sql.Databases("{ENDPOINT_HOST}"),\n' + ' db = Source{[Name="Claims_Warehouse"]}[Data],\n' + ' dbo_claims = db{[Schema="dbo",Item="claims"]}[Data]\n' + "in\n" + " dbo_claims" + ) + lineage = _lineage(mapper, _workspace([_warehouse()]), expression) + + assert lineage["upstreams"] == [ + "urn:li:dataset:(urn:li:dataPlatform:mssql,claims_warehouse.dbo.claims,PROD)" + ] + report = _report(mapper) + assert report.fabric_endpoint_m_shapes_unsupported == 1 + assert "Fabric Endpoint M Shape Unsupported" in {w.title for w in report.warnings} + + +def test_endpoint_uses_server_to_platform_instance_keyed_by_workspace() -> None: + mapper = _mapper( + server_to_platform_instance={ + WORKSPACE_ID: {"platform_instance": "fabric_prod", "env": "DEV"} + } + ) + lineage = _lineage( + mapper, _workspace([_warehouse()]), _m_query(ENDPOINT_HOST, WAREHOUSE_ID) + ) + + assert lineage["upstreams"] == [_onelake_urn(WAREHOUSE_ID, "fabric_prod", "DEV")] + + +def test_swapped_edge_survives_a_narrowed_dataset_type_mapping() -> None: + # The admin-scan fixtures narrow dataset_type_mapping to Sql only: the + # mssql edge used to pass that filter, so its OneLake replacement must + # too, or an existing edge silently becomes none. + mapper = _mapper(dataset_type_mapping={"Sql": "mssql"}) + lineage = _lineage( + mapper, _workspace([_warehouse()]), _m_query(ENDPOINT_HOST, WAREHOUSE_ID) + ) + + assert lineage["upstreams"] == [_onelake_urn(WAREHOUSE_ID)] + assert lineage["column_upstreams"] == [ + f"urn:li:schemaField:({_onelake_urn(WAREHOUSE_ID)},claim_id)" + ] + + +def test_endpoint_outside_workspace_patterns_keeps_mssql_edge_and_warns() -> None: + # A lakehouse in a workspace that workspace_id_pattern excluded is not + # among this workspace's Fabric items, so only its name is known. + mapper = _mapper() + lineage = _lineage( + mapper, _workspace([_warehouse()]), _m_query(ENDPOINT_HOST, "Other_Lakehouse") + ) + + assert lineage["upstreams"] == [MSSQL_OTHER] + report = _report(mapper) + assert report.fabric_endpoint_references_unresolved == 1 + assert report.fabric_endpoint_references_resolved == 0 + assert "Fabric Endpoint Not Resolved" in {w.title for w in report.warnings} + + # The same model mapped again (report + tile) is counted once. + _lineage( + mapper, _workspace([_warehouse()]), _m_query(ENDPOINT_HOST, "Other_Lakehouse") + ) + assert report.fabric_endpoint_references_unresolved == 1 + + +def test_display_name_shared_by_lakehouse_and_warehouse_is_ambiguous() -> None: + mapper = _mapper() + artifacts = _lakehouse_with_endpoint(name="Sales") + [_warehouse(name="Sales")] + lineage = _lineage(mapper, _workspace(artifacts), _m_query(ENDPOINT_HOST, "Sales")) + + assert lineage["upstreams"] == [ + "urn:li:dataset:(urn:li:dataPlatform:mssql,sales.dbo.claims,PROD)" + ] + report = _report(mapper) + assert report.fabric_endpoint_references_ambiguous == 1 + assert report.fabric_endpoint_references_resolved == 0 + assert "Fabric Endpoint Name Ambiguous" in {w.title for w in report.warnings} + + # Naming the warehouse by id is still unambiguous. + lineage = _lineage( + mapper, _workspace(artifacts), _m_query(ENDPOINT_HOST, WAREHOUSE_ID) + ) + assert lineage["upstreams"] == [_onelake_urn(WAREHOUSE_ID)] + + +def test_display_name_on_another_workspace_host_is_not_resolved() -> None: + """Display names are only unique within a workspace: with the + workspace's endpoint host known, a same-named item reached through + another workspace's host is not this workspace's item.""" + mapper = _mapper() + workspace = _workspace(_lakehouse_with_endpoint()) + workspace.fabric_sql_endpoint_hosts = {ENDPOINT_HOST} + other_host = f"other-workspace{FABRIC_SQL_ENDPOINT_HOST_SUFFIX}" + + lineage = _lineage(mapper, workspace, _m_query(other_host, "Claims_Lakehouse")) + assert lineage["upstreams"] == [ + "urn:li:dataset:(urn:li:dataPlatform:mssql,claims_lakehouse.dbo.claims,PROD)" + ] + assert _report(mapper).fabric_endpoint_references_unresolved == 1 + + lineage = _lineage(mapper, workspace, _m_query(ENDPOINT_HOST, "Claims_Lakehouse")) + assert lineage["upstreams"] == [_onelake_urn(LAKEHOUSE_ID)] + + # An endpoint id is globally unique, so it resolves on any host. + lineage = _lineage(mapper, workspace, _m_query(other_host, SQL_ENDPOINT_ID)) + assert lineage["upstreams"] == [_onelake_urn(LAKEHOUSE_ID)] + + +def test_navigation_without_a_table_reports_shape() -> None: + mapper = _mapper() + lineage = _lineage( + mapper, + _workspace([_warehouse()]), + _m_query(ENDPOINT_HOST, WAREHOUSE_ID, navigation="Source"), + ) + + assert lineage["upstreams"] == [] + assert _report(mapper).fabric_endpoint_m_shapes_unsupported == 1 + + +def test_native_query_table_with_a_dot_in_its_name_is_swapped() -> None: + mapper = _mapper() + lineage = _lineage( + mapper, + _workspace([_warehouse()]), + _m_query( + ENDPOINT_HOST, + "Claims_Warehouse", + navigation="Source", + record=', [Query="SELECT claim_id FROM dbo.[v1.claims]"]', + ), + ) + + assert lineage["upstreams"] == [_onelake_urn(WAREHOUSE_ID, table="dbo.v1.claims")] + assert _report(mapper).fabric_endpoint_m_shapes_unsupported == 0 + + +def test_native_query_with_platform_instance_named_like_the_database() -> None: + """The mssql URN is ``instance.database.schema.table``; an instance that + shares the database's name must be stripped, not read as the database.""" + mapper = _mapper( + server_to_platform_instance={ + ENDPOINT_HOST: {"platform_instance": "claims_warehouse"} + } + ) + lineage = _lineage( + mapper, + _workspace([_warehouse()]), + _m_query( + ENDPOINT_HOST, + "Claims_Warehouse", + navigation="Source", + record=', [Query="SELECT claim_id FROM dbo.claims"]', + ), + ) + + assert lineage["upstreams"] == [_onelake_urn(WAREHOUSE_ID)] + + +def test_non_fabric_sql_server_is_untouched() -> None: + mapper = _mapper() + lineage = _lineage( + mapper, _workspace([_warehouse()]), _m_query("sql.example.com", "claims_db") + ) + + assert lineage["upstreams"] == [ + "urn:li:dataset:(urn:li:dataPlatform:mssql,claims_db.dbo.claims,PROD)" + ] + report = _report(mapper) + assert report.fabric_endpoint_references_unresolved == 0 + assert report.fabric_endpoint_references_resolved == 0 + assert report.fabric_endpoint_m_shapes_unsupported == 0 + + +def test_dataflow_entity_over_endpoint_gets_onelake_edge() -> None: + # A Dataflow Gen2 entity reading the warehouse endpoint is mapped the + # same way as a semantic-model table, not left with an mssql edge. + mapper = _mapper() + workspace = _workspace([_warehouse()]) + mapper.workspace_key = mapper.make_container_key_for_workspace(workspace) + dataflow = Dataflow( + id="8b9c0d1e-2f3a-4b4c-8d5e-6f7a8b9c0d1e", + name="Claims Dataflow", + description=None, + workspace_name=workspace.name, + queries=[ + DataflowQuery( + name="claims", + expression=_m_query(ENDPOINT_HOST, WAREHOUSE_ID), + is_shared=True, + load_enabled=True, + ) + ], + ) + + lineage_aspects = [ + mcp.aspect + for mcp in mapper.to_datahub_dataflow(dataflow, workspace) + if isinstance(mcp.aspect, UpstreamLineageClass) + ] + + assert len(lineage_aspects) == 1 + assert [u.dataset for u in lineage_aspects[0].upstreams] == [ + _onelake_urn(WAREHOUSE_ID) + ] + report = _report(mapper) + assert report.fabric_endpoint_references_resolved == 1 + assert report.warnings == [] + + +def test_swapped_endpoint_keeps_source_column_lineage_of_a_renamed_field() -> None: + # A field the model renamed keeps its TMDL sourceColumn on the upstream + # side; the endpoint swap must carry that edge onto the OneLake table + # rather than leaving it on the mssql URN the coarse edge no longer has. + mapper = _mapper() + table = _table(_m_query(ENDPOINT_HOST, WAREHOUSE_ID)) + table.columns = [ + Column( + name="Claim Number", + dataType="String", + isHidden=False, + datahubDataType=StringTypeClass(), + source_column="CLAIM_ID", + ) + ] + mcps = mapper.extract_lineage(table, DS_URN, _workspace([_warehouse()])) + assert len(mcps) == 1 + aspect = mcps[0].aspect + assert isinstance(aspect, UpstreamLineageClass) + assert [u.dataset for u in aspect.upstreams] == [_onelake_urn(WAREHOUSE_ID)] + assert [ + (edge.downstreams, edge.upstreams) for edge in aspect.fineGrainedLineages or [] + ] == [ + ( + [f"urn:li:schemaField:({DS_URN},Claim Number)"], + [f"urn:li:schemaField:({_onelake_urn(WAREHOUSE_ID)},CLAIM_ID)"], + ) + ] diff --git a/metadata-ingestion/tests/unit/powerbi/test_fabric_resolver.py b/metadata-ingestion/tests/unit/powerbi/test_fabric_resolver.py index de3fdcd7da2a1..bf307664114dd 100644 --- a/metadata-ingestion/tests/unit/powerbi/test_fabric_resolver.py +++ b/metadata-ingestion/tests/unit/powerbi/test_fabric_resolver.py @@ -259,13 +259,26 @@ def test_list_items_follows_continuation_token( ] -def test_lakehouse_sql_endpoint_id(resolver: FabricDefinitionResolver) -> None: +def test_lakehouse_sql_endpoint(resolver: FabricDefinitionResolver) -> None: url = f"{FABRIC_BASE_URL}/workspaces/{WORKSPACE}/lakehouses/lh" with requests_mock.Mocker() as m: - m.get(url, json={"properties": {"sqlEndpointProperties": {"id": "ep"}}}) - assert resolver.get_lakehouse_sql_endpoint_id(WORKSPACE, "lh") == "ep" + m.get( + url, + json={ + "properties": { + "sqlEndpointProperties": { + "id": "ep", + "connectionString": "abc.datawarehouse.fabric.microsoft.com", + } + } + }, + ) + endpoint = resolver.get_lakehouse_sql_endpoint(WORKSPACE, "lh") + assert endpoint is not None + assert endpoint.id == "ep" + assert endpoint.connection_string == "abc.datawarehouse.fabric.microsoft.com" m.get(url, json={"properties": {}}) - assert resolver.get_lakehouse_sql_endpoint_id(WORKSPACE, "lh") is None + assert resolver.get_lakehouse_sql_endpoint(WORKSPACE, "lh") is None def test_binary_parts_are_skipped_without_being_reported( diff --git a/metadata-ingestion/tests/unit/powerbi/test_fill_metadata_from_definitions.py b/metadata-ingestion/tests/unit/powerbi/test_fill_metadata_from_definitions.py index 12e343acce8bc..55569d4fb7866 100644 --- a/metadata-ingestion/tests/unit/powerbi/test_fill_metadata_from_definitions.py +++ b/metadata-ingestion/tests/unit/powerbi/test_fill_metadata_from_definitions.py @@ -28,6 +28,7 @@ FabricItem, FabricLroTimeoutError, ItemDefinition, + LakehouseSqlEndpoint, ) from datahub.ingestion.source.powerbi.rest_api_wrapper.powerbi_api import ( PowerBiAPI, @@ -45,6 +46,8 @@ MODEL_B = "7A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D" LAKEHOUSE_ID = "3C4D5E6F-7A8B-4C9D-8E0F-1A2B3C4D5E6F" SQL_ENDPOINT_ID = "6F2E7D8C-9B0A-4C1D-8E2F-3A4B5C6D7E8F" +WAREHOUSE_ID = "9A8B7C6D-5E4F-4A3B-8C2D-1E0F9A8B7C6D" +ENDPOINT_HOST = "abc123.datawarehouse.fabric.microsoft.com" TABLE_TMDL = """table Policies @@ -142,7 +145,10 @@ def _api( fabric = MagicMock() fabric.list_items.return_value = items if items is not None else [] - fabric.get_lakehouse_sql_endpoint_id.return_value = SQL_ENDPOINT_ID + fabric.get_lakehouse_sql_endpoint.return_value = LakehouseSqlEndpoint( + id=SQL_ENDPOINT_ID, connection_string=ENDPOINT_HOST + ) + fabric.get_warehouse_connection_string.return_value = ENDPOINT_HOST definitions = definitions if definitions is not None else {MODEL_A: _definition()} def get_item_definition( @@ -547,16 +553,129 @@ def test_lakehouse_endpoint_registered_and_failure_degrades_gracefully() -> None assert workspace.fabric_artifacts[LAKEHOUSE_ID].artifact_type == "Lakehouse" api = _api(items=items) - api._PowerBiAPI__fabric_resolver.get_lakehouse_sql_endpoint_id.side_effect = ( # type: ignore[attr-defined] + api._PowerBiAPI__fabric_resolver.get_lakehouse_sql_endpoint.side_effect = ( # type: ignore[attr-defined] _http_error(500) ) workspace = _workspace() api.fill_metadata_from_definitions([workspace]) assert workspace.fabric_artifacts[SQL_ENDPOINT_ID].physical_item_ids is None - assert any( - w.title == "Lakehouse SQL Endpoint Not Resolved" for w in api.reporter.warnings + assert api.reporter.fabric_lakehouse_endpoints_unresolved == 1 + assert api.reporter.fabric_lakehouse_endpoints_registered == 0 + assert any(w.title == "Fabric Endpoint Not Resolved" for w in api.reporter.warnings) + + +def test_lakehouse_endpoint_host_is_recorded() -> None: + items = [FabricItem(LAKEHOUSE_ID, "Sales", "Lakehouse", WORKSPACE_ID)] + api = _api(items=items) + workspace = _workspace() + api.fill_metadata_from_definitions([workspace]) + assert workspace.fabric_sql_endpoint_hosts == {ENDPOINT_HOST} + + +def test_lakehouse_without_sql_endpoint_is_counted_and_warned() -> None: + items = [FabricItem(LAKEHOUSE_ID, "Sales", "Lakehouse", WORKSPACE_ID)] + api = _api(items=items) + api._PowerBiAPI__fabric_resolver.get_lakehouse_sql_endpoint.return_value = None # type: ignore[attr-defined] + workspace = _workspace() + api.fill_metadata_from_definitions([workspace]) + assert list(workspace.fabric_artifacts) == [LAKEHOUSE_ID] + assert api.reporter.fabric_lakehouse_endpoints_unresolved == 1 + assert any(w.title == "Fabric Endpoint Not Resolved" for w in api.reporter.warnings) + + +def test_warehouse_registered_as_its_own_endpoint() -> None: + api = _api( + items=[FabricItem(WAREHOUSE_ID, "Claims_Warehouse", "Warehouse", WORKSPACE_ID)] + ) + workspace = _workspace() + api.fill_metadata_from_definitions([workspace]) + + # A warehouse's SQL endpoint id is the warehouse id: the DirectLake path + # resolves the artifact directly, no properties call is needed. + warehouse = workspace.fabric_artifacts[WAREHOUSE_ID] + assert warehouse.artifact_type == "Warehouse" + assert list(workspace.fabric_artifacts) == [WAREHOUSE_ID] + assert api.reporter.fabric_warehouse_endpoints_registered == 1 + assert api.reporter.fabric_lakehouse_endpoints_unresolved == 0 + api._PowerBiAPI__fabric_resolver.get_lakehouse_sql_endpoint.assert_not_called() # type: ignore[attr-defined] + + +def test_warehouse_only_workspace_records_endpoint_host() -> None: + api = _api( + items=[FabricItem(WAREHOUSE_ID, "Claims_Warehouse", "Warehouse", WORKSPACE_ID)] + ) + workspace = _workspace() + api.fill_metadata_from_definitions([workspace]) + assert workspace.fabric_sql_endpoint_hosts == {ENDPOINT_HOST} + + api = _api( + items=[ + FabricItem(LAKEHOUSE_ID, "Sales", "Lakehouse", WORKSPACE_ID), + FabricItem(WAREHOUSE_ID, "Claims_Warehouse", "Warehouse", WORKSPACE_ID), + ] + ) + workspace = _workspace() + api.fill_metadata_from_definitions([workspace]) + assert workspace.fabric_sql_endpoint_hosts == {ENDPOINT_HOST} + api._PowerBiAPI__fabric_resolver.get_warehouse_connection_string.assert_not_called() # type: ignore[attr-defined] + + +@pytest.mark.parametrize( + "lakehouse_failure", + [ + pytest.param(_http_error(500), id="http_error"), + pytest.param(None, id="no_endpoint"), + ], +) +def test_warehouse_supplies_host_when_lakehouse_endpoint_fails( + lakehouse_failure: Optional[Exception], +) -> None: + api = _api( + items=[ + FabricItem(LAKEHOUSE_ID, "Sales", "Lakehouse", WORKSPACE_ID), + FabricItem(WAREHOUSE_ID, "Claims_Warehouse", "Warehouse", WORKSPACE_ID), + ] + ) + resolver = api._PowerBiAPI__fabric_resolver # type: ignore[attr-defined] + if lakehouse_failure is None: + resolver.get_lakehouse_sql_endpoint.return_value = None + else: + resolver.get_lakehouse_sql_endpoint.side_effect = lakehouse_failure + workspace = _workspace() + api.fill_metadata_from_definitions([workspace]) + + assert workspace.fabric_sql_endpoint_hosts == {ENDPOINT_HOST} + resolver.get_warehouse_connection_string.assert_called_once() + + +@pytest.mark.parametrize( + "failure", + [ + pytest.param(_http_error(500), id="http_error"), + pytest.param(None, id="no_connection_string"), + ], +) +def test_warehouse_endpoint_host_unknown_leaves_hosts_empty( + failure: Optional[Exception], +) -> None: + api = _api( + items=[FabricItem(WAREHOUSE_ID, "Claims_Warehouse", "Warehouse", WORKSPACE_ID)] + ) + resolver = api._PowerBiAPI__fabric_resolver # type: ignore[attr-defined] + if failure is None: + resolver.get_warehouse_connection_string.return_value = None + else: + resolver.get_warehouse_connection_string.side_effect = failure + workspace = _workspace() + api.fill_metadata_from_definitions([workspace]) + + assert workspace.fabric_sql_endpoint_hosts == set() + assert WAREHOUSE_ID in workspace.fabric_artifacts + warned = any( + w.title == "Fabric Endpoint Host Unknown" for w in api.reporter.warnings ) + assert warned == (failure is not None) @pytest.mark.parametrize( diff --git a/metadata-ingestion/tests/unit/powerbi/test_rename_columns.py b/metadata-ingestion/tests/unit/powerbi/test_rename_columns.py index 20edf867242fd..d6db852b5e663 100644 --- a/metadata-ingestion/tests/unit/powerbi/test_rename_columns.py +++ b/metadata-ingestion/tests/unit/powerbi/test_rename_columns.py @@ -12,6 +12,7 @@ from datahub.ingestion.source.powerbi.m_query.data_classes import ( ColumnRename, ColumnRenameStep, + FabricSqlEndpointReference, Lineage, ) from datahub.ingestion.source.powerbi.m_query.pattern_handler import ( @@ -264,6 +265,36 @@ def test_sql_lineage_is_not_renamed_again_after_urn_transform() -> None: assert result.column_lineage[0].upstreams[0].column == "City" +def test_rename_keeps_fabric_endpoint_references() -> None: + reference = FabricSqlEndpointReference( + server="abc.datawarehouse.fabric.microsoft.com", + database="sales_lakehouse", + schema_name="dbo", + table_name="dim_customers", + mssql_urn=_UPSTREAM, + ) + lineage = Lineage( + upstreams=[], + column_lineage=[ + ColumnLineageInfo( + downstream=DownstreamColumnRef(column="Town"), + upstreams=[ColumnRef(table=_UPSTREAM, column="Town")], + ) + ], + fabric_endpoint_references=[reference], + ) + result = apply_table_rename_columns( + lineage, + [ + ColumnRenameStep( + renames=[ColumnRename(source_name="City", renamed_name="Town")] + ) + ], + ) + assert result.column_lineage[0].upstreams[0].column == "City" + assert result.fabric_endpoint_references == [reference] + + def test_apply_renames_is_noop_without_steps() -> None: lineage = Lineage(upstreams=[], column_lineage=[]) assert apply_table_rename_columns(lineage, []) is lineage