summaryrefslogtreecommitdiffstats
path: root/sqlglot/jsonpath.py
blob: c410d119d8103b27a91ee1d5c590508eae59a94e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
from __future__ import annotations

import typing as t

from sqlglot.errors import ParseError
from sqlglot.expressions import SAFE_IDENTIFIER_RE
from sqlglot.tokens import Token, Tokenizer, TokenType

if t.TYPE_CHECKING:
    from sqlglot._typing import Lit


class JSONPathTokenizer(Tokenizer):
    SINGLE_TOKENS = {
        "(": TokenType.L_PAREN,
        ")": TokenType.R_PAREN,
        "[": TokenType.L_BRACKET,
        "]": TokenType.R_BRACKET,
        ":": TokenType.COLON,
        ",": TokenType.COMMA,
        "-": TokenType.DASH,
        ".": TokenType.DOT,
        "?": TokenType.PLACEHOLDER,
        "@": TokenType.PARAMETER,
        "'": TokenType.QUOTE,
        '"': TokenType.QUOTE,
        "$": TokenType.DOLLAR,
        "*": TokenType.STAR,
    }

    KEYWORDS = {
        "..": TokenType.DOT,
    }

    IDENTIFIER_ESCAPES = ["\\"]
    STRING_ESCAPES = ["\\"]


JSONPathNode = t.Dict[str, t.Any]


def _node(kind: str, value: t.Any = None, **kwargs: t.Any) -> JSONPathNode:
    node = {"kind": kind, **kwargs}

    if value is not None:
        node["value"] = value

    return node


def parse(path: str) -> t.List[JSONPathNode]:
    """Takes in a JSONPath string and converts into a list of nodes."""
    tokens = JSONPathTokenizer().tokenize(path)
    size = len(tokens)

    i = 0

    def _curr() -> t.Optional[TokenType]:
        return tokens[i].token_type if i < size else None

    def _prev() -> Token:
        return tokens[i - 1]

    def _advance() -> Token:
        nonlocal i
        i += 1
        return _prev()

    def _error(msg: str) -> str:
        return f"{msg} at index {i}: {path}"

    @t.overload
    def _match(token_type: TokenType, raise_unmatched: Lit[True] = True) -> Token:
        pass

    @t.overload
    def _match(token_type: TokenType, raise_unmatched: Lit[False] = False) -> t.Optional[Token]:
        pass

    def _match(token_type, raise_unmatched=False):
        if _curr() == token_type:
            return _advance()
        if raise_unmatched:
            raise ParseError(_error(f"Expected {token_type}"))
        return None

    def _parse_literal() -> t.Any:
        token = _match(TokenType.STRING) or _match(TokenType.IDENTIFIER)
        if token:
            return token.text
        if _match(TokenType.STAR):
            return _node("wildcard")
        if _match(TokenType.PLACEHOLDER) or _match(TokenType.L_PAREN):
            script = _prev().text == "("
            start = i

            while True:
                if _match(TokenType.L_BRACKET):
                    _parse_bracket()  # nested call which we can throw away
                if _curr() in (TokenType.R_BRACKET, None):
                    break
                _advance()
            return _node(
                "script" if script else "filter", path[tokens[start].start : tokens[i].end]
            )

        number = "-" if _match(TokenType.DASH) else ""

        token = _match(TokenType.NUMBER)
        if token:
            number += token.text

        if number:
            return int(number)
        return False

    def _parse_slice() -> t.Any:
        start = _parse_literal()
        end = _parse_literal() if _match(TokenType.COLON) else None
        step = _parse_literal() if _match(TokenType.COLON) else None

        if end is None and step is None:
            return start
        return _node("slice", start=start, end=end, step=step)

    def _parse_bracket() -> JSONPathNode:
        literal = _parse_slice()

        if isinstance(literal, str) or literal is not False:
            indexes = [literal]
            while _match(TokenType.COMMA):
                literal = _parse_slice()

                if literal:
                    indexes.append(literal)

            if len(indexes) == 1:
                if isinstance(literal, str):
                    node = _node("key", indexes[0])
                elif isinstance(literal, dict) and literal["kind"] in ("script", "filter"):
                    node = _node("selector", indexes[0])
                else:
                    node = _node("subscript", indexes[0])
            else:
                node = _node("union", indexes)
        else:
            raise ParseError(_error("Cannot have empty segment"))

        _match(TokenType.R_BRACKET, raise_unmatched=True)

        return node

    nodes = []

    while _curr():
        if _match(TokenType.DOLLAR):
            nodes.append(_node("root"))
        elif _match(TokenType.DOT):
            recursive = _prev().text == ".."
            value = _match(TokenType.VAR) or _match(TokenType.STAR)
            nodes.append(
                _node("recursive" if recursive else "child", value=value.text if value else None)
            )
        elif _match(TokenType.L_BRACKET):
            nodes.append(_parse_bracket())
        elif _match(TokenType.VAR):
            nodes.append(_node("key", _prev().text))
        elif _match(TokenType.STAR):
            nodes.append(_node("wildcard"))
        elif _match(TokenType.PARAMETER):
            nodes.append(_node("current"))
        else:
            raise ParseError(_error(f"Unexpected {tokens[i].token_type}"))

    return nodes


MAPPING = {
    "child": lambda n: f".{n['value']}" if n.get("value") is not None else "",
    "filter": lambda n: f"?{n['value']}",
    "key": lambda n: (
        f".{n['value']}" if SAFE_IDENTIFIER_RE.match(n["value"]) else f'[{generate([n["value"]])}]'
    ),
    "recursive": lambda n: f"..{n['value']}" if n.get("value") is not None else "..",
    "root": lambda _: "$",
    "script": lambda n: f"({n['value']}",
    "slice": lambda n: ":".join(
        "" if p is False else generate([p])
        for p in [n["start"], n["end"], n["step"]]
        if p is not None
    ),
    "selector": lambda n: f"[{generate([n['value']])}]",
    "subscript": lambda n: f"[{generate([n['value']])}]",
    "union": lambda n: f"[{','.join(generate([p]) for p in n['value'])}]",
    "wildcard": lambda _: "*",
}


def generate(
    nodes: t.List[JSONPathNode],
    mapping: t.Optional[t.Dict[str, t.Callable[[JSONPathNode], str]]] = None,
) -> str:
    mapping = MAPPING if mapping is None else mapping
    path = []

    for node in nodes:
        if isinstance(node, dict):
            path.append(mapping[node["kind"]](node))
        elif isinstance(node, str):
            escaped = node.replace('"', '\\"')
            path.append(f'"{escaped}"')
        else:
            path.append(str(node))

    return "".join(path)