Edit on GitHub

sqlglot.anonymize

  1from __future__ import annotations
  2
  3import string
  4
  5from sqlglot.dialects.dialect import Dialect, DialectType
  6from sqlglot.errors import TokenError
  7from sqlglot.tokens import Token, TokenType
  8
  9
 10ALPHABET = string.ascii_lowercase
 11ALPHABET_SIZE = len(ALPHABET)
 12ANONYMIZED_TYPES = {
 13    TokenType.BIT_STRING,
 14    TokenType.BYTE_STRING,
 15    TokenType.HEX_STRING,
 16    TokenType.HEREDOC_STRING,
 17    TokenType.IDENTIFIER,
 18    TokenType.NATIONAL_RAW_STRING,
 19    TokenType.NATIONAL_STRING,
 20    TokenType.NUMBER,
 21    TokenType.RAW_STRING,
 22    TokenType.STRING,
 23    TokenType.UNICODE_STRING,
 24    TokenType.UNICODE_IDENTIFIER,
 25    TokenType.VAR,
 26}
 27QUOTED_TYPES = ANONYMIZED_TYPES - {TokenType.NUMBER, TokenType.VAR}
 28REWRITTEN_TYPES = {TokenType.HINT, TokenType.UNKNOWN}
 29
 30
 31def anonymize(
 32    sql_or_tokens: list[Token] | str,
 33    dialect: DialectType = None,
 34) -> list[Token]:
 35    """Replaces sensitive tokens (identifiers, strings, numbers) with fixed-width,
 36    length-preserving, consistent aliases, and blanks out comments and hint bodies. When a
 37    SQL string is given, it is tokenized with `dialect` first; any un-tokenized remainder
 38    (e.g. an unterminated literal) is appended as a blanked UNKNOWN token. Mutates and
 39    returns `sql_or_tokens`.
 40
 41    Args:
 42        sql_or_tokens: The SQL string to anonymize, or its token list.
 43        dialect: The dialect used to tokenize a SQL string.
 44    """
 45    dialect = Dialect.get_or_raise(dialect)
 46    tokenizer_class = dialect.tokenizer_class
 47    parser_class = dialect.parser_class
 48
 49    errored = False
 50    if isinstance(sql_or_tokens, str):
 51        sql = sql_or_tokens
 52        tokenizer = dialect.tokenizer()
 53        try:
 54            tokens = tokenizer.tokenize(sql)
 55        except TokenError:
 56            tokens = tokenizer.tokens
 57            errored = True
 58    else:
 59        tokens = sql_or_tokens
 60        sql = None
 61
 62    hint_start = tokenizer_class.HINT_START
 63    hint_end = tokenizer_class._COMMENTS.get(hint_start)
 64    nested = tokenizer_class.NESTED_COMMENTS
 65
 66    seen: dict[tuple[bool, str], str] = {}
 67    counter = 0
 68
 69    for i, token in enumerate(tokens):
 70        token.comments = [_blank(comment) for comment in token.comments]
 71
 72        if token.token_type == TokenType.HINT:
 73            # A hint's text is the whole /*+ ... */ comment, so its body is blanked as well
 74            text, stop = _blank_comment(token.text, 0, hint_start, hint_end, nested)
 75            token.text = text + _blank(token.text[stop:])
 76            continue
 77
 78        if (
 79            token.token_type == TokenType.VAR
 80            and i + 1 < len(tokens)
 81            and tokens[i + 1].token_type == TokenType.L_PAREN
 82        ):
 83            # A function name can live in either registry, e.g. JSON_OBJECT is only in
 84            # FUNCTION_PARSERS. They're consulted separately to avoid building their union
 85            name = token.text.upper()
 86            if name in parser_class.FUNCTIONS or name in parser_class.FUNCTION_PARSERS:
 87                continue
 88        if token.token_type not in ANONYMIZED_TYPES:
 89            continue
 90        if not token.text:
 91            continue
 92
 93        is_number = token.token_type == TokenType.NUMBER
 94        key = (is_number, token.text)
 95        alias = seen.get(key)
 96        if alias is None:
 97            seen[key] = (
 98                _number_alias(counter, token.text) if is_number else _alias(counter, token.text)
 99            )
