-
Notifications
You must be signed in to change notification settings - Fork 2.3k
fix(mssql,azuresql): keep OpenMetadata's own queries out of usage and lineage #31163
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
IceS2
wants to merge
3
commits into
main
Choose a base branch
from
fix/mssql-azuresql-query-header-inline
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
184 changes: 184 additions & 0 deletions
184
ingestion/tests/integration/sql_server/test_query_headers.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,184 @@ | ||
| # Copyright 2025 Collate | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """ | ||
| SQL Server must not report OpenMetadata's own queries back as user queries. | ||
|
|
||
| These assertions can only be made against a real server: the header is dropped or | ||
| kept depending on how SQL Server splits a batch into statements, which no amount | ||
| of string inspection reveals. | ||
| """ | ||
|
|
||
| import pytest | ||
| from sqlalchemy import create_engine, text | ||
|
|
||
| from metadata.generated.schema.entity.services.connections.database.azureSQLConnection import ( | ||
| AzureSQLConnection, | ||
| ) | ||
| from metadata.generated.schema.entity.services.connections.database.mssqlConnection import ( | ||
| MssqlConnection as MssqlConnectionConfig, | ||
| ) | ||
| from metadata.ingestion.source.database.azuresql.connection import ( | ||
| AzureSQLConnection as AzureSQLBaseConnection, | ||
| ) | ||
| from metadata.ingestion.source.database.mssql.connection import ( | ||
| MssqlConnection as MssqlBaseConnection, | ||
| ) | ||
| from metadata.ingestion.source.database.mssql.queries import ( | ||
| MSSQL_SQL_STATEMENT, | ||
| MSSQL_SQL_STATEMENT_FROM_QUERY_STORE, | ||
| ) | ||
|
|
||
| OM_MARKER = "OpenMetadata" | ||
| # lives in the statement body, so it survives whether or not the header does | ||
| PROBE_MARKER = "header" + "_probe" | ||
|
|
||
| # every shape OM issues: bare, leading-newline (textwrap.dedent), CTE, parameterised | ||
| STATEMENTS = [ | ||
| "SELECT 1 AS header_probe_plain", | ||
| "\nSELECT 2 AS header_probe_dedent", | ||
| "\n SELECT 3 AS header_probe_dedent_space", | ||
| "WITH probe AS (SELECT 4 AS c) SELECT c AS header_probe_cte FROM probe", | ||
| ] | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def query_store_db(mssql_container, db_name): | ||
| """Enable Query Store with full capture so every probe statement is recorded.""" | ||
| engine = create_engine( | ||
| "mssql+pytds://" + mssql_container.get_connection_url().split("://")[1], | ||
| connect_args={"autocommit": True}, | ||
| ) | ||
| with engine.connect() as conn: | ||
| conn.execute(text(f"ALTER DATABASE [{db_name}] SET QUERY_STORE = ON")) | ||
| conn.execute(text(f"ALTER DATABASE [{db_name}] SET QUERY_STORE (QUERY_CAPTURE_MODE = ALL)")) | ||
| yield db_name | ||
| with engine.connect() as conn: | ||
| conn.execute(text(f"ALTER DATABASE [{db_name}] SET QUERY_STORE = OFF")) | ||
|
|
||
|
|
||
| def om_engine(connection_config, base_connection_cls): | ||
| return base_connection_cls(connection_config).client | ||
|
|
||
|
|
||
| def run_probe_statements(engine): | ||
| with engine.connect() as conn: | ||
| for statement in STATEMENTS: | ||
| conn.execute(text(statement)) | ||
| # parameterised: SQL Server records these via sp_executesql, which puts the | ||
| # parameter declarations ahead of the statement | ||
| conn.execute( | ||
| text("SELECT :v AS header_probe_param"), | ||
| {"v": 5}, | ||
| ) | ||
|
|
||
|
|
||
| def recorded_texts(mssql_container, db_name, query): | ||
| """Rows the usage query would hand to the parser, after its own filtering.""" | ||
| engine = create_engine( | ||
| f"mssql+pytds://{mssql_container.get_connection_url().split('://')[1]}", | ||
| connect_args={"autocommit": True}, | ||
| ) | ||
| sql = query.format( | ||
| result_limit=1000, | ||
| start_time="2000-01-01 00:00:00", | ||
| end_time="2100-01-01 00:00:00", | ||
| start_date="2000-01-01 00:00:00", | ||
| filters="", | ||
| ).replace("%%", "%") | ||
| with engine.connect() as conn: | ||
| conn.execute(text(f"USE [{db_name}]")) | ||
| conn.execute(text("EXEC sys.sp_query_store_flush_db")) | ||
| return [row.query_text for row in conn.execute(text(sql)).fetchall()] | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def mssql_om_engine(mssql_container, query_store_db, scheme): | ||
| config = MssqlConnectionConfig( | ||
| username=mssql_container.username, | ||
| password=mssql_container.password, | ||
| hostPort="localhost:" + mssql_container.get_exposed_port(mssql_container.port), | ||
| database=query_store_db, | ||
| scheme=scheme, | ||
| connectionOptions={"TrustServerCertificate": "yes", "MARS_Connection": "yes"}, | ||
| ) | ||
| return om_engine(config, MssqlBaseConnection) | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def azuresql_om_engine(mssql_container, query_store_db): | ||
| """Azure SQL speaks the same protocol, so the container stands in for it here.""" | ||
| config = AzureSQLConnection( | ||
| username=mssql_container.username, | ||
| password=mssql_container.password, | ||
| hostPort="localhost:" + mssql_container.get_exposed_port(mssql_container.port), | ||
| database=query_store_db, | ||
| connectionOptions={"TrustServerCertificate": "yes", "MARS_Connection": "yes"}, | ||
| ) | ||
| return om_engine(config, AzureSQLBaseConnection) | ||
|
|
||
|
|
||
| class TestOpenMetadataQueriesAreFiltered: | ||
| @pytest.mark.parametrize( | ||
| "query", | ||
| [MSSQL_SQL_STATEMENT_FROM_QUERY_STORE, MSSQL_SQL_STATEMENT], | ||
| ids=["query_store", "plan_cache"], | ||
| ) | ||
| def test_mssql_own_queries_do_not_reach_the_parser(self, mssql_om_engine, mssql_container, query_store_db, query): | ||
| run_probe_statements(mssql_om_engine) | ||
|
|
||
| leaked = [text_ for text_ in recorded_texts(mssql_container, query_store_db, query) if PROBE_MARKER in text_] | ||
|
|
||
| assert leaked == [] | ||
|
|
||
| @pytest.mark.parametrize( | ||
| "query", | ||
| [MSSQL_SQL_STATEMENT_FROM_QUERY_STORE, MSSQL_SQL_STATEMENT], | ||
| ids=["query_store", "plan_cache"], | ||
| ) | ||
| def test_azuresql_own_queries_do_not_reach_the_parser( | ||
| self, azuresql_om_engine, mssql_container, query_store_db, query | ||
| ): | ||
| run_probe_statements(azuresql_om_engine) | ||
|
|
||
| leaked = [text_ for text_ in recorded_texts(mssql_container, query_store_db, query) if PROBE_MARKER in text_] | ||
|
|
||
| assert leaked == [] | ||
|
|
||
|
|
||
| class TestHeaderSurvivesIntoQueryStore: | ||
| """A filter can only work if SQL Server kept the header in the first place.""" | ||
|
|
||
| def test_query_store_keeps_the_header_for_every_statement_shape( | ||
| self, mssql_om_engine, mssql_container, query_store_db | ||
| ): | ||
| run_probe_statements(mssql_om_engine) | ||
|
|
||
| engine = create_engine( | ||
| f"mssql+pytds://{mssql_container.get_connection_url().split('://')[1]}", | ||
| connect_args={"autocommit": True}, | ||
| ) | ||
| with engine.connect() as conn: | ||
| conn.execute(text(f"USE [{query_store_db}]")) | ||
| conn.execute(text("EXEC sys.sp_query_store_flush_db")) | ||
| rows = conn.execute( | ||
| # the marker is split so this query's own text cannot match it and | ||
| # pollute the store for later tests | ||
| text( | ||
| "SELECT query_sql_text FROM sys.query_store_query_text" | ||
| " WHERE query_sql_text LIKE '%hea' + 'der_probe%'" | ||
| ) | ||
| ).fetchall() | ||
|
|
||
| probes = [row[0] for row in rows if "query_store_query_text" not in row[0]] | ||
|
|
||
| assert probes, "no probe statements were recorded" | ||
| assert all(OM_MARKER in probe for probe in probes) | ||
| assert not any(probe.lstrip().startswith("/*") for probe in probes) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Edge Case: Inline header injected inside a leading line comment (--)
inject_inline_query_header only skips statements whose first non-whitespace is a block comment (
stripped.startswith("/*")). If a statement begins with a--line comment (e.g.-- note SELECT ...), the first token is--and the header is placed right after it:-- /* {...} */ note SELECT ..., so the header sits inside the line comment and is dropped — the exact failure this PR fixes. This is unlikely for OpenMetadata's own reflection queries today, so it is a latent gap rather than a live defect; if it matters, also guardstripped.startswith("--")(returning the statement unchanged) or inject after the first real keyword.Leave statements starting with a line comment untouched, matching the existing block-comment guard.:
Check the box to apply the fix or reply for a change | Was this helpful? React with 👍 / 👎