aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/udfs/common/json2/sql_query.h
blob: cb3bafd3b0b66bb9cefdb1f3762962f7a9ad9c46 (plain) (blame)
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
#pragma once

#include "resource.h"
#include "compile_path.h"

#include <yql/essentials/core/sql_types/yql_atom_enums.h>
#include <yql/essentials/public/udf/udf_type_builder.h>
#include <yql/essentials/public/udf/udf_value.h>
#include <yql/essentials/public/udf/udf_helpers.h>
#include <yql/essentials/minikql/dom/node.h>

#include <util/generic/yexception.h>

namespace NJson2Udf {
    using namespace NKikimr;
    using namespace NUdf;
    using namespace NYql;
    using namespace NDom;
    using namespace NJsonPath;

    template <EDataSlot InputType, EJsonQueryWrap Mode>
    class TSqlQuery: public TBoxedValue {
    public:
        explicit TSqlQuery(TSourcePosition pos)
            : Pos_(pos)
        {
        }

        static TStringRef Name();

        static bool DeclareSignature(
            const TStringRef& name,
            TType* userType,
            IFunctionTypeInfoBuilder& builder,
            bool typesOnly) {
            Y_UNUSED(userType);
            if (name != Name()) {
                return false;
            }

            auto jsonType = builder.Resource(JSON_NODE_RESOURCE_NAME);
            auto optionalJsonType = builder.Optional()->Item(jsonType).Build();
            TType* inputType = nullptr;
            if constexpr (InputType == EDataSlot::JsonDocument) {
                inputType = builder.SimpleType<TJsonDocument>();
            } else {
                inputType = jsonType;
            }
            auto inputOptionalType = builder.Optional()->Item(inputType).Build();
            auto jsonPathType = builder.Resource(JSONPATH_RESOURCE_NAME);
            auto dictType = builder.Dict()->Key<TUtf8>().Value(jsonType).Build();

            /*
            Arguments:
                0. Resource<JsonNode>? or JsonDocument?. Input json
                1. Resource<JsonPath>. Jsonpath to execute on json
                2. Dict<TUtf8, Resource<JsonNode>>. Variables to pass into jsonpath
                3. Bool. True - throw on empty result, false otherwise
                4. Resource<JsonNode>?. Default value to return on empty result. Ignored if 2d argument is true
                5. Bool. True - throw on error, false - otherwise
                6. Resource<JsonNode>?. Default value to return on error. Ignored if 4th argument is true
            */
            // we can't mark TSqlQuery as strict due to runtime throw policy setting
            // TODO: optimizer can mark SqlQuery as strict if 3th/5th arguments are literal booleans
            builder.Args()
                ->Add(inputOptionalType)
                .Add(jsonPathType)
                .Add(dictType)
                .Add<bool>()
                .Add(optionalJsonType)
                .Add<bool>()
                .Add(optionalJsonType)
                .Done()
                .Returns(optionalJsonType);

            if (!typesOnly) {
                builder.Implementation(new TSqlQuery(builder.GetSourcePosition()));
            }
            return true;
        }

    private:
        TUnboxedValue Run(
            const IValueBuilder* valueBuilder,
            const TUnboxedValuePod* args) const final {
            Y_UNUSED(valueBuilder);
            try {
                if (!args[0].HasValue()) {
                    return TUnboxedValuePod();
                }

                TValue jsonDom;
                if constexpr (InputType == EDataSlot::JsonDocument) {
                    jsonDom = TValue(NBinaryJson::TBinaryJsonReader::Make(args[0].AsStringRef())->GetRootCursor());
                } else {
                    jsonDom = TValue(args[0]);
                }

                auto* jsonPathResource = static_cast<TJsonPathResource*>(args[1].AsBoxed().Get());
                const auto& jsonPath = *jsonPathResource->Get();

                const bool throwOnEmpty = args[3].Get<bool>();
                const auto emptyDefault = args[4];
                const bool throwOnError = args[5].Get<bool>();
                const auto errorDefault = args[6];
                const auto variables = DictToVariables(args[2]);

                auto result = ExecuteJsonPath(jsonPath, jsonDom, variables, valueBuilder);

                const auto handleCase = [](TStringBuf message, bool throws, const TUnboxedValuePod& caseDefault) {
                    if (throws) {
                        ythrow yexception() << message;
                    }
                    return caseDefault;
                };

                if (result.IsError()) {
                    return handleCase(TStringBuilder() << "Error executing jsonpath:" << Endl << result.GetError() << Endl, throwOnError, errorDefault);
                }

                auto& nodes = result.GetNodes();
                const bool isSingleStruct = nodes.size() == 1 && (nodes[0].Is(EValueType::Array) || nodes[0].Is(EValueType::Object));
                if (Mode == EJsonQueryWrap::Wrap || (Mode == EJsonQueryWrap::ConditionalWrap && !isSingleStruct)) {
                    TVector<TUnboxedValue> converted;
                    converted.reserve(nodes.size());
                    for (auto& node : nodes) {
                        converted.push_back(node.ConvertToUnboxedValue(valueBuilder));
                    }
                    return MakeList(converted.data(), converted.size(), valueBuilder);
                }

                if (nodes.empty()) {
                    return handleCase("Empty result", throwOnEmpty, emptyDefault);
                }

                // No wrapping is applicable and result is not empty. Result must be a single object or array
                if (nodes.size() > 1) {
                    return handleCase("Result consists of multiple items", throwOnError, errorDefault);
                }

                if (!nodes[0].Is(EValueType::Array) && !nodes[0].Is(EValueType::Object)) {
                    return handleCase("Result is neither object nor array", throwOnError, errorDefault);
                }

                return nodes[0].ConvertToUnboxedValue(valueBuilder);
            } catch (const std::exception& e) {
                UdfTerminate((TStringBuilder() << Pos_ << " " << e.what()).data());
            }
        }

        TSourcePosition Pos_;
    };

    template <>
    TStringRef TSqlQuery<EDataSlot::Json, EJsonQueryWrap::NoWrap>::Name() {
        return "SqlQuery";
    }

    template <>
    TStringRef TSqlQuery<EDataSlot::Json, EJsonQueryWrap::Wrap>::Name() {
        return "SqlQueryWrap";
    }

    template <>
    TStringRef TSqlQuery<EDataSlot::Json, EJsonQueryWrap::ConditionalWrap>::Name() {
        return "SqlQueryConditionalWrap";
    }

    template <>
    TStringRef TSqlQuery<EDataSlot::JsonDocument, EJsonQueryWrap::NoWrap>::Name() {
        return "JsonDocumentSqlQuery";
    }

    template <>
    TStringRef TSqlQuery<EDataSlot::JsonDocument, EJsonQueryWrap::Wrap>::Name() {
        return "JsonDocumentSqlQueryWrap";
    }

    template <>
    TStringRef TSqlQuery<EDataSlot::JsonDocument, EJsonQueryWrap::ConditionalWrap>::Name() {
        return "JsonDocumentSqlQueryConditionalWrap";
    }
}