100            counter += 1
101        token.text = seen[key]
102
103    if sql is not None and errored:
104        start = tokens[-1].end + 1 if tokens else 0
105        length = len(sql)
106        while start < length and sql[start].isspace():
107            start += 1
108        if start < length:
109            # The first two characters are kept so that the delimiter the tokenizer choked
110            # on is still visible, e.g. 'u, /*, $$, `u
111            tokens.append(
112                Token(
113                    TokenType.UNKNOWN,
114                    sql[start : start + 2] + "." * (length - start - 2),
115                    start=start,
116                    end=length - 1,
117                    line=sql.count("\n", 0, start) + 1,
118                    col=start - sql.rfind("\n", 0, start),
119                )
120            )
121
122    return tokens
123
124
125def render(sql: str, tokens: list[Token], dialect: DialectType = None) -> str:
126    """Recreates the (anonymized) SQL string from the original `sql` and token positions.
127
128    Every token is rendered over its own source span, so the result is always as long as
129    `sql`: a token that wasn't anonymized is emitted verbatim, keeping the spelling the
130    tokenizer normalized away, and an anonymized one has its alias fitted between the
131    quotes of its span. The gaps between tokens hold only whitespace and comments, so
132    they're redacted rather than reconstructed: comment markers and whitespace survive,
133    everything else is blanked. That covers anything the tokenizer didn't reach as well,
134    which is a trailing gap whenever `anonymize` wasn't the one to tokenize `sql`.
135
136    Args:
137        sql: The original SQL string.
138        tokens: The anonymized tokens to render.
139        dialect: The dialect used to identify comments and quotes in `sql`.
140    """
141    tokenizer_class = Dialect.get_or_raise(dialect).tokenizer_class
142    comments = sorted(tokenizer_class._COMMENTS.items(), key=lambda c: len(c[0]), reverse=True)
143    nested = tokenizer_class.NESTED_COMMENTS
144    quotes = sorted(
145        {
146            **tokenizer_class._QUOTES,
147            **{start: end for start, (end, _) in tokenizer_class._FORMAT_STRINGS.items()},
148            **tokenizer_class._IDENTIFIERS,
149        }.items(),
150        key=lambda quote: (len(quote[0]), len(quote[1])),
151        reverse=True,
152    )
153
154    result = []
155    prev = 0
156    uescape_alias = ""
157
158    for i, token in enumerate(tokens):
159        result.append(_redact(sql[prev : token.start], comments, nested))
160        prev = token.end + 1
161        span = sql[token.start : prev]
162        if token.token_type in REWRITTEN_TYPES:
163            # Blanked in place by `anonymize`, or synthesized by it, so already span-shaped
164            result.append(token.text)
165        elif token.token_type in ANONYMIZED_TYPES:
166            result.append(_fit(span, token.text, quotes, token.token_type))
167        elif token.token_type == TokenType.UESCAPE:
168            if token.text.upper() == "UESCAPE":
169                uescape_alias = tokens[i - 1].text
170            elif token.text and token.text in uescape_alias:
171                # Keep the alias literal when it contains the clause's escape character.
172                span = "'!'".ljust(len(span))
173            result.append(span)
174        else:
175            result.append(span)
176
177    result.append(_redact(sql[prev:], comments, nested))
178
179    return "".join(result)
180
181
182def _alias(counter: int, text: str) -> str:
183    digits = []
184    while counter:
185        counter, digit = divmod(counter, ALPHABET_SIZE)
186        digits.append(ALPHABET[digit])
187
188    letters = "".join(reversed(digits)).rjust(sum(not char.isspace() for char in text), "a")
189
190    alias = []
191    i = 0
192    for char in text:
193        if char.isspace():
194            alias.append(char)
195        else:
196            alias.append(letters[i])
197            i += 1
198
199    return "".join(alias)
200
201
202def _number_alias(counter: int, text: str) -> str:
203    if len(text) > 4000:
204        digits_seen = False
205        blanked = []
206        for char in text:
207            if char.isdigit():
208                blanked.append("0" if digits_seen else "1")
209                digits_seen = True
210            else:
211                blanked.append(char)
212        return "".join(blanked)
213
214    sep = "e" if "e" in text else ("E" if "E" in text else "")
215    mantissa, _, exponent = text.partition(sep) if sep else (text, "", "")
216    sign = ""
217    if exponent.startswith(("-", "+")):
218        sign, exponent = exponent[0], exponent[1:]
219    exponent_length = len(exponent)
220
221    integer, dot, fraction = mantissa.partition(".")
222    integer_length = len(integer)
223    digits = integer_length + len(fraction)
224    mantissa_value = 10 ** (digits - 1) + counter % (9 * 10 ** (digits - 1))
225    result = str(mantissa_value)
226    if dot:
227        result = result[:integer_length] + "." + result[integer_length:]
228    if sep:
229        # The exponent marker is kept even when there are no digits after it, e.g. 1e
230        result += sep + sign
231        if exponent_length:
232            exponent_value = 10 ** (exponent_length - 1) + (counter // (9 * 10 ** (digits - 1))) % (
233                9 * 10 ** (exponent_length - 1)
234            )
235            result += str(exponent_value)
236
237    return result
238
239
240def _fit(span: str, alias: str, quotes: list[tuple[str, str]], token_type: TokenType) -> str:
241    """Fits `alias` into the quoted region of `span`, so the two are always the same length."""
242    start = end = 0
243
244    if token_type in QUOTED_TYPES:
245        for open_quote, close_quote in quotes:
246            if (
247                len(span) >= len(open_quote) + len(close_quote)
248                and span.startswith(open_quote)
249                and span.endswith(close_quote)
250            ):
251                start, end = len(open_quote), len(close_quote)
252
253                if token_type == TokenType.HEREDOC_STRING:
254                    # A heredoc's tag is part of its delimiter, e.g. $tag$body$tag$
255                    open_end = span.find(close_quote, start)
256                    close_start = span.rfind(open_quote, 0, len(span) - end)
257                    if start <= open_end < close_start:
258                        start, end = open_end + len(close_quote), len(span) - close_start
259
260                break
261
262    width = len(span) - start - end
263    if token_type == TokenType.IDENTIFIER and end and len(alias) < width:
264        return (span[:start] + alias + span[-end:]).ljust(len(span))
265    pad = "0" if token_type == TokenType.NUMBER else "a"
266
267    return span[:start] + alias[:width].rjust(width, pad) + span[len(span) - end :]
268
269
270def _blank(sql: str) -> str:
271    return "".join(char if char.isspace() else "." for char in sql)
272
273
274def _blank_comment(sql: str, i: int, start: str, end: str | None, nested: bool) -> tuple[str, int]:
275    """Blanks the body of the comment at `i`, returning its text and the index past it."""
276    body = i + len(start)
277
278    if not end:
279        stop = sql.find("\n", body)
280        stop = len(sql) if stop == -1 else stop
281        return start + _blank(sql[body:stop]), stop
282
283    depth = 1
284    j = body
285    while j < len(sql):
286        if nested and sql.startswith(start, j):
287            depth += 1
288            j += len(start)
289        elif sql.startswith(end, j):
290            j += len(end)
291            depth -= 1
292            if not depth:
293                return start + _blank(sql[body : j - len(end)]) + end, j
294        else:
295            j += 1
296
297    return start + _blank(sql[body:]), len(sql)
298
299
300def _redact(sql: str, comments: list[tuple[str, str | None]], nested: bool) -> str:
301    if not sql or sql.isspace():
302        return sql
303
304    result = []
305    i = 0
306    length = len(sql)
307
308    while i < length:
309        for start, end in comments:
310            if sql.startswith(start, i):
311                text, i = _blank_comment(sql, i, start, end, nested)
312                result.append(text)
313                break
314        else:
315            char = sql[i]
316            result.append(char if char.isspace() else ".")
317            i += 1
318
319    return "".join(result)
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
ALPHABET_SIZE = 26
ANONYMIZED_TYPES = {<TokenType.NATIONAL_RAW_STRING: 96>, <TokenType.NATIONAL_STRING: 97>, <TokenType.RAW_STRING: 98>, <TokenType.HEREDOC_STRING: 99>, <TokenType.UNICODE_STRING: 100>, <TokenType.UNICODE_IDENTIFIER: 101>, <TokenType.STRING: 80>, <TokenType.NUMBER: 81>, <TokenType.IDENTIFIER: 82>, <TokenType.VAR: 92>, <TokenType.BIT_STRING: 93>, <TokenType.HEX_STRING: 94>, <TokenType.BYTE_STRING: 95>}
QUOTED_TYPES = {<TokenType.NATIONAL_RAW_STRING: 96>, <TokenType.NATIONAL_STRING: 97>, <TokenType.RAW_STRING: 98>, <TokenType.HEREDOC_STRING: 99>, <TokenType.UNICODE_STRING: 100>, <TokenType.UNICODE_IDENTIFIER: 101>, <TokenType.STRING: 80>, <TokenType.IDENTIFIER: 82>, <TokenType.BIT_STRING: 93>, <TokenType.HEX_STRING: 94>, <TokenType.BYTE_STRING: 95>}
REWRITTEN_TYPES = {<TokenType.UNKNOWN: 222>, <TokenType.HINT: 303>}
def anonymize( sql_or_tokens: list[sqlglot.tokenizer_core.Token] | str, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None) -> list[sqlglot.tokenizer_core.Token]:
 32def anonymize(
 33    sql_or_tokens: list[Token] | str,
 34    dialect: DialectType = None,
 35) -> list[Token]:
 36    """Replaces sensitive tokens (identifiers, strings, numbers) with fixed-width,
 37    length-preserving, consistent aliases, and blanks out comments and hint bodies. When a
 38    SQL string is given, it is tokenized with `dialect` first; any un-tokenized remainder
 39    (e.g. an unterminated literal) is appended as a blanked UNKNOWN token. Mutates and
 40    returns `sql_or_tokens`.
 41
 42    Args:
 43        sql_or_tokens: The SQL string to anonymize, or its token list.
 44        dialect: The dialect used to tokenize a SQL string.
 45    """
 46    dialect = Dialect.get_or_raise(dialect)
 47    tokenizer_class = dialect.tokenizer_class
 48    parser_class = dialect.parser_class
 49
 50    errored = False
 51    if isinstance(sql_or_tokens, str):
 52        sql = sql_or_tokens
 53        tokenizer = dialect.tokenizer()
 54        try:
 55            tokens = tokenizer.tokenize(sql)
 56        except TokenError:
 57            tokens = tokenizer.tokens
 58            errored = True
 59    else:
 60        tokens = sql_or_tokens
 61        sql = None
 62
 63    hint_start = tokenizer_class.HINT_START
 64    hint_end = tokenizer_class._COMMENTS.get(hint_start)
 65    nested = tokenizer_class.NESTED_COMMENTS
 66
 67    seen: dict[tuple[bool, str], str] = {}
 68    counter = 0
 69
 70    for i, token in enumerate(tokens):
 71        token.comments = [_blank(comment) for comment in token.comments]
 72
 73        if token.token_type == TokenType.HINT:
 74            # A hint's text is the whole /*+ ... */ comment, so its body is blanked as well
 75            text, stop = _blank_comment(token.text, 0, hint_start, hint_end, nested)
 76            token.text = text + _blank(token.text[stop:])
 77            continue
 78
 79        if (
 80            token.token_type == TokenType.VAR
 81            and i + 1 < len(tokens)
 82            and tokens[i + 1].token_type == TokenType.L_PAREN
 83        ):
 84            # A function name can live in either registry, e.g. JSON_OBJECT is only in
 85            # FUNCTION_PARSERS. They're consulted separately to avoid building their union
 86            name = token.text.upper()
 87            if name in parser_class.FUNCTIONS or name in parser_class.FUNCTION_PARSERS:
 88                continue
 89        if token.token_type not in ANONYMIZED_TYPES:
 90            continue
 91        if not token.text:
 92            continue
 93
 94        is_number = token.token_type == TokenType.NUMBER
 95        key = (is_number, token.text)
 96        alias = seen.get(key)
 97        if alias is None:
 98            seen[key] = (
 99                _number_alias(counter, token.text) if is_number else _alias(counter, token.text)
100            )
101            counter += 1
102        token.text = seen[key]
103
104    if sql is not None and errored:
105        start = tokens[-1].end + 1 if tokens else 0
106        length = len(sql)
107        while start < length and sql[start].isspace():
108            start += 1
109        if start < length:
110            # The first two characters are kept so that the delimiter the tokenizer choked
111            # on is still visible, e.g. 'u, /*, $$, `u
112            tokens.append(
113                Token(
114                    TokenType.UNKNOWN,
115                    sql[start : start + 2] + "." * (length - start - 2),
116                    start=start,
117                    end=length - 1,
118                    line=sql.count("\n", 0, start) + 1,
119                    col=start - sql.rfind("\n", 0, start),
120                )
121            )
122
123    return tokens

