Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
e1bc29f
Add SQLGlot parser support
mohittilala Dec 8, 2025
ee33434
Add query_hash to all lineage parsing logs for better tracking
mohittilala Dec 8, 2025
fd5c23b
Better logging of parser logs
mohittilala Dec 8, 2025
5a7eac8
Merge branch 'main' into sqlglot-support
mohittilala Dec 10, 2025
cb44e01
Merge branch 'sqlglot-support' of github.com:open-metadata/OpenMetada…
mohittilala Dec 10, 2025
95a1674
Cache db service lookups to reduce repeated searches
mohittilala Dec 10, 2025
658cac9
sqlglot query masking fallback to sqlparse and better logging to track
mohittilala Dec 10, 2025
95cf8b3
Consistent logs for query parsing with all useful information
mohittilala Dec 10, 2025
0419aa9
Add query masking tests for all parsers
mohittilala Dec 10, 2025
d6a8eed
Remove duplicate query masking tests
mohittilala Dec 10, 2025
862b9f2
Add specific dialect sql tests and helper methods to test/compare all…
mohittilala Dec 10, 2025
f1ff677
py_format
mohittilala Dec 10, 2025
8cbb924
Add tests for large set of complex query patterns to validate all par…
mohittilala Dec 10, 2025
6430cfa
Add memory limits on lineage query parsers with default 100mb limit
mohittilala Dec 11, 2025
0552fb4
Better memory limit handling and more tests
mohittilala Dec 12, 2025
2727ca7
Merge branch 'main' into sqlglot-support
mohittilala Dec 14, 2025
05cd0bf
Remove query parsing issue summary since it's killing the workflow wh…
mohittilala Dec 14, 2025
c637e18
py_format
mohittilala Dec 14, 2025
026bddc
Add e2e lineage tests for oracle db and fix oracle query lineage filters
mohittilala Dec 15, 2025
3ae5b6d
py_format
mohittilala Dec 15, 2025
8f04040
Remove SqlGlot parsing from query masker
mohittilala Dec 15, 2025
01d6ab8
Add __init__.py to query test packages
mohittilala Dec 15, 2025
3e0ecde
Better logs to track get lineage method
mohittilala Dec 15, 2025
cb8bc61
Disable memory limits for now as they are performance overhead
mohittilala Dec 15, 2025
6dcfc27
Update sql file path for e2e oracle db lineage tests
mohittilala Dec 15, 2025
9f585fe
TEMP: Add local rc build of latest sqllineage with sqlglot support fo…
mohittilala Dec 15, 2025
4921084
Revert search_cache name change in sql_lineage.py
mohittilala Dec 15, 2025
079bf22
Handle tests hanging with timeouts caused by graph checks or heavy qu…
mohittilala Dec 15, 2025
82bbfa0
Complex query test formatting
mohittilala Dec 15, 2025
d0d8a64
py_format
mohittilala Dec 15, 2025
7c65077
Handle complex query tests with appropriate flags #01
mohittilala Dec 16, 2025
cc04d3e
Handle complex query tests with appropriate flags #02
mohittilala Dec 16, 2025
2bd3ecd
Handle complex query tests with appropriate flags #03
mohittilala Dec 16, 2025
05f4a4d
Handle complex query tests with appropriate flags #04 (final)
mohittilala Dec 18, 2025
a279b38
Update query lineage test helper for better troubleshooting
mohittilala Dec 18, 2025
cc4c1c5
Merge branch 'main' into sqlglot-support
mohittilala Dec 18, 2025
712cfa0
Add dialect specific query masking tests and skip sqlglot failures fo…
mohittilala Dec 18, 2025
4c316da
Fix or skip other failing test related to sqlglot changes
mohittilala Dec 18, 2025
3e79bc2
Merge branch 'sqlglot-support' of github.com:open-metadata/OpenMetada…
mohittilala Dec 18, 2025
589cf9d
py_format
mohittilala Dec 18, 2025
fb76a34
Reduce sleep between proc calls for faster tests
mohittilala Dec 18, 2025
3f906d8
Merge branch 'main' into sqlglot-support
mohittilala Dec 18, 2025
8d1f5a9
Merge branch 'sqlglot-support' of github.com:open-metadata/OpenMetada…
mohittilala Dec 18, 2025
7597449
Remove default test diff limit and skip graph check that timeout in c…
mohittilala Dec 18, 2025
a397987
Clear the topology runner cache in test to have cleaned state
mohittilala Dec 18, 2025
04320f5
Skip flaky graph check timeouts on test
mohittilala Dec 18, 2025
15b4a7b
Handle no parser in mask_query and log every message as debug to not …
mohittilala Dec 18, 2025
ae6ef04
Update parser logs to debug for less verbosity on default log level
mohittilala Dec 18, 2025
21a8045
Remove TEMP collate-sqllineage whl added for test since 2.0.0 is out
mohittilala Dec 18, 2025
a50de20
Log maximum 10 failures in workflow summary to not overload ingestion
mohittilala Dec 18, 2025
db801ac
Cleanup oracle db image after lineage e2e tests
mohittilala Dec 19, 2025
9df335b
Remove query parsing failures tracking from sql lineage process
mohittilala Dec 19, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ingestion/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@
"requests>=2.23",
"requests-aws4auth~=1.1", # Only depends on requests as external package. Leaving as base.
"sqlalchemy>=1.4.0,<2",
"collate-sqllineage~=1.6.0",
"collate-sqllineage~=2.0",
"tabulate==0.9.0",
"typing-inspect",
"packaging", # For version parsing
Expand Down
134 changes: 102 additions & 32 deletions ingestion/src/metadata/ingestion/lineage/masker.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,39 +10,44 @@
# limitations under the License.
"""
Query masking utilities

All masking functions (SqlParse, SqlFluff, SqlGlot) reuse the already-parsed AST
from the LineageRunner to avoid duplicate parsing and improve performance.
"""

