aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/providers/pure/yql_pure_provider.cpp
blob: a87d7cfdad864ce04ebd1dba336db37fb7c752a2 (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
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#include "yql_pure_provider.h"

#include <yql/essentials/core/yql_type_annotation.h>
#include <yql/essentials/core/yql_graph_transformer.h>
#include <yql/essentials/core/yql_expr_type_annotation.h>
#include <yql/essentials/core/peephole_opt/yql_opt_peephole_physical.h>
#include <yql/essentials/utils/log/log.h>
#include <yql/essentials/providers/common/provider/yql_provider_names.h>
#include <yql/essentials/providers/common/provider/yql_data_provider_impl.h>
#include <yql/essentials/providers/common/provider/yql_provider.h>
#include <yql/essentials/providers/common/codec/yql_codec.h>
#include <yql/essentials/providers/common/schema/expr/yql_expr_schema.h>
#include <yql/essentials/providers/common/transform/yql_exec.h>
#include <yql/essentials/providers/common/transform/yql_lazy_init.h>
#include <yql/essentials/providers/common/mkql/yql_provider_mkql.h>
#include <yql/essentials/providers/common/mkql_simple_file/mkql_simple_file.h>
#include <yql/essentials/providers/result/expr_nodes/yql_res_expr_nodes.h>
#include <yql/essentials/minikql/computation/mkql_computation_node.h>
#include <yql/essentials/minikql/mkql_program_builder.h>
#include <yql/essentials/minikql/mkql_node_cast.h>
#include <yql/essentials/minikql/mkql_opt_literal.h>
#include <yql/essentials/minikql/comp_nodes/mkql_factories.h>
#include <yql/essentials/parser/pg_wrapper/interface/comp_factory.h>
#include <yql/essentials/providers/common/comp_nodes/yql_factory.h>

#include <util/stream/length.h>

namespace NYql {

namespace {

using namespace NKikimr;
using namespace NKikimr::NMiniKQL;

class TPureDataSinkExecTransformer : public TExecTransformerBase {
public:
    TPureDataSinkExecTransformer(const TPureState::TPtr state)
        : State_(state)
    {
        AddHandler({TStringBuf("Result")}, RequireNone(), Hndl(&TPureDataSinkExecTransformer::HandleRes));
    }

    void Rewind() override {
        TExecTransformerBase::Rewind();
    }

    TStatusCallbackPair HandleRes(const TExprNode::TPtr& input, TExprContext& ctx) {
        YQL_CLOG(DEBUG, ProviderPure) << "Executing " << input->Content() << " (UniqueId=" << input->UniqueId() << ")";
        if (TStringBuf("Result") != input->Content()) {
            ythrow yexception() << "Don't know how to execute " << input->Content();
        }

        NNodes::TResOrPullBase resOrPull(input);

        IDataProvider::TFillSettings fillSettings = NCommon::GetFillSettings(resOrPull.Ref());
        YQL_ENSURE(fillSettings.Format == IDataProvider::EResultFormat::Yson);

        auto lambda = resOrPull.Input();

        if (!IsPureIsolatedLambda(lambda.Ref())) {
            ctx.AddError(TIssue(ctx.GetPosition(lambda.Pos()), TStringBuilder() << "Failed to execute node due to bad graph: " << input->Content()));
            return SyncError();
        }

        const bool isList = lambda.Ref().GetTypeAnn()->GetKind() == ETypeAnnotationKind::List;
        auto optimized = lambda.Ptr();
        auto source1 = ctx.Builder(lambda.Pos())
            .Callable("Take")
                .Callable(0, "SourceOf")
                    .Callable(0, "StreamType")
                        .Callable(0, "NullType")
                        .Seal()
                    .Seal()
                .Seal()
                .Callable(1, "Uint64")
                    .Atom(0, "1")
                .Seal()
            .Seal()
            .Build();

        optimized = ctx.Builder(lambda.Pos())
            .Callable(isList ? "FlatMap" : "Map")
                .Add(0, source1)
                .Lambda(1)
                    .Param("x")
                    .Set(optimized)
                .Seal()
            .Seal()
            .Build();

        bool hasNonDeterministicFunctions;
        auto status = PeepHoleOptimizeNode(optimized, optimized, ctx, *State_->Types, nullptr, hasNonDeterministicFunctions);
        if (status.Level == IGraphTransformer::TStatus::Error) {
            return SyncStatus(status);
        }

        TUserDataTable crutches = State_->Types->UserDataStorageCrutches;
        TUserDataTable files;
        auto filesRes = NCommon::FreezeUsedFiles(*optimized, files, *State_->Types, ctx, [](const TString&) { return true; }, crutches);
        if (filesRes.first.Level != TStatus::Ok) {
            return filesRes;
        }

        TVector<TString> columns(NCommon::GetResOrPullColumnHints(*input));
        if (columns.empty()) {
            columns = NCommon::GetStructFields(lambda.Ref().GetTypeAnn());
        }

        TStringStream out;
        NYson::TYsonWriter writer(&out, NCommon::GetYsonFormat(fillSettings), ::NYson::EYsonType::Node, false);
        writer.OnBeginMap();
        if (NCommon::HasResOrPullOption(*input, "type")) {
            writer.OnKeyedItem("Type");
            NCommon::WriteResOrPullType(writer, lambda.Ref().GetTypeAnn(), TColumnOrder(columns));
        }

        TScopedAlloc alloc(__LOCATION__, TAlignedPagePoolCounters(), State_->FunctionRegistry->SupportsSizedAllocators());
        TTypeEnvironment env(alloc);
        TProgramBuilder pgmBuilder(env, *State_->FunctionRegistry, false, State_->Types->LangVer);
        NCommon::TMkqlCommonCallableCompiler compiler;

        NCommon::TMkqlBuildContext mkqlCtx(compiler, pgmBuilder, ctx);
        auto root = NCommon::MkqlBuildExpr(*optimized, mkqlCtx);

        root = TransformProgram(root, files, env);

        TExploringNodeVisitor explorer;
        explorer.Walk(root.GetNode(), env.GetNodeStack());
        auto compFactory = GetCompositeWithBuiltinFactory({
            GetYqlFactory(),
            GetPgFactory()
        });

        NUdf::TUniquePtr<NUdf::ILogProvider> logProvider = NUdf::MakeLogProvider(
            [](const NUdf::TStringRef& component, NUdf::ELogLevel level, const NUdf::TStringRef& message) {
                Cerr << Now() << " " << component << " [" << level << "] " << message << "\n";
            },
            State_->Types->RuntimeLogLevel
        );

        TComputationPatternOpts patternOpts(alloc.Ref(), env, compFactory, State_->FunctionRegistry,
            State_->Types->ValidateMode, NUdf::EValidatePolicy::Exception, State_->Types->OptLLVM.GetOrElse(TString()),
            EGraphPerProcess::Multi, nullptr, nullptr, nullptr, logProvider.Get());

        auto pattern = MakeComputationPattern(explorer, root, {}, patternOpts);
        const TComputationOptsFull computeOpts(nullptr, alloc.Ref(), env,
            *State_->Types->RandomProvider, *State_->Types->TimeProvider,
            NUdf::EValidatePolicy::Exception, nullptr, nullptr, logProvider.Get(), State_->Types->LangVer);
        auto graph = pattern->Clone(computeOpts);
        const TBindTerminator bind(graph->GetTerminator());
        graph->Prepare();
        auto value = graph->GetValue();
        bool truncated = false;
        auto type = root.GetStaticType();
        TString data;
        TStringOutput dataOut(data);
        TCountingOutput dataCountingOut(&dataOut);
        NYson::TYsonWriter dataWriter(&dataCountingOut, NCommon::GetYsonFormat(fillSettings), ::NYson::EYsonType::Node, false);
        YQL_ENSURE(type->IsStream());
        auto itemType = AS_TYPE(TStreamType, type)->GetItemType();
        if (isList) {
            TMaybe<ui64> rowsLimit = fillSettings.RowsLimitPerWrite;
            TMaybe<ui64> bytesLimit = fillSettings.AllResultsBytesLimit;
            TMaybe<TVector<ui32>> structPositions = NCommon::CreateStructPositions(itemType, &columns);
            dataWriter.OnBeginList();
            ui64 rows = 0;
            for (;;) {
                NUdf::TUnboxedValue item;
                auto status = value.Fetch(item);
                if (status == NUdf::EFetchStatus::Finish) {
                    break;
                }

                YQL_ENSURE(status == NUdf::EFetchStatus::Ok);
                if ((rowsLimit && rows >= *rowsLimit) || (bytesLimit && dataCountingOut.Counter() >= *bytesLimit)) {
                    truncated = true;
                    break;
                }

                dataWriter.OnListItem();
                NCommon::WriteYsonValue(dataWriter, item, itemType, structPositions.Get());
                ++rows;
            }
            dataWriter.OnEndList();
        } else {
            NUdf::TUnboxedValue item;
            YQL_ENSURE(value.Fetch(item) == NUdf::EFetchStatus::Ok);
            NCommon::WriteYsonValue(dataWriter, item, itemType, nullptr);
            YQL_ENSURE(value.Fetch(item) == NUdf::EFetchStatus::Finish);
        }

        writer.OnKeyedItem("Data");
        writer.OnRaw(fillSettings.Discard ? "#" : data);

        if (truncated) {
            writer.OnKeyedItem("Truncated");
            writer.OnBooleanScalar(true);
        }

        writer.OnEndMap();
        input->SetState(TExprNode::EState::ExecutionComplete);
        input->SetResult(ctx.NewAtom(input->Pos(), out.Str()));
        return SyncOk();
    }

private:
    TRuntimeNode TransformProgram(TRuntimeNode root, const TUserDataTable& files, TTypeEnvironment& env) {
        TExploringNodeVisitor explorer;
        explorer.Walk(root.GetNode(), env.GetNodeStack());
        bool wereChanges = false;
        TRuntimeNode program = SinglePassVisitCallables(root, explorer,
            TSimpleFileTransformProvider(State_->FunctionRegistry, files), env, true, wereChanges);
        program = LiteralPropagationOptimization(program, env, true);
        return program;
    }

private:
    const TPureState::TPtr State_;
};

THolder<TExecTransformerBase> CreatePureDataSourceExecTransformer(const TPureState::TPtr& state) {
    return THolder(new TPureDataSinkExecTransformer(state));
}

class TPureProvider : public TDataProviderBase {
public:
    TPureProvider(const TPureState::TPtr& state)
        : State_(state)
        , ExecTransformer_([this]() { return CreatePureDataSourceExecTransformer(State_); })
    {}

    TStringBuf GetName() const final {
        return PureProviderName;
    }

    IGraphTransformer& GetCallableExecutionTransformer() override {
        return *ExecTransformer_;
    }

private:
    const TPureState::TPtr State_;
    TLazyInitHolder<TExecTransformerBase> ExecTransformer_;
};

}

TIntrusivePtr<IDataProvider> CreatePureProvider(const TPureState::TPtr& state) {
    return MakeIntrusive<TPureProvider>(state);
}

TDataProviderInitializer GetPureDataProviderInitializer() {
    return [] (
        const TString& userName,
        const TString& sessionId,
        const TGatewaysConfig* gatewaysConfig,
        const IFunctionRegistry* functionRegistry,
        TIntrusivePtr<IRandomProvider> randomProvider,
        TIntrusivePtr<TTypeAnnotationContext> typeCtx,
        const TOperationProgressWriter& progressWriter,
        const TYqlOperationOptions& operationOptions,
        THiddenQueryAborter hiddenAborter,
        const TQContext& qContext
    ) {
        Y_UNUSED(userName);
        Y_UNUSED(sessionId);
        Y_UNUSED(gatewaysConfig);
        Y_UNUSED(randomProvider);
        Y_UNUSED(typeCtx);
        Y_UNUSED(progressWriter);
        Y_UNUSED(operationOptions);
        Y_UNUSED(hiddenAborter);
        Y_UNUSED(qContext);

        TDataProviderInfo info;
        info.Names.insert(TString{PureProviderName});

        auto state = MakeIntrusive<TPureState>();
        state->Types = typeCtx.Get();
        state->FunctionRegistry = functionRegistry;

        info.Source = CreatePureProvider(state);
        info.OpenSession = [state](
            const TString& sessionId,
            const TString& username,
            const TOperationProgressWriter& progressWriter,
            const TYqlOperationOptions& operationOptions,
            TIntrusivePtr<IRandomProvider> randomProvider,
            TIntrusivePtr<ITimeProvider> timeProvider) {
            Y_UNUSED(sessionId);
            Y_UNUSED(username);
            Y_UNUSED(progressWriter);
            Y_UNUSED(operationOptions);
            Y_UNUSED(randomProvider);
            Y_UNUSED(timeProvider);
            return NThreading::MakeFuture();
        };

        info.CloseSessionAsync = [](const TString& sessionId) {
            Y_UNUSED(sessionId);
            return NThreading::MakeFuture();
        };

        return info;
    };
}

}