-
Notifications
You must be signed in to change notification settings - Fork 359
feat: helper to find key in model block #5079
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -158,3 +158,55 @@ def get_range_of_model_block( | |
| return Range( | ||
| start=start_position.to_range(splitlines).start, end=end_position.to_range(splitlines).end | ||
| ) | ||
|
|
||
|
|
||
| def get_range_of_a_key_in_model_block( | ||
| sql: str, | ||
| dialect: str, | ||
| key: str, | ||
| ) -> t.Optional[Range]: | ||
| """ | ||
| Get the range of a specific key in the model block of an SQL file. | ||
| """ | ||
| tokens = tokenize(sql, dialect=dialect) | ||
| if tokens is None: | ||
| return None | ||
|
|
||
| # Find the start of the model block | ||
| start_index = next( | ||
| ( | ||
| i | ||
| for i, t in enumerate(tokens) | ||
| if t.token_type is TokenType.VAR and t.text.upper() == "MODEL" | ||
| ), | ||
| None, | ||
| ) | ||
| end_index = next( | ||
| (i for i, t in enumerate(tokens) if t.token_type is TokenType.SEMICOLON), | ||
| None, | ||
| ) | ||
| if start_index is None or end_index is None: | ||
| return None | ||
| if start_index >= end_index: | ||
| return None | ||
|
|
||
| tokens_of_interest = tokens[start_index + 1 : end_index] | ||
| # Find the key token | ||
| key_token = next( | ||
| ( | ||
| t | ||
| for t in tokens_of_interest | ||
| if t.token_type is TokenType.VAR and t.text.upper() == key.upper() | ||
| ), | ||
| None, | ||
| ) | ||
|
Comment on lines
+195
to
+202
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just a heads up that this looks good as a best-effort approach, just not sure if it guarantees you'll match the exact token. Think that the token corresponding to the property's key could appear elsewhere in the Probably not worth trying to further improve it, but a simple heuristic if you notice any issues would be to check if the previous token is a comma, since properties are comma-separated. |
||
| if key_token is None: | ||
| return None | ||
|
|
||
| position = TokenPositionDetails( | ||
| line=key_token.line, | ||
| col=key_token.col, | ||
| start=key_token.start, | ||
| end=key_token.end, | ||
| ) | ||
| return position.to_range(sql.splitlines()) | ||
benfdking marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Uh oh!
There was an error while loading. Please reload this page.