Edit on GitHub

sqlglot.jsonpath

  1from __future__ import annotations
  2
  3import typing as t
  4
  5import sqlglot.expressions as exp
  6from sqlglot.errors import ParseError
  7from sqlglot.tokens import Token, Tokenizer, TokenType
  8
  9if t.TYPE_CHECKING:
 10    from sqlglot.dialects.dialect import DialectType
 11    from collections.abc import Collection
 12
 13
 14class JSONPathTokenizer(Tokenizer):
 15    SINGLE_TOKENS = {
 16        "(": TokenType.L_PAREN,
 17        ")": TokenType.R_PAREN,
 18        "[": TokenType.L_BRACKET,
 19        "]": TokenType.R_BRACKET,
 20        ":": TokenType.COLON,
 21        ",": TokenType.COMMA,
 22        "-": TokenType.DASH,
 23        ".": TokenType.DOT,
 24        "?": TokenType.PLACEHOLDER,
 25        "@": TokenType.PARAMETER,
 26        "'": TokenType.QUOTE,
 27        '"': TokenType.QUOTE,
 28        "$": TokenType.DOLLAR,
 29        "*": TokenType.STAR,
 30    }
 31
 32    KEYWORDS = {
 33        "..": TokenType.DOT,
 34    }
 35
 36    IDENTIFIER_ESCAPES = ["\\"]
 37    STRING_ESCAPES = ["\\"]
 38    NUMBERS_CAN_HAVE_DECIMALS = False
 39
 40    VAR_TOKENS = {
 41        TokenType.VAR,
 42    }
 43
 44
 45def parse(path: str, dialect: DialectType = None) -> exp.JSONPath:
 46    """Takes in a JSON path string and parses it into a JSONPath expression."""
 47    from sqlglot.dialects import Dialect
 48
 49    dialect_inst = Dialect.get_or_raise(dialect)
 50    jsonpath_tokenizer = dialect_inst.jsonpath_tokenizer()
 51    tokens = jsonpath_tokenizer.tokenize(path)
 52    size = len(tokens)
 53
 54    i = 0
 55
 56    def _curr() -> TokenType | None:
 57        return tokens[i].token_type if i < size else None
 58
 59    def _prev() -> Token:
 60        return tokens[i - 1]
 61
 62    def _advance() -> Token:
 63        nonlocal i
 64        i += 1
 65        return _prev()
 66
 67    def _error(msg: str) -> str:
 68        return f"{msg} at index {i}: {path}"
 69
 70    @t.overload
 71    def _match(token_type: TokenType, raise_unmatched: t.Literal[True] = True) -> Token:
 72        pass
 73
 74    @t.overload
 75    def _match(token_type: TokenType, raise_unmatched: t.Literal[False] = False) -> Token | None:
 76        pass
 77
 78    def _match(token_type, raise_unmatched=False):
 79        if _curr() == token_type:
 80            return _advance()
 81        if raise_unmatched:
 82            raise ParseError(_error(f"Expected {token_type}"))
 83        return None
 84
 85    def _match_set(types: Collection[TokenType]) -> Token | None:
 86        return _advance() if _curr() in types else None
 87
 88    def _parse_literal() -> t.Any:
 89        token = _match(TokenType.STRING) or _match(TokenType.IDENTIFIER)
 90        if token:
 91            return token.text
 92        if _match(TokenType.STAR):
 93            return exp.JSONPathWildcard()
 94        if _match(TokenType.PLACEHOLDER) or _match(TokenType.L_PAREN):
 95            script = _prev().text == "("
 96            start = i
 97
 98            while True:
 99                if _match(TokenType.L_BRACKET):
100                    _parse_bracket()  # nested call which we can throw away
101                if _curr() in (TokenType.R_BRACKET, None):
102                    break
103                _advance()
104
105            expr_type = exp.JSONPathScript if script else exp.JSONPathFilter
106            end = tokens[i].end if i < size else tokens[-1].end
107            return expr_type(this=path[tokens[start].start : end])
108
109        number = "-" if _match(TokenType.DASH) else ""
110
111        token = _match(TokenType.NUMBER)
112        if token:
113            number += token.text
114
115        if number:
116            try:
117                return int(number)
118            except ValueError:
119                raise ParseError(_error(f"Invalid integer index: {number}"))
120
121        return False
122
123    def _parse_slice() -> t.Any:
124        start = _parse_literal()
125        end = _parse_literal() if _match(TokenType.COLON) else None
126        step = _parse_literal() if _match(TokenType.COLON) else None
127
128        if end is None and step is None:
129            return start
130
131        return exp.JSONPathSlice(start=start, end=end, step=step)
132
133    def _parse_bracket() -> exp.JSONPathPart:
134        literal = _parse_slice()
135
136        if isinstance(literal, str) or literal is not False:
137            indexes = [literal]
138            while _match(TokenType.COMMA):
139                literal = _parse_slice()
140
141                if isinstance(literal, str) or literal is not False:
142                    indexes.append(literal)
143
144            if len(indexes) == 1:
145                if isinstance(indexes[0], str):
146