serialize.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #pragma once
  2. #include "resource.h"
  3. #include <yql/essentials/public/udf/udf_value.h>
  4. #include <yql/essentials/public/udf/udf_helpers.h>
  5. #include <yql/essentials/minikql/dom/json.h>
  6. #include <yql/essentials/types/binary_json/write.h>
  7. namespace NJson2Udf {
  8. using namespace NKikimr;
  9. using namespace NUdf;
  10. using namespace NYql;
  11. using namespace NDom;
  12. using namespace NBinaryJson;
  13. template <EDataSlot ResultType>
  14. class TSerialize : public TBoxedValue {
  15. public:
  16. TSerialize(TSourcePosition pos)
  17. : Pos_(pos)
  18. {
  19. }
  20. static const TStringRef& Name();
  21. static bool DeclareSignature(
  22. const TStringRef& name,
  23. TType* userType,
  24. IFunctionTypeInfoBuilder& builder,
  25. bool typesOnly) {
  26. Y_UNUSED(userType);
  27. if (name != Name()) {
  28. return false;
  29. }
  30. TType* resultType = nullptr;
  31. if constexpr (ResultType == EDataSlot::Json) {
  32. resultType = builder.SimpleType<TJson>();
  33. } else {
  34. resultType = builder.SimpleType<TJsonDocument>();
  35. }
  36. builder.Args()
  37. ->Add<TAutoMap<TJsonNodeResource>>()
  38. .Done()
  39. .Returns(resultType);
  40. if (!typesOnly) {
  41. builder.Implementation(new TSerialize(builder.GetSourcePosition()));
  42. }
  43. return true;
  44. }
  45. private:
  46. TUnboxedValue Run(
  47. const IValueBuilder* valueBuilder,
  48. const TUnboxedValuePod* args) const final {
  49. try {
  50. const TUnboxedValue& jsonDom = args[0];
  51. if constexpr (ResultType == EDataSlot::Json) {
  52. return valueBuilder->NewString(SerializeJsonDom(jsonDom));
  53. } else {
  54. const auto binaryJson = SerializeToBinaryJson(jsonDom);
  55. return valueBuilder->NewString(TStringBuf(binaryJson.Data(), binaryJson.Size()));
  56. }
  57. } catch (const std::exception& e) {
  58. UdfTerminate((TStringBuilder() << Pos_ << " " << e.what()).data());
  59. }
  60. }
  61. TSourcePosition Pos_;
  62. };
  63. template <>
  64. const TStringRef& TSerialize<EDataSlot::Json>::Name() {
  65. static auto name = TStringRef::Of("Serialize");
  66. return name;
  67. }
  68. template <>
  69. const TStringRef& TSerialize<EDataSlot::JsonDocument>::Name() {
  70. static auto name = TStringRef::Of("SerializeToJsonDocument");
  71. return name;
  72. }
  73. }