import time
import traceback
from typing import Optional

from cachetools import LRUCache
from collate_sqllineage.runner import SQLPARSE_DIALECT, LineageRunner
from collate_sqllineage.core.parser.sqlfluff.analyzer import SqlFluffLineageAnalyzer
from collate_sqllineage.core.parser.sqlglot.analyzer import SqlGlotLineageAnalyzer
from collate_sqllineage.core.parser.sqlparse.analyzer import SqlParseLineageAnalyzer
from collate_sqllineage.runner import LineageRunner
from sqlparse.sql import Comparison
from sqlparse.tokens import Literal, Number, String

from metadata.ingestion.lineage.models import Dialect
from metadata.utils.execution_time_tracker import calculate_execution_time
from metadata.utils.execution_time_tracker import (
calculate_execution_time,
pretty_print_time_duration,
)
from metadata.utils.logger import utils_logger

logger = utils_logger()

MASK_TOKEN = "?"

# Cache size is 128 to avoid memory issues
masked_query_cache = LRUCache(maxsize=128)


# pylint: disable=protected-access
def get_logger():
# pylint: disable=import-outside-toplevel
from metadata.utils.logger import utils_logger

return utils_logger()


def mask_literals_with_sqlparse(query: str, parser: LineageRunner):
def mask_literals_with_sqlparse(
query: str, parser: LineageRunner, query_hash: Optional[str] = None
):
"""
Mask literals in a query using sqlparse.
Mask literals in a query using SqlParse.
"""
logger = get_logger()

try:
parsed = parser._parsed_result

Expand All @@ -54,7 +59,6 @@ def mask_token(token):
Literal.String.Single,
Literal.Number.Integer,
Literal.Number.Float,
Literal.String.Single,
):
token.value = MASK_TOKEN
elif token.is_group:
Expand All @@ -74,23 +78,32 @@ def mask_token(token):
# Return the formatted masked query
return str(parsed)
except Exception as exc:
logger.debug(f"Failed to mask query with sqlparse: {exc}")
hash_prefix = f"[{query_hash}] " if query_hash else ""
logger.debug(f"{hash_prefix}Failed to mask query with SqlParse: {exc}")
logger.debug(traceback.format_exc())

return query


def mask_literals_with_sqlfluff(query: str, parser: LineageRunner) -> str:
def mask_literals_with_sqlfluff(
query: str, parser: LineageRunner, query_hash: Optional[str] = None
) -> str:
"""
Mask literals in a query using SQLFluff.
Mask literals in a query using SqlFluff.
"""
logger = get_logger()
try:
if not parser._evaluated:
parser._eval()

parsed = parser._parsed_result

if parsed is None:
hash_prefix = f"[{query_hash}] " if query_hash else ""
logger.debug(
f"{hash_prefix}Skipping SqlFluff query masking as parsed result is None"
)
return query

def replace_literals(segment):
"""Recursively replace literals with placeholders."""
if segment.is_type("literal", "quoted_literal", "numeric_literal"):
Expand All @@ -108,7 +121,8 @@ def replace_literals(segment):
)
return masked_query
except Exception as exc:
logger.debug(f"Failed to mask query with sqlfluff: {exc}")
hash_prefix = f"[{query_hash}] " if query_hash else ""
logger.debug(f"{hash_prefix}Failed to mask query with SqlFluff: {exc}")
logger.debug(traceback.format_exc())

return query
Expand All @@ -120,30 +134,86 @@ def mask_query(
dialect: str = Dialect.ANSI.value,
parser: Optional[LineageRunner] = None,
parser_required: bool = False,
) -> str:
query_hash: Optional[str] = None,
) -> Optional[str]:
"""Evaluate and return the best available parser for the query."""
hash_prefix = f"[{query_hash}] " if query_hash else ""

start_time = time.time()
masked_query = mask_query_impl(query, dialect, parser, parser_required, query_hash)
elapsed = time.time() - start_time

