match_recognize.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. #include "match_recognize.h"
  2. #include "source.h"
  3. #include "context.h"
  4. #include <util/generic/overloaded.h>
  5. namespace NSQLTranslationV1 {
  6. namespace {
  7. constexpr auto VarDataName = "data";
  8. constexpr auto VarMatchedVarsName = "vars";
  9. constexpr auto VarLastRowIndexName = "lri";
  10. class TMatchRecognizeColumnAccessNode final : public TAstListNode {
  11. public:
  12. TMatchRecognizeColumnAccessNode(TPosition pos, TString var, TString column)
  13. : TAstListNode(pos)
  14. , Var(std::move(var))
  15. , Column(std::move(column)) {
  16. }
  17. const TString* GetColumnName() const override {
  18. return std::addressof(Column);
  19. }
  20. bool DoInit(TContext& ctx, ISource* /* src */) override {
  21. switch (ctx.GetColumnReferenceState()) {
  22. case EColumnRefState::MatchRecognizeMeasures:
  23. if (!ctx.SetMatchRecognizeAggrVar(Var)) {
  24. return false;
  25. }
  26. Add(
  27. "Member",
  28. BuildAtom(Pos, "row"),
  29. Q(Column)
  30. );
  31. break;
  32. case EColumnRefState::MatchRecognizeDefine:
  33. if (ctx.GetMatchRecognizeDefineVar() != Var) {
  34. ctx.Error() << "Row pattern navigation function is required";
  35. return false;
  36. }
  37. BuildLookup(VarLastRowIndexName);
  38. break;
  39. case EColumnRefState::MatchRecognizeDefineAggregate:
  40. if (!ctx.SetMatchRecognizeAggrVar(Var)) {
  41. return false;
  42. }
  43. BuildLookup("index");
  44. break;
  45. default:
  46. Y_ABORT("Unexpected column reference state");
  47. }
  48. return true;
  49. }
  50. TNodePtr DoClone() const override {
  51. return new TMatchRecognizeColumnAccessNode(Pos, Var, Column);
  52. }
  53. private:
  54. void BuildLookup(TString varKeyName) {
  55. Add(
  56. "Member",
  57. Y(
  58. "Lookup",
  59. Y(
  60. "ToIndexDict",
  61. BuildAtom(Pos, VarDataName)
  62. ),
  63. BuildAtom(Pos, std::move(varKeyName))
  64. ),
  65. Q(Column)
  66. );
  67. }
  68. private:
  69. TString Var;
  70. TString Column;
  71. };
  72. class TMatchRecognizeDefineAggregate final : public TAstListNode {
  73. public:
  74. TMatchRecognizeDefineAggregate(TPosition pos, TString name, TVector<TNodePtr> args)
  75. : TAstListNode(pos)
  76. , Name(std::move(name))
  77. , Args(std::move(args)) {
  78. }
  79. bool DoInit(TContext& ctx, ISource* src) override {
  80. Y_DEBUG_ABORT_UNLESS(ctx.GetColumnReferenceState() == EColumnRefState::MatchRecognizeDefine);
  81. TColumnRefScope scope(ctx, EColumnRefState::MatchRecognizeDefineAggregate, false, ctx.GetMatchRecognizeDefineVar());
  82. if (Args.size() != 1) {
  83. ctx.Error() << "Exactly one argument is required in MATCH_RECOGNIZE navigation function";
  84. return false;
  85. }
  86. const auto arg = Args[0];
  87. if (!arg->Init(ctx, src)) {
  88. return false;
  89. }
  90. const auto body = [&]() -> TNodePtr {
  91. if ("first" == Name) {
  92. return Y("Member", Y("Head", "item"), Q("From"));
  93. } else if ("last" == Name) {
  94. return Y("Member", Y("Last", "item"), Q("To"));
  95. } else {
  96. ctx.Error() << "Unknown row pattern navigation function: " << Name;
  97. return {};
  98. }
  99. }();
  100. if (!body) {
  101. return false;
  102. }
  103. Add("Apply", BuildLambda(Pos, Y("index"), arg), body);
  104. return true;
  105. }
  106. TNodePtr DoClone() const override {
  107. return new TMatchRecognizeDefineAggregate(Pos, Name, Args);
  108. }
  109. private:
  110. TString Name;
  111. TVector<TNodePtr> Args;
  112. };
  113. class TMatchRecognizeVarAccessNode final : public INode {
  114. public:
  115. TMatchRecognizeVarAccessNode(TPosition pos, TNodePtr arg)
  116. : INode(pos)
  117. , Arg(std::move(arg)) {
  118. }
  119. [[nodiscard]] const TString& GetVar() const noexcept {
  120. return Var;
  121. }
  122. TAggregationPtr GetAggregation() const override {
  123. return Arg->GetAggregation();
  124. }
  125. bool DoInit(TContext& ctx, ISource* src) override {
  126. if (!Arg->Init(ctx, src)) {
  127. return false;
  128. }
  129. Var = ctx.ExtractMatchRecognizeAggrVar();
  130. Expr = [&]() -> TNodePtr {
  131. switch (ctx.GetColumnReferenceState()) {
  132. case EColumnRefState::MatchRecognizeMeasures:
  133. return Arg;
  134. case EColumnRefState::MatchRecognizeDefine:
  135. return Y(
  136. "Apply",
  137. BuildLambda(Pos, Y("item"), Arg),
  138. Y(
  139. "Member",
  140. BuildAtom(ctx.Pos(), VarMatchedVarsName),
  141. Q(Var)
  142. )
  143. );
  144. default:
  145. Y_ABORT("Unexpected column reference state");
  146. }
  147. }();
  148. return Expr->Init(ctx, src);
  149. }
  150. TNodePtr DoClone() const override {
  151. return new TMatchRecognizeVarAccessNode(Pos, Arg);
  152. }
  153. TAstNode* Translate(TContext& ctx) const override {
  154. return Expr->Translate(ctx);
  155. }
  156. private:
  157. TString Var;
  158. TNodePtr Arg;
  159. TNodePtr Expr;
  160. };
  161. class TMatchRecognize final : public TAstListNode {
  162. public:
  163. TMatchRecognize(
  164. TPosition pos,
  165. TString label,
  166. TNodePtr partitionKeySelector,
  167. TNodePtr partitionColumns,
  168. TVector<TSortSpecificationPtr> sortSpecs,
  169. TVector<TNamedFunction> measures,
  170. TNodePtr rowsPerMatch,
  171. TNodePtr skipTo,
  172. TNodePtr pattern,
  173. TNodePtr patternVars,
  174. TNodePtr subset,
  175. TVector<TNamedFunction> definitions)
  176. : TAstListNode(pos)
  177. , Label(std::move(label))
  178. , PartitionKeySelector(std::move(partitionKeySelector))
  179. , PartitionColumns(std::move(partitionColumns))
  180. , SortSpecs(std::move(sortSpecs))
  181. , Measures(std::move(measures))
  182. , RowsPerMatch(std::move(rowsPerMatch))
  183. , SkipTo(std::move(skipTo))
  184. , Pattern(std::move(pattern))
  185. , PatternVars(std::move(patternVars))
  186. , Subset(std::move(subset))
  187. , Definitions(std::move(definitions)) {
  188. }
  189. private:
  190. bool DoInit(TContext& ctx, ISource* src) override {
  191. auto inputRowType = Y("ListItemType", Y("TypeOf", Label));
  192. if (!PartitionKeySelector->Init(ctx, src)) {
  193. return false;
  194. }
  195. if (!PartitionColumns->Init(ctx, src)) {
  196. return false;
  197. }
  198. const auto sortTraits = SortSpecs.empty() ? Y("Void") : src->BuildSortSpec(SortSpecs, Label, true, false);
  199. if (!sortTraits->Init(ctx, src)) {
  200. return false;
  201. }
  202. auto measureNames = Y();
  203. for (const auto& m: Measures) {
  204. measureNames->Add(BuildQuotedAtom(m.Callable->GetPos(), m.Name));
  205. }
  206. auto measureVars = Y();
  207. for (const auto& m: Measures) {
  208. TColumnRefScope scope(ctx, EColumnRefState::MatchRecognizeMeasures);
  209. if (!m.Callable->Init(ctx, src)) {
  210. return false;
  211. }
  212. const auto varAccess = dynamic_cast<TMatchRecognizeVarAccessNode*>(m.Callable.Get());
  213. auto var = varAccess ? varAccess->GetVar() : "";
  214. measureVars->Add(BuildQuotedAtom(m.Callable->GetPos(), std::move(var)));
  215. }
  216. auto measuresNode = Y("MatchRecognizeMeasuresAggregates", inputRowType, Q(PatternVars), Q(measureNames), Q(measureVars));
  217. for (const auto& m: Measures) {
  218. auto aggr = m.Callable->GetAggregation();
  219. if (!aggr) {
  220. // TODO(YQL-16508): support aggregations inside expressions
  221. // ctx.Error(m.Callable->GetPos()) << "Cannot use aggregations inside expression";
  222. // return false;
  223. measuresNode->Add(m.Callable);
  224. } else {
  225. const auto [traits, result] = aggr->AggregationTraits(Y("TypeOf", Label), false, false, false, ctx);
  226. if (!result) {
  227. return false;
  228. }
  229. measuresNode->Add(traits);
  230. }
  231. }
  232. if (!RowsPerMatch->Init(ctx, src)) {
  233. return false;
  234. }
  235. if (!SkipTo->Init(ctx, src)) {
  236. return false;
  237. }
  238. if (!Pattern->Init(ctx, src)) {
  239. return false;
  240. }
  241. if (!PatternVars->Init(ctx, src)) {
  242. return false;
  243. }
  244. auto defineNames = Y();
  245. for (const auto& d: Definitions) {
  246. defineNames->Add(BuildQuotedAtom(d.Callable->GetPos(), d.Name));
  247. }
  248. auto defineNode = Y("MatchRecognizeDefines", inputRowType, Q(PatternVars), Q(defineNames));
  249. for (const auto& d: Definitions) {
  250. TColumnRefScope scope(ctx, EColumnRefState::MatchRecognizeDefine, true, d.Name);
  251. if (!d.Callable->Init(ctx, src)) {
  252. return false;
  253. }
  254. defineNode->Add(BuildLambda(d.Callable->GetPos(), Y(VarDataName, VarMatchedVarsName, VarLastRowIndexName), d.Callable));
  255. }
  256. Add(
  257. "block",
  258. Q(Y(
  259. Y("let", "input", Label),
  260. Y("let", "partitionKeySelector", PartitionKeySelector),
  261. Y("let", "partitionColumns", PartitionColumns),
  262. Y("let", "sortTraits", sortTraits),
  263. Y("let", "measures", measuresNode),
  264. Y("let", "rowsPerMatch", RowsPerMatch),
  265. Y("let", "skipTo", SkipTo),
  266. Y("let", "pattern", Pattern),
  267. Y("let", "subset", Subset ? Subset : Q("")),
  268. Y("let", "define", defineNode),
  269. Y("let", "res", Y("MatchRecognize",
  270. "input",
  271. "partitionKeySelector",
  272. "partitionColumns",
  273. "sortTraits",
  274. Y("MatchRecognizeParams",
  275. "measures",
  276. "rowsPerMatch",
  277. "skipTo",
  278. "pattern",
  279. "define"
  280. )
  281. )),
  282. Y("return", "res")
  283. ))
  284. );
  285. return true;
  286. }
  287. TNodePtr DoClone() const override {
  288. return new TMatchRecognize(
  289. Pos,
  290. Label,
  291. PartitionKeySelector,
  292. PartitionColumns,
  293. SortSpecs,
  294. Measures,
  295. RowsPerMatch,
  296. SkipTo,
  297. Pattern,
  298. PatternVars,
  299. Subset,
  300. Definitions
  301. );
  302. }
  303. private:
  304. TString Label;
  305. TNodePtr PartitionKeySelector;
  306. TNodePtr PartitionColumns;
  307. TVector<TSortSpecificationPtr> SortSpecs;
  308. TVector<TNamedFunction> Measures;
  309. TNodePtr RowsPerMatch;
  310. TNodePtr SkipTo;
  311. TNodePtr Pattern;
  312. TNodePtr PatternVars;
  313. TNodePtr Subset;
  314. TVector<TNamedFunction> Definitions;
  315. };
  316. } // anonymous namespace
  317. TNodePtr TMatchRecognizeBuilder::Build(TContext& ctx, TString label, ISource* src) {
  318. TNodePtr node = new TMatchRecognize(
  319. Pos,
  320. std::move(label),
  321. std::move(PartitionKeySelector),
  322. std::move(PartitionColumns),
  323. std::move(SortSpecs),
  324. std::move(Measures),
  325. std::move(RowsPerMatch),
  326. std::move(SkipTo),
  327. std::move(Pattern),
  328. std::move(PatternVars),
  329. std::move(Subset),
  330. std::move(Definitions)
  331. );
  332. if (!node->Init(ctx, src)) {
  333. return {};
  334. }
  335. return node;
  336. }
  337. TNodePtr BuildMatchRecognizeColumnAccess(TPosition pos, TString var, TString column) {
  338. return MakeIntrusive<TMatchRecognizeColumnAccessNode>(pos, std::move(var), std::move(column));
  339. }
  340. TNodePtr BuildMatchRecognizeDefineAggregate(TPosition pos, TString name, TVector<TNodePtr> args) {
  341. const auto result = MakeIntrusive<TMatchRecognizeDefineAggregate>(pos, std::move(name), std::move(args));
  342. return BuildMatchRecognizeVarAccess(pos, std::move(result));
  343. }
  344. TNodePtr BuildMatchRecognizeVarAccess(TPosition pos, TNodePtr extractor) {
  345. return MakeIntrusive<TMatchRecognizeVarAccessNode>(pos, std::move(extractor));
  346. }
  347. } // namespace NSQLTranslationV1