Skip to content

tdfs4ds.agent.sql_cleanup

tdfs4ds.agent.sql_cleanup

Deterministic clean-ups of SQL written by the query optimizer's model.

Each function takes SQL text and returns SQL text, and is read through the lexer of :mod:tdfs4ds.utils.view_text: string literals (Teradata: '' is the only escape), quoted identifiers and comments are opaque tokens, so no rule ever edits the inside of a literal or a comment, and every match is on a whole token (ORDERS_AGG is not ORDER).

These clean-ups are applied to model candidates only, never to the SQL of a view as it is stored (skill_simplify_query), and the optimizer keeps one only when the candidate still compiles with it (_sanitize_and_analyze).

Rules, each with the shape that broke before:

  • comments are removed outside literals only (COALESCE(c, '--') stays);
  • back-quoted names become double-quoted names, outside literals only;
  • a derived table without alias gets _dtN only after a whole-word FROM / JOIN and only when the parenthesis holds a query;
  • a reserved word used as an alias is renamed only where it is a name: the alias itself and the places that refer to it; never a type after CAST(.. AS, a function call, WITH TIME ZONE, INTERVAL '1' DAY, EXTRACT(YEAR FROM, DATE '...', DAY(4) TO SECOND; and never a column name of the query's result (that is the view's interface);
  • an identity wrapper SELECT a, b FROM (SELECT a, b ...) x is flattened only when the outer column list is exactly the inner one, in the same order, and the inner query is not a set operation.

Pure, stdlib only, no database.

__all__ module-attribute

__all__ = ['PROACTIVE_RESERVED_ALIASES', 'strip_comments', 'backticks_to_quotes', 'rename_reserved_alias', 'rename_reserved_aliases_proactive', 'add_missing_derived_table_aliases', 'flatten_identity_wrapper', 'output_column_names']

PROACTIVE_RESERVED_ALIASES module-attribute

PROACTIVE_RESERVED_ALIASES = ('threshold', 'value', 'result', 'position', 'period', 'count', 'type', 'key', 'index', 'check', 'grant', 'role', 'default')

_SET_OPS module-attribute

_SET_OPS = {'UNION', 'INTERSECT', 'EXCEPT', 'MINUS'}

_AFTER_MISSING_ALIAS module-attribute

_AFTER_MISSING_ALIAS = {'WHERE', 'GROUP', 'ORDER', 'HAVING', 'QUALIFY', 'UNION', 'INTERSECT', 'EXCEPT', 'MINUS', 'ON', 'SAMPLE', 'JOIN', 'INNER', 'LEFT', 'RIGHT', 'FULL', 'CROSS'}

code_tokens

code_tokens(sql_or_tokens) -> list

The tokens that are neither whitespace nor comments.

matching_close

matching_close(toks: list, open_idx: int) -> int

Index in toks of the ) closing the ( at open_idx, or -1.

scan_sql

scan_sql(sql: str) -> list

Every token of sql, whitespace and comments included, in order.

Concatenating t.value of all tokens gives back sql exactly.

view_body

view_body(ddl: str) -> ViewText

Split ddl (a view definition or a plain query) into its parts.

Never raises: unreadable text gives header=None and the stripped text as body.

strip_comments

strip_comments(sql: str) -> str

sql without -- and /* */ comments; literals are left whole.

backticks_to_quotes

backticks_to_quotes(sql: str) -> str

Back-quoted names (a MySQL habit) as Teradata double-quoted names.

_bare

_bare(tok) -> str

_select_items

_select_items(t: list, sel: int, end: int, depth: int) -> list

Token lists of the select items between sel (the SELECT token) and end.

_item_name

_item_name(item: list, depth: int) -> Optional[str]

The output name of one select item, upper-cased, or None when unknown.

_main_select

_main_select(t: list)

(index of the main SELECT, index of its FROM or end) at depth 0, or None.

output_column_names

output_column_names(sql: str) -> Optional[list]

Names of the columns the query returns (upper-cased, None for an item whose name cannot be read), or None when the main SELECT is not found.

_regions

_regions(t: list) -> set

Indices of tokens that are type names or EXTRACT fields, never names.

_is_keyword_use

_is_keyword_use(t: list, i: int, skip: set) -> bool

True when the token at i is used as a keyword or a type, not a name.

_is_definition

_is_definition(t: list, i: int) -> str

'column', 'relation', 'cte' or '' for the name token at i.

_free_name

_free_name(sql: str, base: str) -> str

rename_reserved_alias

rename_reserved_alias(sql: str, word: str, new_name: Optional[str] = None) -> Optional[str]

sql with the alias word renamed where it is a name, or None.

None means nothing was renamed: word is not used as an alias, a quoted "word" exists (it could name the same thing), or renaming would change the column names of the query's result.

rename_reserved_aliases_proactive

rename_reserved_aliases_proactive(sql: str) -> tuple

(sql with the words of :data:PROACTIVE_RESERVED_ALIASES renamed where they are aliases, list of the words renamed).

add_missing_derived_table_aliases

add_missing_derived_table_aliases(sql: str) -> str

Give _dtN to every derived table (FROM (SELECT ...) / JOIN (SELECT ...)) that has no alias.

_literal_item

_literal_item(item: list) -> bool

'v' AS name / 42 AS name / -1 AS name.

_identity_name

_identity_name(item: list) -> Optional[str]

Column name of col / x.col / col AS col / x.col AS col, else None.

flatten_identity_wrapper

flatten_identity_wrapper(sql: str) -> str

Collapse SELECT <inner columns> [, 'lit' AS x] FROM (<inner>) [AS] alias into <inner> (literals appended to its select list).

Refused (text returned unchanged) when the outer column list is not exactly the inner one in the same order, when the inner query is a set operation, when the outer query has DISTINCT / TOP / any clause after the alias.