elapsed_str = pretty_print_time_duration(elapsed)
logger.debug(f"{hash_prefix}Query masking completed in {elapsed_str}")

return masked_query


def mask_query_impl(
query: str,
dialect: str = Dialect.ANSI.value,
parser: Optional[LineageRunner] = None,
parser_required: bool = False,
query_hash: Optional[str] = None,
) -> Optional[str]:
"""
Mask a query using sqlparse or sqlfluff.
Mask a query using SqlGlot, SqlFluff, or SqlParse based on the analyzer used.
"""
logger = get_logger()
hash_prefix = f"[{query_hash}] " if query_hash else ""

try:
if masked_query_cache.get((query, dialect)):
return masked_query_cache.get((query, dialect))
if parser_required and not parser:
logger.debug(f"{hash_prefix}Query masking skipped as no parser available.")
return None
if not parser:

masking_parser = parser
# Since SqlGlot generalizes query structures/syntax, we will use
# SqlParse for masking if SqlGlot is used for parsing
Comment on lines +172 to +173

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure if i understand this fully?? why can't we build a making with sqlglot - using sqlparse here would not achieve the performance improvements we are expecting

@mohittilala mohittilala Dec 16, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sqlglot normalizes sqls after parsing and doesn't retain original sql content.

for reference (masking with sqlglot):

Original Query: SELECT * FROM user WHERE id=1234 AND name='Alice' AND birthdate=DATE '2023-01-01';

E       AssertionError: 
E       	[SqlGlot] Expected Masked Query: SELECT * FROM user WHERE id=? AND name=? AND birthdate=DATE ?;
E       	[SqlGlot] Actual Masked Query: SELECT * FROM user WHERE id = ? AND name = ? AND birthdate = CAST(? AS DATE)

here, type casting birthdate=DATE ? is normalized to birthdate = CAST(? AS DATE) and there is no option for us to disable this behaviour as it's intended use-case of sqlglot.

ideally, this is not an issue but when sql is complex and sqlglot does any mistake in converting sql then we wouldn't even get the original sql so can't rely 100% on the parsing/conversion capabilities of sqlglot.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code reference:

from sqlglot import parse_one, exp

sql = "SELECT * FROM user WHERE id=1234 AND name='Alice' AND birthdate=DATE '2023-01-01';"

expression:exp.Expression = parse_one(sql)
transformed = expression.transform(
    lambda n: exp.Placeholder() if isinstance(n, exp.Literal) else n
)
masked_sql = transformed.sql()

print(f"Original Query: {sql}")
print(f"Masked Query:   {masked_sql}")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sqlparse parsing time is almost same as sqlglot so here it would be 2x time than expectation but no workaround for now.

if parser and isinstance(parser._analyzer, SqlGlotLineageAnalyzer):
masking_parser = LineageRunner(query, analyzer=SqlParseLineageAnalyzer)
len(masking_parser.source_tables)

if not masking_parser:
# Try to create a parser with the same fallback strategy as LineageParser
# but since we are not using SqlGlot for masking, we skip it here.
# Try SqlFluff, then SqlParse
# TODO: Evaluate if sqlparse should be the first choice here since it is
# faster and almost same support as sqlfluff for masking literals.
try:
parser = LineageRunner(query, dialect=dialect)
len(parser.source_tables)
masking_parser = LineageRunner(
query, dialect=dialect, analyzer=SqlFluffLineageAnalyzer
)
len(masking_parser.source_tables)
except Exception:
parser = LineageRunner(query)
len(parser.source_tables)
if parser._dialect == SQLPARSE_DIALECT:
masked_query = mask_literals_with_sqlparse(query, parser)
masking_parser = LineageRunner(query, analyzer=SqlParseLineageAnalyzer)
len(masking_parser.source_tables)

logger.debug(
f"{hash_prefix}Query masking started using [{masking_parser._analyzer.__class__.__name__}]"
f" for parser [{parser and parser._analyzer.__class__.__name__}]"
)

# Check which analyzer was used based on _analyzer attribute
if isinstance(masking_parser._analyzer, SqlFluffLineageAnalyzer):
masked_query = mask_literals_with_sqlfluff(
query, masking_parser, query_hash
)
elif isinstance(masking_parser._analyzer, SqlParseLineageAnalyzer):
masked_query = mask_literals_with_sqlparse(
query, masking_parser, query_hash
)
else:
masked_query = mask_literals_with_sqlfluff(query, parser)
logger.debug(
f"{hash_prefix}Query masking skipped as no parser._analyzer available."
f" Analyzer: {masking_parser._analyzer}"
)
return None

masked_query_cache[(query, dialect)] = masked_query
return masked_query
except Exception as exc:
logger.debug(f"Failed to mask query with sqlfluff: {exc}")
logger.debug(f"{hash_prefix}Failed to mask query: {exc}")
logger.debug(traceback.format_exc())
return None
Loading