Renames aliases to a consistent format (e.g., using T#).
(sql)
| 42 | |
| 43 | |
| 44 | def anonymize_aliases(sql): |
| 45 | """Renames aliases to a consistent format (e.g., using T#).""" |
| 46 | sql_tokens = list() |
| 47 | tokens = SQLTokenizer().tokenize(sql) |
| 48 | |
| 49 | # First, split all TABLE.COLUMN examples into three tokens. |
| 50 | for token in tokens: |
| 51 | token = token.replace('"', '\'') |
| 52 | if token != '.' and token.count('.') == 1 and not token.replace( |
| 53 | '.', '', 1).isnumeric(): |
| 54 | table, column = token.split('.') |
| 55 | sql_tokens.extend([table, '.', column]) |
| 56 | else: |
| 57 | sql_tokens.append(token) |
| 58 | |
| 59 | # Create an alias dictionary that maps from table names to column names |
| 60 | alias_dict = dict() |
| 61 | for token in sql_tokens: |
| 62 | if 'alias' in token and token not in alias_dict: |
| 63 | alias_dict[token] = 'T' + str(len(alias_dict) + 1) |
| 64 | |
| 65 | # Reconstruct the SQL query, this time replacing old alias names with the new |
| 66 | # assigned alias names. |
| 67 | new_tokens = list() |
| 68 | for token in sql_tokens: |
| 69 | if token in alias_dict: |
| 70 | new_tokens.append(alias_dict[token]) |
| 71 | else: |
| 72 | new_tokens.append(token) |
| 73 | |
| 74 | return new_tokens |
| 75 | |
| 76 | |
| 77 | def preprocess_sql(sql): |
no test coverage detected
searching dependent graphs…