aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/udfs/common/python/bindings/py_struct.cpp
blob: a4ab99ee32cd7009905fa87d6086616f2fb7803d (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
#include "py_struct.h"
#include "py_cast.h"
#include "py_errors.h"
#include "py_gil.h"
#include "py_utils.h"

#include <yql/essentials/public/udf/udf_value.h>
#include <yql/essentials/public/udf/udf_value_builder.h>
#include <yql/essentials/public/udf/udf_type_inspection.h>
#include <yql/essentials/public/udf/udf_terminator.h>

#include <util/string/cast.h>
#include <util/string/join.h>
#include <util/string/builder.h>

using namespace NKikimr;

namespace NPython {

namespace {

TPyObjectPtr CreateNewStrucInstance(const TPyCastContext::TPtr& ctx, const NKikimr::NUdf::TType* type, const NUdf::TStructTypeInspector& inspector)
{
    const auto it = ctx->StructTypes.emplace(type, TPyObjectPtr());
    if (it.second) {
#if PY_MAJOR_VERSION >= 3
        std::vector<PyStructSequence_Field> fields(inspector.GetMembersCount() + 1U);
        for (ui32 i = 0U; i < inspector.GetMembersCount(); ++i) {
            fields[i] = {const_cast<char*>(inspector.GetMemberName(i).Data()), nullptr};
        }
        fields.back() = {nullptr, nullptr};

        PyStructSequence_Desc desc = {
            INIT_MEMBER(name, "yql.Struct"),
            INIT_MEMBER(doc, nullptr),
            INIT_MEMBER(fields, fields.data()),
            INIT_MEMBER(n_in_sequence, int(inspector.GetMembersCount()))
        };

        const auto typeObject = new PyTypeObject();
        if (0 > PyStructSequence_InitType2(typeObject, &desc)) {
            throw yexception() << "can't create struct type: " << GetLastErrorAsString();
        }

        it.first->second.ResetSteal(reinterpret_cast<PyObject*>(typeObject));
    }

    const TPyObjectPtr object = PyStructSequence_New(it.first->second.GetAs<PyTypeObject>());
#else
        const auto className = TString("yql.Struct_") += ToString(ctx->StructTypes.size());
        PyObject* metaclass = (PyObject *) &PyClass_Type;
        const TPyObjectPtr name = PyRepr(TStringBuf(className));
        const TPyObjectPtr bases = PyTuple_New(0);
        const TPyObjectPtr dict = PyDict_New();

        TPyObjectPtr newClass = PyObject_CallFunctionObjArgs(
                metaclass, name.Get(), bases.Get(), dict.Get(),
                nullptr);
        if (!newClass) {
            throw yexception() << "can't create new type: " << GetLastErrorAsString();
        }

        it.first->second = std::move(newClass);
    }

    Y_UNUSED(inspector);
    const TPyObjectPtr object = PyInstance_New(it.first->second.Get(), nullptr, nullptr);
#endif
    if (!object) {
        throw yexception() << "can't struct instance: " << GetLastErrorAsString();
    }
    return object;
}

}

TPyObjectPtr ToPyStruct(const TPyCastContext::TPtr& ctx, const NUdf::TType* type, const NUdf::TUnboxedValuePod& value)
{
    const NUdf::TStructTypeInspector inspector(*ctx->PyCtx->TypeInfoHelper, type);
    const TPyObjectPtr object = CreateNewStrucInstance(ctx, type, inspector);
    const auto membersCount = inspector.GetMembersCount();

    if (auto ptr = value.GetElements()) {
        for (Py_ssize_t i = 0; i < membersCount; ++i) {
#if PY_MAJOR_VERSION >= 3
            auto item = ToPyObject(ctx, inspector.GetMemberType(i), *ptr++);
            PyStructSequence_SetItem(object.Get(), i, item.Release());
#else
            const TStringBuf name = inspector.GetMemberName(i);
            const auto item = ToPyObject(ctx, inspector.GetMemberType(i), *ptr++);
            if (0 > PyObject_SetAttrString(object.Get(), name.data(), item.Get())) {
                throw yexception()
                        << "Can't set attr '" << name << "' to python object: "
                        << GetLastErrorAsString();
            }
#endif
        }
    } else {
        for (Py_ssize_t i = 0; i < membersCount; ++i) {
#if PY_MAJOR_VERSION >= 3
            auto item = ToPyObject(ctx, inspector.GetMemberType(i), value.GetElement(i));
            PyStructSequence_SetItem(object.Get(), i, item.Release());
#else
            const TStringBuf name = inspector.GetMemberName(i);
            const auto item = ToPyObject(ctx, inspector.GetMemberType(i), value.GetElement(i));
            if (0 > PyObject_SetAttrString(object.Get(), name.data(), item.Get())) {
                throw yexception()
                        << "Can't set attr '" << name << "' to python object: "
                        << GetLastErrorAsString();
            }
#endif
        }
    }

    return object;
}

NUdf::TUnboxedValue FromPyStruct(const TPyCastContext::TPtr& ctx, const NUdf::TType* type, PyObject* value)
{
    NUdf::TUnboxedValue* items = nullptr;
    const NUdf::TStructTypeInspector inspector(*ctx->PyCtx->TypeInfoHelper, type);
    const auto membersCount = inspector.GetMembersCount();
    auto mkqlStruct = ctx->ValueBuilder->NewArray(membersCount, items);

    TVector<TString> errors;
    if (PyDict_Check(value)) {
        for (ui32 i = 0; i < membersCount; i++) {
            TStringBuf memberName = inspector.GetMemberName(i);
            auto memberType = inspector.GetMemberType(i);
            // borrowed reference - no need to manage ownership
            PyObject* item = PyDict_GetItemString(value, memberName.data());
            if (!item) {
                TPyObjectPtr bytesMemberName = PyBytes_FromStringAndSize(memberName.data(), memberName.size());
                item = PyDict_GetItem(value, bytesMemberName.Get());
            }
            if (!item) {
                if (ctx->PyCtx->TypeInfoHelper->GetTypeKind(memberType) == NUdf::ETypeKind::Optional) {
                    items[i] = NUdf::TUnboxedValue();
                    continue;
                }

                errors.push_back(TStringBuilder() << "Dict has no item '" << memberName << "'");
                continue;
            }

            try {
                items[i] = FromPyObject(ctx, inspector.GetMemberType(i), item);
            } catch (const yexception& e) {
                errors.push_back(TStringBuilder() << "Failed to convert dict item '" << memberName << "' - " << e.what());
            }
        }

        if (!errors.empty()) {
            throw yexception() << "Failed to convert dict to struct\n" << JoinSeq("\n", errors) << "\nDict repr: " << PyObjectRepr(value);
        }
    } else {
        for (ui32 i = 0; i < membersCount; i++) {
            TStringBuf memberName = inspector.GetMemberName(i);
            auto memberType = inspector.GetMemberType(i);
            TPyObjectPtr attr = PyObject_GetAttrString(value, memberName.data());
            if (!attr) {
                if (ctx->PyCtx->TypeInfoHelper->GetTypeKind(memberType) == NUdf::ETypeKind::Optional &&
                    PyErr_ExceptionMatches(PyExc_AttributeError)) {
                    PyErr_Clear();
                    items[i] = NUdf::TUnboxedValue();
                    continue;
                }

                errors.push_back(TStringBuilder() << "Object has no attr '" << memberName << "' , error: " << GetLastErrorAsString());
                continue;
            }

            try {
                items[i] = FromPyObject(ctx, memberType, attr.Get());
            } catch (const yexception& e) {
                errors.push_back(TStringBuilder() << "Failed to convert object attr '" << memberName << "' - " << e.what());
            }
        }

        if (!errors.empty()) {
            throw yexception() << "Failed to convert object to struct\n" << JoinSeq("\n", errors) << "\nObject repr: " << PyObjectRepr(value);
        }
    }

    return mkqlStruct;
}

}