Replaces sensitive tokens (identifiers, strings, numbers) with fixed-width, length-preserving, consistent aliases, and blanks out comments and hint bodies. When a SQL string is given, it is tokenized with dialect first; any un-tokenized remainder (e.g. an unterminated literal) is appended as a blanked UNKNOWN token. Mutates and returns sql_or_tokens.

Arguments:
  • sql_or_tokens: The SQL string to anonymize, or its token list.
  • dialect: The dialect used to tokenize a SQL string.
def render( sql: str, tokens: list[sqlglot.tokenizer_core.Token], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None) -> str:
126def render(sql: str, tokens: list[Token], dialect: DialectType = None) -> str:
127    """Recreates the (anonymized) SQL string from the original `sql` and token positions.
128
129    Every token is rendered over its own source span, so the result is always as long as
130    `sql`: a token that wasn't anonymized is emitted verbatim, keeping the spelling the
131    tokenizer normalized away, and an anonymized one has its alias fitted between the
132    quotes of its span. The gaps between tokens hold only whitespace and comments, so
133    they're redacted rather than reconstructed: comment markers and whitespace survive,
134    everything else is blanked. That covers anything the tokenizer didn't reach as well,
135    which is a trailing gap whenever `anonymize` wasn't the one to tokenize `sql`.
136
137    Args:
138        sql: The original SQL string.
139        tokens: The anonymized tokens to render.
140        dialect: The dialect used to identify comments and quotes in `sql`.
141    """
142    tokenizer_class = Dialect.get_or_raise(dialect).tokenizer_class
143    comments = sorted(tokenizer_class._COMMENTS.items(), key=lambda c: len(c[0]), reverse=True)
144    nested = tokenizer_class.NESTED_COMMENTS
145    quotes = sorted(
146        {
147            **tokenizer_class._QUOTES,
148            **{start: end for start, (end, _) in tokenizer_class._FORMAT_STRINGS.items()},
149            **tokenizer_class._IDENTIFIERS,
150        }.items(),
151        key=lambda quote: (len(quote[0]), len(quote[1])),
152        reverse=True,
153    )
154
155    result = []
156    prev = 0
157    uescape_alias = ""
158
159    for i, token in enumerate(tokens):
160        result.append(_redact(sql[prev : token.start], comments, nested))
161        prev = token.end + 1
162        span = sql[token.start : prev]
163        if token.token_type in REWRITTEN_TYPES:
164            # Blanked in place by `anonymize`, or synthesized by it, so already span-shaped
165            result.append(token.text)
166        elif token.token_type in ANONYMIZED_TYPES:
167            result.append(_fit(span, token.text, quotes, token.token_type))
168        elif token.token_type == TokenType.UESCAPE:
169            if token.text.upper() == "UESCAPE":
170                uescape_alias = tokens[i - 1].text
171            elif token.text and token.text in uescape_alias:
172                # Keep the alias literal when it contains the clause's escape character.
173                span = "'!'".ljust(len(span))
174            result.append(span)
175        else:
176            result.append(span)
177
178    result.append(_redact(sql[prev:], comments, nested))
179
180    return "".join(result)

Recreates the (anonymized) SQL string from the original sql and token positions.

Every token is rendered over its own source span, so the result is always as long as sql: a token that wasn't anonymized is emitted verbatim, keeping the spelling the tokenizer normalized away, and an anonymized one has its alias fitted between the quotes of its span. The gaps between tokens hold only whitespace and comments, so they're redacted rather than reconstructed: comment markers and whitespace survive, everything else is blanked. That covers anything the tokenizer didn't reach as well, which is a trailing gap whenever anonymize wasn't the one to tokenize sql.

Arguments:
  • sql: The original SQL string.
  • tokens: The anonymized tokens to render.
  • dialect: The dialect used to identify comments and quotes in sql.