yql_join.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934
  1. #include "yql_join.h"
  2. #include "yql_expr_type_annotation.h"
  3. #include "yql_opt_utils.h"
  4. #include <util/string/cast.h>
  5. #include <util/string/join.h>
  6. #include <util/string/type.h>
  7. namespace NYql {
  8. using namespace NNodes;
  9. namespace {
  10. const TTypeAnnotationNode* AddOptionalType(const TTypeAnnotationNode* type, TExprContext& ctx) {
  11. if (type->IsOptionalOrNull()) {
  12. return type;
  13. }
  14. return ctx.MakeType<TOptionalExprType>(type);
  15. }
  16. struct TJoinState {
  17. bool Used = false;
  18. };
  19. IGraphTransformer::TStatus ParseJoinKeys(TExprNode& side, TVector<std::pair<TStringBuf, TStringBuf>>& keys,
  20. TVector<const TTypeAnnotationNode*>& keyTypes, const TJoinLabels& labels,
  21. TExprContext& ctx, bool isCross) {
  22. if (!EnsureTuple(side, ctx)) {
  23. return IGraphTransformer::TStatus::Error;
  24. }
  25. for (auto& child : side.Children()) {
  26. if (!EnsureAtom(*child, ctx)) {
  27. return IGraphTransformer::TStatus::Error;
  28. }
  29. }
  30. if (isCross) {
  31. if (side.ChildrenSize() != 0) {
  32. ctx.AddError(TIssue(ctx.GetPosition(side.Pos()),
  33. TStringBuilder() << "Expected empty list"));
  34. return IGraphTransformer::TStatus::Error;
  35. }
  36. } else {
  37. if (side.ChildrenSize() < 2 || (side.ChildrenSize() % 2) != 0) {
  38. ctx.AddError(TIssue(ctx.GetPosition(side.Pos()),
  39. TStringBuilder() << "Expected non-empty list of atoms with even length"));
  40. return IGraphTransformer::TStatus::Error;
  41. }
  42. }
  43. keys.clear();
  44. for (ui32 i = 0; i < side.ChildrenSize(); i += 2) {
  45. auto table = side.Child(i)->Content();
  46. auto column = side.Child(i + 1)->Content();
  47. auto key = std::make_pair(table, column);
  48. keys.push_back(key);
  49. }
  50. for (auto& key : keys) {
  51. auto keyType = labels.FindColumn(key.first, key.second);
  52. if (!keyType) {
  53. ctx.AddError(TIssue(ctx.GetPosition(side.Pos()),
  54. TStringBuilder() << "Unknown column: " << key.second << " in correlation name: " << key.first));
  55. return IGraphTransformer::TStatus::Error;
  56. }
  57. if (!(*keyType)->IsHashable() || !(*keyType)->IsEquatable()) {
  58. ctx.AddError(TIssue(ctx.GetPosition(side.Pos()),
  59. TStringBuilder() << "Unsupported type of column: " << key.second << " in correlation name: " << key.first
  60. << ", type: " << *(*keyType)));
  61. return IGraphTransformer::TStatus::Error;
  62. }
  63. keyTypes.push_back(*keyType);
  64. }
  65. return IGraphTransformer::TStatus::Ok;
  66. }
  67. struct TGLobalJoinState {
  68. ui32 NestedJoins = 0;
  69. };
  70. bool AddEquiJoinLinkOptionHint(const std::string_view& side, std::unordered_set<std::string_view>& hints, const TExprNode& hintNode, TExprContext& ctx) {
  71. if (!EnsureAtom(hintNode, ctx)) {
  72. return false;
  73. }
  74. const auto pos = ctx.GetPosition(hintNode.Pos());
  75. if (hintNode.IsAtom({"unique", "small"})) {
  76. if (hints.contains(hintNode.IsAtom("small") ? "unique" : "small")) {
  77. ctx.AddError(TIssue(pos, TStringBuilder() << "Hints 'unique' and 'small' are not compatible"));
  78. return false;
  79. }
  80. } else if (!hintNode.IsAtom("any")) {
  81. ctx.AddError(TIssue(pos, TStringBuilder() << "Unknown hint: '" << hintNode.Content() << "' for " << side << " side"));
  82. return false;
  83. }
  84. hints.insert(hintNode.Content());
  85. return true;
  86. }
  87. IGraphTransformer::TStatus ParseJoins(const TJoinLabels& labels,
  88. TExprNode& joins, TVector<TJoinState>& joinsStates, THashSet<TStringBuf>& scope,
  89. TGLobalJoinState& globalState, bool strictKeys, TExprContext& ctx, const TUniqueConstraintNode** unique = nullptr, const TDistinctConstraintNode** distinct = nullptr);
  90. IGraphTransformer::TStatus ParseJoinScope(const TJoinLabels& labels,
  91. TExprNode& side, TVector<TJoinState>& joinsStates, THashSet<TStringBuf>& scope,
  92. TGLobalJoinState& globalState, bool strictKeys, const TUniqueConstraintNode*& unique, const TDistinctConstraintNode*& distinct, TExprContext& ctx) {
  93. if (side.IsAtom()) {
  94. const auto label = side.Content();
  95. const auto input = labels.FindInput(label);
  96. if (!input) {
  97. ctx.AddError(TIssue(ctx.GetPosition(side.Pos()),
  98. TStringBuilder() << "Unknown correlation name: " << label));
  99. return IGraphTransformer::TStatus::Error;
  100. }
  101. for (const auto& x : (*input)->Tables) {
  102. scope.insert(x);
  103. }
  104. const auto rename = [&](const TPartOfConstraintBase::TPathType& path) -> std::vector<TPartOfConstraintBase::TPathType> {
  105. if (path.empty())
  106. return {};
  107. auto newPath = path;
  108. newPath.front() = ctx.AppendString((*input)->FullName(newPath.front()));
  109. return {std::move(newPath)};
  110. };
  111. if (const auto u = (*input)->Unique) {
  112. unique = u->RenameFields(ctx, rename);
  113. }
  114. if (const auto d = (*input)->Distinct) {
  115. distinct = d->RenameFields(ctx, rename);
  116. }
  117. return IGraphTransformer::TStatus::Ok;
  118. }
  119. if (globalState.NestedJoins + 2 == labels.Inputs.size()) {
  120. ctx.AddError(TIssue(ctx.GetPosition(side.Pos()),
  121. TStringBuilder() << "Too many nested joins, expected exactly: " << (labels.Inputs.size() - 2)));
  122. return IGraphTransformer::TStatus::Error;
  123. }
  124. ++globalState.NestedJoins;
  125. return ParseJoins(labels, side, joinsStates, scope, globalState, strictKeys, ctx, &unique, &distinct);
  126. }
  127. IGraphTransformer::TStatus ParseJoins(const TJoinLabels& labels,
  128. TExprNode& joins, TVector<TJoinState>& joinsStates, THashSet<TStringBuf>& scope,
  129. TGLobalJoinState& globalState, bool strictKeys, TExprContext& ctx, const TUniqueConstraintNode** unique, const TDistinctConstraintNode** distinct) {
  130. if (!EnsureTupleSize(joins, 6, ctx)) {
  131. return IGraphTransformer::TStatus::Error;
  132. }
  133. const auto& joinType = joins.Head();
  134. if (!EnsureAtom(joinType, ctx)) {
  135. return IGraphTransformer::TStatus::Error;
  136. }
  137. if (!joinType.IsAtom({"Inner", "Left", "Right", "Full", "LeftOnly", "RightOnly", "Exclusion", "LeftSemi" , "RightSemi", "Cross"})) {
  138. ctx.AddError(TIssue(ctx.GetPosition(joinType.Pos()), TStringBuilder() << "Unsupported join type: " << joinType.Content()));
  139. return IGraphTransformer::TStatus::Error;
  140. }
  141. THashSet<TStringBuf> myLeftScope;
  142. const TUniqueConstraintNode* lUnique = nullptr;
  143. const TDistinctConstraintNode* lDistinct = nullptr;
  144. if (const auto status = ParseJoinScope(labels, *joins.Child(1), joinsStates, myLeftScope, globalState, strictKeys, lUnique, lDistinct, ctx); status.Level != IGraphTransformer::TStatus::Ok) {
  145. return status;
  146. }
  147. THashSet<TStringBuf> myRightScope;
  148. const TUniqueConstraintNode* rUnique = nullptr;
  149. const TDistinctConstraintNode* rDistinct = nullptr;
  150. if (const auto status = ParseJoinScope(labels, *joins.Child(2), joinsStates, myRightScope, globalState, strictKeys, rUnique, rDistinct, ctx); status.Level != IGraphTransformer::TStatus::Ok) {
  151. return status;
  152. }
  153. TVector<std::pair<TStringBuf, TStringBuf>> leftKeys;
  154. TVector<const TTypeAnnotationNode*> leftKeyTypes;
  155. const bool cross = joinType.IsAtom("Cross");
  156. if (const auto status = ParseJoinKeys(*joins.Child(3), leftKeys, leftKeyTypes, labels, ctx, cross); status.Level != IGraphTransformer::TStatus::Ok) {
  157. return status;
  158. }
  159. std::vector<std::string_view> lCheck;
  160. lCheck.reserve(leftKeys.size());
  161. for (const auto& x : leftKeys) {
  162. for (const auto& name : (*labels.FindInput(x.first))->AllNames(x.second))
  163. lCheck.emplace_back(ctx.AppendString(name));
  164. if (!myLeftScope.contains(x.first)) {
  165. ctx.AddError(TIssue(ctx.GetPosition(joins.Pos()),
  166. TStringBuilder() << "Correlation name " << x.first << " is out of scope"));
  167. return IGraphTransformer::TStatus::Error;
  168. }
  169. joinsStates[*labels.FindInputIndex(x.first)].Used = true;
  170. }
  171. TVector<std::pair<TStringBuf, TStringBuf>> rightKeys;
  172. TVector<const TTypeAnnotationNode*> rightKeyTypes;
  173. if (const auto status = ParseJoinKeys(*joins.Child(4), rightKeys, rightKeyTypes, labels, ctx, cross); status.Level != IGraphTransformer::TStatus::Ok) {
  174. return status;
  175. }
  176. std::vector<std::string_view> rCheck;
  177. rCheck.reserve(rightKeys.size());
  178. for (const auto& x : rightKeys) {
  179. for (const auto& name : (*labels.FindInput(x.first))->AllNames(x.second))
  180. rCheck.emplace_back(ctx.AppendString(name));
  181. if (!myRightScope.contains(x.first)) {
  182. ctx.AddError(TIssue(ctx.GetPosition(joins.Pos()),
  183. TStringBuilder() << "Correlation name " << x.first << " is out of scope"));
  184. return IGraphTransformer::TStatus::Error;
  185. }
  186. joinsStates[*labels.FindInputIndex(x.first)].Used = true;
  187. }
  188. if (leftKeys.size() != rightKeys.size()) {
  189. ctx.AddError(TIssue(ctx.GetPosition(joins.Pos()),
  190. TStringBuilder() << "Mismatch of key column count in equality between " << leftKeys.front().first
  191. << " and " << rightKeys.front().first));
  192. return IGraphTransformer::TStatus::Error;
  193. }
  194. for (auto i = 0U; i < leftKeyTypes.size(); ++i) {
  195. if (strictKeys && leftKeyTypes[i] != rightKeyTypes[i]) {
  196. ctx.AddError(TIssue(ctx.GetPosition(joins.Pos()),
  197. TStringBuilder() << "Strict key type match requested, but keys have different types: ("
  198. << leftKeys[i].first << "." << leftKeys[i].second
  199. << " has type: " << *leftKeyTypes[i] << ", " << rightKeys[i].first << "." << rightKeys[i].second
  200. << " has type: " << *rightKeyTypes[i] << ")"));
  201. return IGraphTransformer::TStatus::Error;
  202. }
  203. if (ECompareOptions::Uncomparable == CanCompare<true>(leftKeyTypes[i], rightKeyTypes[i])) {
  204. ctx.AddError(TIssue(ctx.GetPosition(joins.Pos()),
  205. TStringBuilder() << "Cannot compare key columns (" << leftKeys[i].first << "." << leftKeys[i].second
  206. << " has type: " << *leftKeyTypes[i] << ", " << rightKeys[i].first << "." << rightKeys[i].second
  207. << " has type: " << *rightKeyTypes[i] << ")"));
  208. return IGraphTransformer::TStatus::Error;
  209. }
  210. }
  211. if (cross) {
  212. for (const auto& x : myLeftScope) {
  213. joinsStates[*labels.FindInputIndex(x)].Used = true;
  214. }
  215. for (const auto& x : myRightScope) {
  216. joinsStates[*labels.FindInputIndex(x)].Used = true;
  217. }
  218. }
  219. scope.clear();
  220. const bool singleSide = joinType.Content().ends_with("Only") || joinType.Content().ends_with("Semi");
  221. const bool rightSide = joinType.Content().starts_with("Right");
  222. const bool leftSide = joinType.Content().starts_with("Left");
  223. if (!singleSide || !rightSide) {
  224. scope.insert(myLeftScope.cbegin(), myLeftScope.cend());
  225. }
  226. if (!singleSide || !leftSide) {
  227. scope.insert(myRightScope.cbegin(), myRightScope.cend());
  228. }
  229. const auto linkOptions = joins.Child(5);
  230. if (!EnsureTuple(*linkOptions, ctx)) {
  231. return IGraphTransformer::TStatus::Error;
  232. }
  233. std::optional<std::unordered_set<std::string_view>> leftHints, rightHints;
  234. bool hasJoinStrategyHint = false;
  235. for (auto child : linkOptions->Children()) {
  236. if (!EnsureTupleMinSize(*child, 1, ctx)) {
  237. return IGraphTransformer::TStatus::Error;
  238. }
  239. if (!EnsureAtom(child->Head(), ctx)) {
  240. return IGraphTransformer::TStatus::Error;
  241. }
  242. const auto& option = child->Head();
  243. if (option.IsAtom({"left", "right"})) {
  244. if (!EnsureTupleSize(*child, 2, ctx)) {
  245. return IGraphTransformer::TStatus::Error;
  246. }
  247. auto& hints = option.IsAtom("left") ? leftHints : rightHints;
  248. if (hints) {
  249. ctx.AddError(TIssue(ctx.GetPosition(option.Pos()), TStringBuilder() <<
  250. "Duplication of hints for " << option.Content() << " side"));
  251. return IGraphTransformer::TStatus::Error;
  252. }
  253. hints.emplace();
  254. if (child->Child(1)->IsAtom()) {
  255. if (!AddEquiJoinLinkOptionHint(option.Content(), *hints, *child->Child(1), ctx)) {
  256. return IGraphTransformer::TStatus::Error;
  257. }
  258. } else {
  259. if (!EnsureTuple(*child->Child(1), ctx)) {
  260. return IGraphTransformer::TStatus::Error;
  261. }
  262. for (auto hint : child->Child(1)->Children()) {
  263. if (!AddEquiJoinLinkOptionHint(option.Content(), *hints, *hint, ctx)) {
  264. return IGraphTransformer::TStatus::Error;
  265. }
  266. }
  267. }
  268. }
  269. else if (option.IsAtom("forceSortedMerge") || option.IsAtom("forceStreamLookup")) {
  270. if (!EnsureTupleSize(*child, 1, ctx)) {
  271. return IGraphTransformer::TStatus::Error;
  272. }
  273. if (hasJoinStrategyHint) {
  274. ctx.AddError(TIssue(ctx.GetPosition(option.Pos()), TStringBuilder() <<
  275. "Duplicate " << option.Content() << " link option"));
  276. return IGraphTransformer::TStatus::Error;
  277. }
  278. hasJoinStrategyHint = true;
  279. }
  280. else if (option.IsAtom("join_algo")) {
  281. //do nothing
  282. }
  283. else if (option.IsAtom("compact")) {
  284. if (!EnsureTupleSize(*child, 1, ctx)) {
  285. return IGraphTransformer::TStatus::Error;
  286. }
  287. }
  288. else {
  289. ctx.AddError(TIssue(ctx.GetPosition(option.Pos()), TStringBuilder() <<
  290. "Unknown option name: " << option.Content()));
  291. return IGraphTransformer::TStatus::Error;
  292. }
  293. }
  294. const bool lAny = leftHints && (leftHints->contains("unique") || leftHints->contains("any"));
  295. const bool rAny = rightHints && (rightHints->contains("unique") || rightHints->contains("any"));
  296. const bool lOneRow = lAny || lUnique && lUnique->ContainsCompleteSet(lCheck);
  297. const bool rOneRow = rAny || rUnique && rUnique->ContainsCompleteSet(rCheck);
  298. if (unique) {
  299. if (singleSide) {
  300. if (leftSide)
  301. *unique = lUnique;
  302. else if (rightSide)
  303. *unique = rUnique;
  304. } else if (!joinType.IsAtom("Cross")) {
  305. const bool exclusion = joinType.IsAtom("Exclusion") ;
  306. const bool useLeft = lUnique && (rOneRow || exclusion);
  307. const bool useRight = rUnique && (lOneRow || exclusion);
  308. if (useLeft && !useRight)
  309. *unique = lUnique;
  310. else if (useRight && !useLeft)
  311. *unique = rUnique;
  312. else if (useLeft && useRight)
  313. *unique = TUniqueConstraintNode::Merge(lUnique, rUnique, ctx);
  314. }
  315. }
  316. if (distinct) {
  317. if (singleSide) {
  318. if (leftSide)
  319. *distinct = lDistinct;
  320. else if (rightSide)
  321. *distinct = rDistinct;
  322. } else if (!joinType.IsAtom("Cross")) {
  323. const bool inner = joinType.IsAtom("Inner");
  324. const bool useLeft = lDistinct && rOneRow && (inner || leftSide);
  325. const bool useRight = rDistinct && lOneRow && (inner || rightSide);
  326. if (useLeft && !useRight)
  327. *distinct = lDistinct;
  328. else if (useRight && !useLeft)
  329. *distinct = rDistinct;
  330. else if (useLeft && useRight)
  331. *distinct = TDistinctConstraintNode::Merge(lDistinct, rDistinct, ctx);
  332. }
  333. }
  334. return IGraphTransformer::TStatus::Ok;
  335. }
  336. struct TFlattenState {
  337. TString Table;
  338. TTypeAnnotationNode::TListType AllTypes;
  339. };
  340. void CollectEquiJoinKeyColumnsFromLeaf(const TExprNode& columns, THashMap<TStringBuf, THashSet<TStringBuf>>& tableKeysMap) {
  341. YQL_ENSURE(columns.ChildrenSize() % 2 == 0);
  342. for (ui32 i = 0; i < columns.ChildrenSize(); i += 2) {
  343. auto table = columns.Child(i)->Content();
  344. auto column = columns.Child(i + 1)->Content();
  345. tableKeysMap[table].insert(column);
  346. }
  347. }
  348. void CollectEquiJoinKeyColumns(const TExprNode& joinTree, THashMap<TStringBuf, THashSet<TStringBuf>>& tableKeysMap) {
  349. auto& left = *joinTree.Child(1);
  350. if (!left.IsAtom()) {
  351. CollectEquiJoinKeyColumns(left, tableKeysMap);
  352. }
  353. auto& right = *joinTree.Child(2);
  354. if (!right.IsAtom()) {
  355. CollectEquiJoinKeyColumns(right, tableKeysMap);
  356. }
  357. CollectEquiJoinKeyColumnsFromLeaf(*joinTree.Child(3), tableKeysMap);
  358. CollectEquiJoinKeyColumnsFromLeaf(*joinTree.Child(4), tableKeysMap);
  359. }
  360. bool CollectEquiJoinOnlyParents(const TExprNode& current, const TExprNode* prev, ui32 depth,
  361. TVector<TEquiJoinParent>& results, const TExprNode* extractMembersInScope,
  362. const TParentsMap& parents)
  363. {
  364. if (depth == 0) {
  365. if (!prev || !TCoEquiJoin::Match(&current)) {
  366. return false;
  367. }
  368. TCoEquiJoin equiJoin(&current);
  369. for (ui32 i = 0; i + 2 < equiJoin.ArgCount(); ++i) {
  370. auto joinInput = equiJoin.Arg(i).Cast<TCoEquiJoinInput>();
  371. auto list = joinInput.List();
  372. if (list.Raw() == prev) {
  373. results.emplace_back(equiJoin.Raw(), i, extractMembersInScope);
  374. return true;
  375. }
  376. }
  377. YQL_ENSURE(false, "Unable to locate FlatMap in EquiJoin");
  378. }
  379. auto it = parents.find(&current);
  380. if (it == parents.end() || it->second.empty()) {
  381. return false;
  382. }
  383. const TExprNode* extractMembers = extractMembersInScope;
  384. bool currentIsExtractMembers = TCoExtractMembers::Match(&current);
  385. if (currentIsExtractMembers) {
  386. if (extractMembers) {
  387. // repeatable extract members should not actually happen
  388. return false;
  389. }
  390. extractMembers = current.Child(1);
  391. }
  392. auto nextPrev = (TCoFlatMapBase::Match(&current) || currentIsExtractMembers) ? &current : prev;
  393. for (auto parent : it->second) {
  394. if (!CollectEquiJoinOnlyParents(*parent, nextPrev, currentIsExtractMembers ? depth : (depth - 1), results,
  395. extractMembers, parents))
  396. {
  397. return false;
  398. }
  399. }
  400. return true;
  401. }
  402. }
  403. TMaybe<TIssue> TJoinLabel::Parse(TExprContext& ctx, TExprNode& node, const TStructExprType* structType, const TUniqueConstraintNode* unique, const TDistinctConstraintNode* distinct) {
  404. Tables.clear();
  405. InputType = structType;
  406. Unique = unique;
  407. Distinct = distinct;
  408. if (auto atom = TMaybeNode<TCoAtom>(&node)) {
  409. if (auto err = ValidateLabel(ctx, atom.Cast())) {
  410. return err;
  411. }
  412. AddLabel = true;
  413. Tables.push_back(atom.Cast().Value());
  414. return {};
  415. }
  416. else if (auto tuple = TMaybeNode<TCoAtomList>(&node)) {
  417. if (tuple.Cast().Size() == 0) {
  418. return TIssue(ctx.GetPosition(node.Pos()), "Empty list of correlation names are not allowed");
  419. }
  420. for (const auto& child : tuple.Cast()) {
  421. if (auto err = ValidateLabel(ctx, child)) {
  422. return err;
  423. }
  424. Tables.push_back(child.Value());
  425. }
  426. Sort(Tables);
  427. auto prevLabel = Tables[0];
  428. for (ui32 i = 1; i < Tables.size(); ++i) {
  429. if (Tables[i] == prevLabel) {
  430. return TIssue(ctx.GetPosition(node.Pos()), TStringBuilder() << "Duplication of correlation names: " << prevLabel);
  431. }
  432. prevLabel = Tables[i];
  433. }
  434. // all labels are unique, ensure that all columns are under one of label
  435. for (auto column : InputType->GetItems()) {
  436. auto name = column->GetName();
  437. auto pos = name.find('.');
  438. if (pos == TString::npos) {
  439. return TIssue(ctx.GetPosition(node.Pos()), TStringBuilder() << "Expected columns name as table.name, but got: " << name);
  440. }
  441. auto table = name.substr(0, pos);
  442. if (!BinarySearch(Tables.begin(), Tables.end(), table)) {
  443. return TIssue(ctx.GetPosition(node.Pos()), TStringBuilder() << "Unknown table name: " << table);
  444. }
  445. auto columnName = name.substr(pos + 1);
  446. if (columnName.empty()) {
  447. return TIssue(ctx.GetPosition(node.Pos()), "Empty correlation name is not allowed");
  448. }
  449. }
  450. return {};
  451. }
  452. else {
  453. return TIssue(ctx.GetPosition(node.Pos()), TStringBuilder() << "Expected either atom or list, but got" << node.Type());
  454. }
  455. }
  456. TMaybe<TIssue> TJoinLabel::ValidateLabel(TExprContext& ctx, const TCoAtom& label) {
  457. if (label.Value().empty()) {
  458. return TIssue(ctx.GetPosition(label.Pos()), "Empty correlation name is not allowed");
  459. }
  460. if (label.Value().Contains('.')) {
  461. return TIssue(ctx.GetPosition(label.Pos()), "Dot symbol is not allowed in the correlation name");
  462. }
  463. return {};
  464. }
  465. TString TJoinLabel::FullName(const TStringBuf& column) const {
  466. if (AddLabel) {
  467. return FullColumnName(Tables.front(), column);
  468. } else {
  469. return TString(column);
  470. }
  471. }
  472. TVector<TString> TJoinLabel::AllNames(const TStringBuf& column) const {
  473. TVector<TString> result(Tables.size());
  474. std::transform(Tables.cbegin(), Tables.cend(), result.begin(), std::bind(&FullColumnName, std::placeholders::_1, std::cref(column)));
  475. return result;
  476. }
  477. TStringBuf TJoinLabel::ColumnName(const TStringBuf& column) const {
  478. auto pos = column.find('.');
  479. if (pos == TString::npos) {
  480. return column;
  481. }
  482. return column.substr(pos + 1);
  483. }
  484. TStringBuf TJoinLabel::TableName(const TStringBuf& column) const {
  485. auto pos = column.find('.');
  486. if (pos == TString::npos) {
  487. YQL_ENSURE(AddLabel);
  488. return Tables[0];
  489. }
  490. return column.substr(0, pos);
  491. }
  492. bool TJoinLabel::HasTable(const TStringBuf& table) const {
  493. return BinarySearch(Tables.begin(), Tables.end(), table);
  494. }
  495. TMaybe<const TTypeAnnotationNode*> TJoinLabel::FindColumn(const TStringBuf& table, const TStringBuf& column) const {
  496. auto pos = InputType->FindItem(MemberName(table, column));
  497. if (!pos) {
  498. return TMaybe<const TTypeAnnotationNode*>();
  499. }
  500. return InputType->GetItems()[*pos]->GetItemType();
  501. }
  502. TString TJoinLabel::MemberName(const TStringBuf& table, const TStringBuf& column) const {
  503. return AddLabel ? TString(column) : FullColumnName(table, column);
  504. }
  505. TVector<TString> TJoinLabel::EnumerateAllColumns() const {
  506. TVector<TString> result;
  507. if (AddLabel) {
  508. // add label to all columns
  509. for (auto& x : InputType->GetItems()) {
  510. result.push_back(FullColumnName(Tables[0], x->GetName()));
  511. }
  512. } else {
  513. for (auto& x : InputType->GetItems()) {
  514. result.push_back(TString(x->GetName()));
  515. }
  516. }
  517. return result;
  518. }
  519. TVector<TString> TJoinLabel::EnumerateAllMembers() const {
  520. TVector<TString> result;
  521. for (auto& x : InputType->GetItems()) {
  522. result.push_back(TString(x->GetName()));
  523. }
  524. return result;
  525. }
  526. TMaybe<TIssue> TJoinLabels::Add(TExprContext& ctx, TExprNode& node, const TStructExprType* structType, const TUniqueConstraintNode* unique, const TDistinctConstraintNode* distinct) {
  527. ui32 index = Inputs.size();
  528. Inputs.emplace_back();
  529. TJoinLabel& label = Inputs.back();
  530. if (auto err = label.Parse(ctx, node, structType, unique, distinct)) {
  531. return err;
  532. }
  533. for (auto& table : label.Tables) {
  534. if (!InputByTable.insert({ table, index }).second) {
  535. return TIssue(
  536. ctx.GetPosition(node.Pos()),
  537. TStringBuilder() << "Duplication of table name " << table);
  538. }
  539. }
  540. return {};
  541. }
  542. TMaybe<const TJoinLabel*> TJoinLabels::FindInput(const TStringBuf& table) const {
  543. auto inputIndex = InputByTable.FindPtr(table);
  544. if (!inputIndex) {
  545. return {};
  546. }
  547. return &Inputs[*inputIndex];
  548. }
  549. TMaybe<ui32> TJoinLabels::FindInputIndex(const TStringBuf& table) const {
  550. auto inputIndex = InputByTable.FindPtr(table);
  551. if (!inputIndex) {
  552. return{};
  553. }
  554. return *inputIndex;
  555. }
  556. TMaybe<const TTypeAnnotationNode*> TJoinLabels::FindColumn(const TStringBuf& table, const TStringBuf& column) const {
  557. auto tableIndex = InputByTable.FindPtr(table);
  558. if (!tableIndex) {
  559. return TMaybe<const TTypeAnnotationNode*>();
  560. }
  561. return Inputs[*tableIndex].FindColumn(table, column);
  562. }
  563. TMaybe<const TTypeAnnotationNode*> TJoinLabels::FindColumn(const TStringBuf& fullName) const {
  564. TStringBuf part1;
  565. TStringBuf part2;
  566. SplitTableName(fullName, part1, part2);
  567. return FindColumn(part1, part2);
  568. }
  569. TVector<TString> TJoinLabels::EnumerateColumns(const TStringBuf& table) const {
  570. TVector<TString> result;
  571. auto tableIndex = InputByTable.FindPtr(table);
  572. Y_ENSURE(tableIndex, "Unknown table:" << table);
  573. auto& label = Inputs[*tableIndex];
  574. if (label.AddLabel) {
  575. // add label to all columns
  576. for (auto& x : label.InputType->GetItems()) {
  577. result.push_back(FullColumnName(table, x->GetName()));
  578. }
  579. }
  580. else {
  581. // filter out some columns
  582. for (auto& x : label.InputType->GetItems()) {
  583. TStringBuf part1;
  584. TStringBuf part2;
  585. SplitTableName(x->GetName(), part1, part2);
  586. if (part1 == table) {
  587. result.push_back(TString(x->GetName()));
  588. }
  589. }
  590. }
  591. return result;
  592. }
  593. IGraphTransformer::TStatus ValidateEquiJoinOptions(TPositionHandle positionHandle, TExprNode& optionsNode,
  594. TJoinOptions& options, TExprContext& ctx)
  595. {
  596. auto position = ctx.GetPosition(positionHandle);
  597. if (!EnsureTuple(optionsNode, ctx)) {
  598. return IGraphTransformer::TStatus::Error;
  599. }
  600. options = TJoinOptions{};
  601. THashSet<TStringBuf> renameTargetSet;
  602. bool hasRename = false;
  603. for (auto child : optionsNode.Children()) {
  604. if (!EnsureTupleMinSize(*child, 1, ctx)) {
  605. return IGraphTransformer::TStatus::Error;
  606. }
  607. if (!EnsureAtom(*child->Child(0), ctx)) {
  608. return IGraphTransformer::TStatus::Error;
  609. }
  610. auto optionName = child->Child(0)->Content();
  611. if (optionName == "rename") {
  612. hasRename = true;
  613. if (!EnsureTupleSize(*child, 3, ctx)) {
  614. return IGraphTransformer::TStatus::Error;
  615. }
  616. if (!EnsureAtom(*child->Child(1), ctx)) {
  617. return IGraphTransformer::TStatus::Error;
  618. }
  619. if (!EnsureAtom(*child->Child(2), ctx)) {
  620. return IGraphTransformer::TStatus::Error;
  621. }
  622. auto& v = options.RenameMap[child->Child(1)->Content()];
  623. if (!child->Child(2)->Content().empty()) {
  624. if (!renameTargetSet.insert(child->Child(2)->Content()).second) {
  625. ctx.AddError(TIssue(position, TStringBuilder() <<
  626. "Duplicated target column: " << child->Child(2)->Content()));
  627. return IGraphTransformer::TStatus::Error;
  628. }
  629. v.push_back(child->Child(2)->Content());
  630. }
  631. } else if (optionName == "flatten") {
  632. options.Flatten = true;
  633. } else if (optionName == "strict_keys") {
  634. options.StrictKeys = true;
  635. } else if (optionName == "preferred_sort") {
  636. THashSet<TStringBuf> sortBySet;
  637. TVector<TStringBuf> sortBy;
  638. if (!EnsureTupleSize(*child, 2, ctx)) {
  639. return IGraphTransformer::TStatus::Error;
  640. }
  641. if (!EnsureTupleMinSize(*child->Child(1), 1, ctx)) {
  642. return IGraphTransformer::TStatus::Error;
  643. }
  644. for (auto column : child->Child(1)->Children()) {
  645. if (!EnsureAtom(*column, ctx)) {
  646. return IGraphTransformer::TStatus::Error;
  647. }
  648. if (!sortBySet.insert(column->Content()).second) {
  649. ctx.AddError(TIssue(ctx.GetPosition(column->Pos()), TStringBuilder() <<
  650. "Duplicated preferred_sort column: " << column->Content()));
  651. return IGraphTransformer::TStatus::Error;
  652. }
  653. sortBy.push_back(column->Content());
  654. }
  655. if (!options.PreferredSortSets.insert(sortBy).second) {
  656. ctx.AddError(TIssue(ctx.GetPosition(child->Child(1)->Pos()), TStringBuilder() <<
  657. "Duplicated preferred_sort set: " << JoinSeq(", ", sortBy)));
  658. }
  659. } else if (optionName == "cbo_passed") {
  660. // do nothing
  661. } else if (optionName == "join_algo") {
  662. // do nothing
  663. } else if (optionName == "compact") {
  664. options.Compact = true;
  665. } else {
  666. ctx.AddError(TIssue(position, TStringBuilder() <<
  667. "Unknown option name: " << optionName));
  668. return IGraphTransformer::TStatus::Error;
  669. }
  670. if (hasRename && options.Flatten) {
  671. ctx.AddError(TIssue(position, TStringBuilder() <<
  672. "Options flatten and rename are incompatible with each other"));
  673. return IGraphTransformer::TStatus::Error;
  674. }
  675. }
  676. return IGraphTransformer::TStatus::Ok;
  677. }
  678. IGraphTransformer::TStatus EquiJoinAnnotation(
  679. TPositionHandle positionHandle,
  680. const TStructExprType*& resultType,
  681. const TJoinLabels& labels,
  682. TExprNode& joins,
  683. const TJoinOptions& options,
  684. TExprContext& ctx
  685. ) {
  686. auto position = ctx.GetPosition(positionHandle);
  687. if (labels.InputByTable.size() < 2) {
  688. ctx.AddError(TIssue(position, TStringBuilder() << "Expected at least 2 table"));
  689. return IGraphTransformer::TStatus::Error;
  690. }
  691. TVector<TJoinState> joinsStates(labels.Inputs.size());
  692. TGLobalJoinState globalState;
  693. THashSet<TStringBuf> scope;
  694. auto parseStatus = ParseJoins(labels, joins, joinsStates, scope, globalState, options.StrictKeys, ctx);
  695. if (parseStatus.Level != IGraphTransformer::TStatus::Ok) {
  696. return parseStatus;
  697. }
  698. if (globalState.NestedJoins + 2 != labels.Inputs.size()) {
  699. ctx.AddError(TIssue(position,
  700. TStringBuilder() << "Too few nested joins, expected exactly: " << (labels.Inputs.size() - 2)));
  701. return IGraphTransformer::TStatus::Error;
  702. }
  703. for (ui32 i = 0; i < joinsStates.size(); ++i) {
  704. if (!joinsStates[i].Used) {
  705. ctx.AddError(TIssue(position, TStringBuilder() <<
  706. "Input with correlation name(s) " << JoinSeq(", ", labels.Inputs[i].Tables) << " was not used"));
  707. return IGraphTransformer::TStatus::Error;
  708. }
  709. }
  710. auto columnTypes = GetJoinColumnTypes(joins, labels, ctx);
  711. TVector<const TItemExprType*> resultFields;
  712. TMap<TString, TFlattenState> flattenFields; // column -> table
  713. THashSet<TString> processedRenames;
  714. for (auto it: labels.Inputs) {
  715. for (auto item: it.InputType->GetItems()) {
  716. TString fullName = it.FullName(item->GetName());
  717. auto type = columnTypes.FindPtr(fullName);
  718. if (type) {
  719. TVector<TStringBuf> fullNames;
  720. fullNames.push_back(fullName);
  721. if (!processedRenames.contains(fullName)) {
  722. auto renameIt = options.RenameMap.find(fullName);
  723. if (renameIt != options.RenameMap.end()) {
  724. fullNames = renameIt->second;
  725. processedRenames.insert(fullName);
  726. }
  727. }
  728. for (auto& fullName: fullNames) {
  729. if (options.Flatten) {
  730. auto tableName = it.TableName(fullName);
  731. auto columnName = it.ColumnName(fullName);
  732. auto iter = flattenFields.find(columnName);
  733. if (iter != flattenFields.end()) {
  734. if (AreSameJoinKeys(joins, tableName, columnName, iter->second.Table, columnName)) {
  735. iter->second.AllTypes.push_back(*type);
  736. continue;
  737. }
  738. ctx.AddError(TIssue(position, TStringBuilder() <<
  739. "Conflict of flattening output on columns " << fullName << " and " << iter->second.Table
  740. << "." << columnName));
  741. return IGraphTransformer::TStatus::Error;
  742. }
  743. TFlattenState state;
  744. state.AllTypes.push_back(*type);
  745. state.Table = TString(tableName);
  746. flattenFields.emplace(TString(columnName), state);
  747. } else {
  748. resultFields.push_back(ctx.MakeType<TItemExprType>(fullName, *type));
  749. }
  750. }
  751. }
  752. }
  753. }
  754. if (options.Flatten) {
  755. for (auto& x : flattenFields) {
  756. if (const auto commonType = CommonType(positionHandle, x.second.AllTypes, ctx)) {
  757. const bool unwrap = ETypeAnnotationKind::Optional == commonType->GetKind() &&
  758. std::any_of(x.second.AllTypes.cbegin(), x.second.AllTypes.cend(), [](const TTypeAnnotationNode* type) { return ETypeAnnotationKind::Optional != type->GetKind(); });
  759. resultFields.emplace_back(ctx.MakeType<TItemExprType>(x.first, unwrap ? commonType->Cast<TOptionalExprType>()->GetItemType() : commonType));
  760. } else
  761. return IGraphTransformer::TStatus::Error;
  762. }
  763. }
  764. resultType = ctx.MakeType<TStructExprType>(resultFields);
  765. if (!resultType->Validate(position, ctx)) {
  766. return IGraphTransformer::TStatus::Error;
  767. }
  768. return IGraphTransformer::TStatus::Ok;
  769. }
  770. IGraphTransformer::TStatus EquiJoinConstraints(
  771. TPositionHandle positionHandle,
  772. const TUniqueConstraintNode*& unique,
  773. const TDistinctConstraintNode*& distinct,
  774. const TJoinLabels& labels,
  775. TExprNode& joins,
  776. TExprContext& ctx
  777. ) {
  778. const auto position = ctx.GetPosition(positionHandle);
  779. YQL_ENSURE(labels.InputByTable.size() >= 2U);
  780. TVector<TJoinState> joinsStates(labels.Inputs.size());
  781. TGLobalJoinState globalState;
  782. THashSet<TStringBuf> scope;
  783. if (const auto parseStatus = ParseJoins(labels, joins, joinsStates, scope, globalState, false, ctx, &unique, &distinct); parseStatus.Level != IGraphTransformer::TStatus::Ok) {
  784. return parseStatus;
  785. }
  786. return IGraphTransformer::TStatus::Ok;
  787. }
  788. THashMap<TStringBuf, THashSet<TStringBuf>> CollectEquiJoinKeyColumnsByLabel(const TExprNode& joinTree) {
  789. THashMap<TStringBuf, THashSet<TStringBuf>> result;
  790. CollectEquiJoinKeyColumns(joinTree, result);
  791. return result;
  792. };
  793. bool IsLeftJoinSideOptional(const TStringBuf& joinType) {
  794. if (joinType == "Right" || joinType == "Full" || joinType == "Exclusion") {
  795. return true;
  796. }
  797. return false;
  798. }
  799. bool IsRightJoinSideOptional(const TStringBuf& joinType) {
  800. if (joinType == "Left" || joinType == "Full" || joinType == "Exclusion") {
  801. return true;
  802. }
  803. return false;
  804. }
  805. TExprNode::TPtr FilterOutNullJoinColumns(TPositionHandle pos, const TExprNode::TPtr& input,
  806. const TJoinLabel& label, const TSet<TString>& optionalKeyColumns, TExprContext& ctx) {
  807. if (optionalKeyColumns.empty()) {
  808. return input;
  809. }
  810. TExprNode::TListType optColumns;
  811. for (auto fullColumnName : optionalKeyColumns) {
  812. TStringBuf table;
  813. TStringBuf column;
  814. SplitTableName(fullColumnName, table, column);
  815. auto memberName = label.MemberName(table, column);
  816. optColumns.push_back(ctx.NewAtom(pos, memberName));
  817. }
  818. return ctx.Builder(pos)
  819. .Callable("SkipNullMembers")
  820. .Add(0, input)
  821. .List(1)
  822. .Add(std::move(optColumns))
  823. .Seal()
  824. .Seal()
  825. .Build();
  826. }
  827. TMap<TStringBuf, TVector<TStringBuf>> LoadJoinRenameMap(const TExprNode& settings) {
  828. TMap<TStringBuf, TVector<TStringBuf>> res;
  829. for (const auto& child : settings.Children()) {
  830. if (child->Head().IsAtom("rename")) {
  831. auto& v = res[child->Child(1)->Content()];
  832. if (!child->Child(2)->Content().empty()) {
  833. v.push_back(child->Child(2)->Content());
  834. }
  835. }
  836. }
  837. return res;
  838. }
  839. TCoLambda BuildJoinRenameLambda(TPositionHandle pos, const TMap<TStringBuf, TVector<TStringBuf>>& renameMap,
  840. const TStructExprType& joinResultType, TExprContext& ctx)
  841. {
  842. THashMap<TStringBuf, TStringBuf> reverseRenameMap;
  843. for (const auto& [oldName , targets] : renameMap) {
  844. for (TStringBuf newName : targets) {
  845. reverseRenameMap[newName] = oldName;
  846. }
  847. }
  848. TCoArgument rowArg = Build<TCoArgument>(ctx, pos)
  849. .Name("row")
  850. .Done();
  851. TVector<TExprBase> renameTuples;
  852. for (auto& item : joinResultType.GetItems()) {
  853. TStringBuf newName = item->GetName();
  854. auto renamedFrom = reverseRenameMap.FindPtr(newName);
  855. TStringBuf oldName = renamedFrom ? *renamedFrom : newName;
  856. auto tuple = Build<TCoNameValueTuple>(ctx, pos)
  857. .Name().Build(newName)
  858. .Value<TCoMember>()
  859. .Struct(rowArg)
  860. .Name().Build(oldName)
  861. .Build()
  862. .Done();
  863. renameTuples.push_back(tuple);
  864. }
  865. return Build<TCoLambda>(ctx, pos)
  866. .Args({rowArg})
  867. .Body<TCoAsStruct>()
  868. .Add(renameTuples)
  869. .Build()
  870. .Done();
  871. }
  872. TSet<TVector<TStringBuf>> LoadJoinSortSets(const TExprNode& settings) {
  873. TSet<TVector<TStringBuf>> res;
  874. for (const auto& child : settings.Children()) {
  875. if (child->Child(0)->Content() == "preferred_sort") {
  876. TVector<TStringBuf> sortBy;
  877. for (auto column : child->Child(1)->Children()) {
  878. sortBy.push_back(column->Content());
  879. }
  880. res.insert(sortBy);
  881. }
  882. }
  883. return res;
  884. }
  885. THashMap<TString, const TTypeAnnotationNode*> GetJoinColumnTypes(const TExprNode& joins,
  886. const TJoinLabels& labels, TExprContext& ctx) {
  887. return GetJoinColumnTypes(joins, labels, joins.Child(0)->Content(), ctx);
  888. }
  889. THashMap<TString, const TTypeAnnotationNode*> GetJoinColumnTypes(const TExprNode& joins,
  890. const TJoinLabels& labels, const TStringBuf& joinType, TExprContext& ctx) {
  891. THashMap<TString, const TTypeAnnotationNode*> finalType;
  892. THashMap<TString, const TTypeAnnotationNode*> leftType;
  893. THashMap<TString, const TTypeAnnotationNode*> rightType;
  894. bool isLeftOptional = IsLeftJoinSideOptional(joinType);
  895. bool isRightOptional = IsRightJoinSideOptional(joinType);
  896. if (joins.Child(1)->IsAtom()) {
  897. auto name = joins.Child(1)->Content();
  898. auto input = *labels.FindInput(name);
  899. for (auto& x : input->InputType->GetItems()) {
  900. leftType[input->FullName(x->GetName())] = x->GetItemType();
  901. }
  902. }
  903. else {
  904. leftType = GetJoinColumnTypes(*joins.Child(1), labels, ctx);
  905. }
  906. if (joins.Child(2)->IsAtom()) {
  907. auto name = joins.Child(2)->Content();
  908. auto input = *labels.FindInput(name);
  909. for (auto& x : input->InputType->GetItems()) {
  910. rightType[input->FullName(x->GetName())] = x->GetItemType();
  911. }
  912. }
  913. else {
  914. rightType = GetJoinColumnTypes(*joins.Child(2), labels, ctx);
  915. }
  916. if (isLeftOptional) {
  917. for (auto& x : leftType) {
  918. x.second = AddOptionalType(x.second, ctx);
  919. }
  920. }
  921. if (isRightOptional) {
  922. for (auto& x : rightType) {
  923. x.second = AddOptionalType(x.second, ctx);
  924. }
  925. }
  926. if (joinType != "RightOnly" && joinType != "RightSemi") {
  927. for (auto& x : leftType) {
  928. finalType.insert({ x.first, x.second });
  929. }
  930. }
  931. if (joinType != "LeftOnly" && joinType != "LeftSemi") {
  932. for (auto& x : rightType) {
  933. finalType.insert({ x.first, x.second });
  934. }
  935. }
  936. return finalType;
  937. }
  938. bool AreSameJoinKeys(const TExprNode& joins, const TStringBuf& table1, const TStringBuf& column1, const TStringBuf& table2, const TStringBuf& column2) {
  939. if (!joins.Child(1)->IsAtom()) {
  940. if (AreSameJoinKeys(*joins.Child(1), table1, column1, table2, column2)) {
  941. return true;
  942. }
  943. }
  944. if (!joins.Child(2)->IsAtom()) {
  945. if (AreSameJoinKeys(*joins.Child(2), table1, column1, table2, column2)) {
  946. return true;
  947. }
  948. }
  949. for (ui32 i = 0; i < joins.Child(3)->ChildrenSize(); i += 2) {
  950. if (joins.Child(3)->Child(i)->Content() == table1) {
  951. if (joins.Child(4)->Child(i)->Content() == table2 &&
  952. joins.Child(3)->Child(i + 1)->Content() == column1 &&
  953. joins.Child(4)->Child(i + 1)->Content() == column2) {
  954. return true;
  955. }
  956. }
  957. else if (joins.Child(3)->Child(i)->Content() == table2) {
  958. if (joins.Child(4)->Child(i)->Content() == table1 &&
  959. joins.Child(3)->Child(i + 1)->Content() == column2 &&
  960. joins.Child(4)->Child(i + 1)->Content() == column1) {
  961. return true;
  962. }
  963. }
  964. }
  965. return false;
  966. }
  967. std::pair<bool, bool> IsRequiredSide(const TExprNode::TPtr& joinTree, const TJoinLabels& labels, ui32 inputIndex) {
  968. auto joinType = joinTree->Child(0)->Content();
  969. auto left = joinTree->ChildPtr(1);
  970. auto right = joinTree->ChildPtr(2);
  971. if (joinType == "Inner" || joinType == "Left" || joinType == "LeftOnly" || joinType == "LeftSemi" || joinType == "RightSemi" || joinType == "Cross") {
  972. if (!left->IsAtom()) {
  973. auto x = IsRequiredSide(left, labels, inputIndex);
  974. if (x.first) {
  975. return x;
  976. }
  977. }
  978. else {
  979. auto table = left->Content();
  980. if (*labels.FindInputIndex(table) == inputIndex) {
  981. return { true, joinType == "Inner" || joinType == "LeftSemi" };
  982. }
  983. }
  984. }
  985. if (joinType == "Inner" || joinType == "Right" || joinType == "RightOnly" || joinType == "RightSemi" || joinType == "LeftSemi" || joinType == "Cross") {
  986. if (!right->IsAtom()) {
  987. auto x = IsRequiredSide(right, labels, inputIndex);
  988. if (x.first) {
  989. return x;
  990. }
  991. }
  992. else {
  993. auto table = right->Content();
  994. if (*labels.FindInputIndex(table) == inputIndex) {
  995. return{ true, joinType == "Inner" || joinType == "RightSemi"};
  996. }
  997. }
  998. }
  999. return{ false, false };
  1000. }
  1001. TMaybe<bool> IsFilteredSide(const TExprNode::TPtr& joinTree, const TJoinLabels& labels, ui32 inputIndex) {
  1002. auto joinType = joinTree->Child(0)->Content();
  1003. auto left = joinTree->ChildPtr(1);
  1004. auto right = joinTree->ChildPtr(2);
  1005. TMaybe<bool> isLeftFiltered;
  1006. if (!left->IsAtom()) {
  1007. isLeftFiltered = IsFilteredSide(left, labels, inputIndex);
  1008. } else {
  1009. auto table = left->Content();
  1010. if (*labels.FindInputIndex(table) == inputIndex) {
  1011. if (joinType == "Inner" || joinType == "LeftOnly" || joinType == "LeftSemi") {
  1012. isLeftFiltered = true;
  1013. } else if (joinType != "RightOnly" && joinType != "RightSemi") {
  1014. isLeftFiltered = false;
  1015. }
  1016. }
  1017. }
  1018. TMaybe<bool> isRightFiltered;
  1019. if (!right->IsAtom()) {
  1020. isRightFiltered = IsFilteredSide(right, labels, inputIndex);
  1021. } else {
  1022. auto table = right->Content();
  1023. if (*labels.FindInputIndex(table) == inputIndex) {
  1024. if (joinType == "Inner" || joinType == "RightOnly" || joinType == "RightSemi") {
  1025. isRightFiltered = true;
  1026. } else if (joinType != "LeftOnly" && joinType != "LeftSemi") {
  1027. isRightFiltered = false;
  1028. }
  1029. }
  1030. }
  1031. YQL_ENSURE(!(isLeftFiltered.Defined() && isRightFiltered.Defined()));
  1032. if (!isLeftFiltered.Defined() && !isRightFiltered.Defined()) {
  1033. return {};
  1034. }
  1035. return isLeftFiltered.Defined() ? isLeftFiltered : isRightFiltered;
  1036. }
  1037. void AppendEquiJoinRenameMap(TPositionHandle pos, const TMap<TStringBuf, TVector<TStringBuf>>& newRenameMap,
  1038. TExprNode::TListType& joinSettingNodes, TExprContext& ctx) {
  1039. for (auto& x : newRenameMap) {
  1040. if (x.second.empty()) {
  1041. joinSettingNodes.push_back(ctx.Builder(pos)
  1042. .List()
  1043. .Atom(0, "rename")
  1044. .Atom(1, x.first)
  1045. .Atom(2, "")
  1046. .Seal()
  1047. .Build());
  1048. continue;
  1049. }
  1050. for (auto& y : x.second) {
  1051. if (x.first == y && x.second.size() == 1) {
  1052. continue;
  1053. }
  1054. joinSettingNodes.push_back(ctx.Builder(pos)
  1055. .List()
  1056. .Atom(0, "rename")
  1057. .Atom(1, x.first)
  1058. .Atom(2, y)
  1059. .Seal()
  1060. .Build());
  1061. }
  1062. }
  1063. }
  1064. void AppendEquiJoinSortSets(TPositionHandle pos, const TSet<TVector<TStringBuf>>& newSortSets,
  1065. TExprNode::TListType& joinSettingNodes, TExprContext& ctx)
  1066. {
  1067. for (auto& ss : newSortSets) {
  1068. YQL_ENSURE(!ss.empty());
  1069. joinSettingNodes.push_back(ctx.Builder(pos)
  1070. .List()
  1071. .Atom(0, "preferred_sort")
  1072. .List(1)
  1073. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1074. for (ui32 i = 0; i < ss.size(); ++i) {
  1075. parent.Atom(i, ss[i]);
  1076. }
  1077. return parent;
  1078. })
  1079. .Seal()
  1080. .Seal()
  1081. .Build());
  1082. }
  1083. }
  1084. TMap<TStringBuf, TVector<TStringBuf>> UpdateUsedFieldsInRenameMap(
  1085. const TMap<TStringBuf, TVector<TStringBuf>>& renameMap,
  1086. const TSet<TStringBuf>& usedFields,
  1087. const TStructExprType* structType
  1088. ) {
  1089. TMap<TStringBuf, TStringBuf> reversedRenameMap;
  1090. TMap<TStringBuf, TVector<TStringBuf>> newRenameMap;
  1091. for (auto& x : renameMap) {
  1092. if (!x.second.empty()) {
  1093. for (auto& y : x.second) {
  1094. reversedRenameMap[y] = x.first;
  1095. }
  1096. }
  1097. else {
  1098. // previous drops
  1099. newRenameMap[x.first].clear();
  1100. }
  1101. }
  1102. for (auto& item : structType->GetItems()) {
  1103. bool needRemove = !usedFields.contains(item->GetName());
  1104. if (auto renamed = reversedRenameMap.FindPtr(item->GetName())) {
  1105. if (needRemove) {
  1106. if (newRenameMap[*renamed].empty()) {
  1107. newRenameMap[*renamed].push_back("");
  1108. }
  1109. }
  1110. else {
  1111. if (!newRenameMap[*renamed].empty() && newRenameMap[*renamed][0].empty()) {
  1112. newRenameMap[*renamed].clear(); // Do not remove column because it will be renamed.
  1113. }
  1114. newRenameMap[*renamed].push_back(item->GetName());
  1115. }
  1116. }
  1117. else {
  1118. if (needRemove) {
  1119. newRenameMap[item->GetName()].push_back("");
  1120. }
  1121. }
  1122. }
  1123. for (auto& x : newRenameMap) {
  1124. if (AnyOf(x.second, [](const TStringBuf& value) { return !value.empty(); })) {
  1125. continue;
  1126. }
  1127. x.second.clear();
  1128. }
  1129. return newRenameMap;
  1130. }
  1131. TVector<TEquiJoinParent> CollectEquiJoinOnlyParents(const TCoFlatMapBase& flatMap, const TParentsMap& parents)
  1132. {
  1133. TVector<TEquiJoinParent> result;
  1134. if (!CollectEquiJoinOnlyParents(flatMap.Ref(), nullptr, 2, result, nullptr, parents)) {
  1135. result.clear();
  1136. }
  1137. return result;
  1138. }
  1139. TEquiJoinLinkSettings GetEquiJoinLinkSettings(const TExprNode& linkSettings) {
  1140. TEquiJoinLinkSettings result;
  1141. result.Pos = linkSettings.Pos();
  1142. auto collectHints = [](TSet<TString>& hints, const TExprNode& hintsNode) {
  1143. if (hintsNode.IsAtom()) {
  1144. hints.insert(ToString(hintsNode.Content()));
  1145. } else {
  1146. for (auto h : hintsNode.Children()) {
  1147. YQL_ENSURE(h->IsAtom());
  1148. hints.insert(ToString(h->Content()));
  1149. }
  1150. }
  1151. };
  1152. if (auto left = GetSetting(linkSettings, "left")) {
  1153. collectHints(result.LeftHints, *left->Child(1));
  1154. }
  1155. if (auto right = GetSetting(linkSettings, "right")) {
  1156. collectHints(result.RightHints, *right->Child(1));
  1157. }
  1158. if (auto algo = GetSetting(linkSettings, "join_algo")) {
  1159. YQL_ENSURE(algo->Child(1)->IsAtom());
  1160. result.JoinAlgo = FromString<EJoinAlgoType>(algo->Child(1)->Content());
  1161. }
  1162. result.ForceSortedMerge = HasSetting(linkSettings, "forceSortedMerge");
  1163. if (HasSetting(linkSettings, "forceStreamLookup")) {
  1164. result.JoinAlgo = EJoinAlgoType::StreamLookupJoin;
  1165. }
  1166. if (HasSetting(linkSettings, "compact")) {
  1167. result.Compact = true;
  1168. }
  1169. return result;
  1170. }
  1171. TExprNode::TPtr BuildEquiJoinLinkSettings(const TEquiJoinLinkSettings& linkSettings, TExprContext& ctx) {
  1172. auto builder = [&](const TStringBuf& side) -> TExprNode::TPtr {
  1173. return ctx.Builder(linkSettings.Pos)
  1174. .List()
  1175. .Atom(0, side)
  1176. .List(1)
  1177. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1178. ui32 i = 0;
  1179. for (auto h : (side == "left" ? linkSettings.LeftHints : linkSettings.RightHints)) {
  1180. parent.Atom(i++, h);
  1181. }
  1182. return parent;
  1183. })
  1184. .Seal()
  1185. .Seal()
  1186. .Build();
  1187. };
  1188. TExprNode::TListType settings;
  1189. if (linkSettings.ForceSortedMerge) {
  1190. settings.push_back(ctx.NewList(linkSettings.Pos, { ctx.NewAtom(linkSettings.Pos, "forceSortedMerge", TNodeFlags::Default) }));
  1191. }
  1192. if (linkSettings.LeftHints) {
  1193. settings.push_back(builder("left"));
  1194. }
  1195. if (linkSettings.RightHints) {
  1196. settings.push_back(builder("right"));
  1197. }
  1198. if (linkSettings.Compact) {
  1199. settings.push_back(ctx.NewList(linkSettings.Pos, { ctx.NewAtom(linkSettings.Pos, "compact", TNodeFlags::Default) }));
  1200. }
  1201. return ctx.NewList(linkSettings.Pos, std::move(settings));
  1202. }
  1203. TExprNode::TPtr RemapNonConvertibleMemberForJoin(TPositionHandle pos, const TExprNode::TPtr& memberValue,
  1204. const TTypeAnnotationNode& memberType, const TTypeAnnotationNode& unifiedType, TExprContext& ctx)
  1205. {
  1206. TExprNode::TPtr result = memberValue;
  1207. if (&memberType != &unifiedType) {
  1208. result = ctx.Builder(pos)
  1209. .Callable("StrictCast")
  1210. .Add(0, std::move(result))
  1211. .Add(1, ExpandType(pos, unifiedType, ctx))
  1212. .Seal()
  1213. .Build();
  1214. }
  1215. if (RemoveOptionalType(&unifiedType)->GetKind() != ETypeAnnotationKind::Data) {
  1216. if (unifiedType.HasOptionalOrNull()) {
  1217. result = ctx.Builder(pos)
  1218. .Callable("If")
  1219. .Callable(0, "HasNull")
  1220. .Add(0, result)
  1221. .Seal()
  1222. .Callable(1, "Null")
  1223. .Seal()
  1224. .Callable(2, "StablePickle")
  1225. .Add(0, result)
  1226. .Seal()
  1227. .Seal()
  1228. .Build();
  1229. } else {
  1230. result = ctx.NewCallable(pos, "StablePickle", { result });
  1231. }
  1232. }
  1233. return result;
  1234. }
  1235. TExprNode::TPtr PrepareListForJoin(TExprNode::TPtr list, const TTypeAnnotationNode::TListType& keyTypes, TExprNode::TListType& keys, TExprNode::TListType&& payloads, bool payload, bool optional, bool filter, TExprContext& ctx) {
  1236. const auto pos = list->Pos();
  1237. const auto filterPayloads = [&payloads](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1238. if (payloads.empty())
  1239. parent.Arg(1, "row");
  1240. else
  1241. parent.Callable(1, "FilterMembers")
  1242. .Arg(0, "row")
  1243. .List(1)
  1244. .Add(std::move(payloads))
  1245. .Seal()
  1246. .Seal();
  1247. return parent;
  1248. };
  1249. if (keyTypes.empty() && 1U == keys.size()) {
  1250. return payload ?
  1251. ctx.Builder(pos)
  1252. .Callable("Map")
  1253. .Add(0, std::move(list))
  1254. .Lambda(1)
  1255. .Param("row")
  1256. .List()
  1257. .Add(0, std::move(keys.front()))
  1258. .Do(filterPayloads)
  1259. .Seal()
  1260. .Seal()
  1261. .Seal()
  1262. .Build():
  1263. ctx.Builder(pos)
  1264. .Callable("List")
  1265. .Callable(0, "ListType")
  1266. .Callable(0, "DataType")
  1267. .Atom(0, "Bool", TNodeFlags::Default)
  1268. .Seal()
  1269. .Seal()
  1270. .Seal()
  1271. .Build();
  1272. }
  1273. if (1U == keyTypes.size()) {
  1274. const auto keyType = ctx.MakeType<TOptionalExprType>(keyTypes.front());
  1275. list = payload ? optional ?
  1276. ctx.Builder(pos)
  1277. .Callable("Map")
  1278. .Add(0, std::move(list))
  1279. .Lambda(1)
  1280. .Param("row")
  1281. .List()
  1282. .Callable(0, "StrictCast")
  1283. .Callable(0, "Member")
  1284. .Arg(0, "row")
  1285. .Add(1, std::move(keys.front()))
  1286. .Seal()
  1287. .Add(1, ExpandType(pos, *keyType, ctx))
  1288. .Seal()
  1289. .Do(filterPayloads)
  1290. .Seal()
  1291. .Seal()
  1292. .Seal()
  1293. .Build():
  1294. ctx.Builder(pos)
  1295. .Callable("FlatMap")
  1296. .Add(0, std::move(list))
  1297. .Lambda(1)
  1298. .Param("row")
  1299. .Callable("FlatMap")
  1300. .Callable(0, "StrictCast")
  1301. .Callable(0, "Member")
  1302. .Arg(0, "row")
  1303. .Add(1, std::move(keys.front()))
  1304. .Seal()
  1305. .Add(1, ExpandType(pos, *keyType, ctx))
  1306. .Seal()
  1307. .Lambda(1)
  1308. .Param("key")
  1309. .Callable("Just")
  1310. .List(0)
  1311. .Arg(0, "key")
  1312. .Do(filterPayloads)
  1313. .Seal()
  1314. .Seal()
  1315. .Seal()
  1316. .Seal()
  1317. .Seal()
  1318. .Seal()
  1319. .Build():
  1320. ctx.Builder(pos)
  1321. .Callable(optional ? "Map" : "FlatMap")
  1322. .Add(0, std::move(list))
  1323. .Lambda(1)
  1324. .Param("row")
  1325. .Callable("StrictCast")
  1326. .Callable(0, "Member")
  1327. .Arg(0, "row")
  1328. .Add(1, std::move(keys.front()))
  1329. .Seal()
  1330. .Add(1, ExpandType(pos, *keyType, ctx))
  1331. .Seal()
  1332. .Seal()
  1333. .Seal()
  1334. .Build();
  1335. } else {
  1336. const auto keyType = ctx.MakeType<TOptionalExprType>(ctx.MakeType<TTupleExprType>(keyTypes));
  1337. list = payload ? optional ?
  1338. ctx.Builder(pos)
  1339. .Callable("Map")
  1340. .Add(0, std::move(list))
  1341. .Lambda(1)
  1342. .Param("row")
  1343. .List()
  1344. .Callable(0, "StrictCast")
  1345. .List(0)
  1346. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1347. ui32 pos = 0;
  1348. for (auto& key : keys) {
  1349. parent.Callable(pos++, "Member")
  1350. .Arg(0, "row")
  1351. .Add(1, std::move(key))
  1352. .Seal();
  1353. }
  1354. return parent;
  1355. })
  1356. .Seal()
  1357. .Add(1, ExpandType(pos, *keyType, ctx))
  1358. .Seal()
  1359. .Do(filterPayloads)
  1360. .Seal()
  1361. .Seal()
  1362. .Seal()
  1363. .Build():
  1364. ctx.Builder(pos)
  1365. .Callable("FlatMap")
  1366. .Add(0, std::move(list))
  1367. .Lambda(1)
  1368. .Param("row")
  1369. .Callable("FlatMap")
  1370. .Callable(0, "StrictCast")
  1371. .List(0)
  1372. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1373. ui32 pos = 0;
  1374. for (auto& key : keys) {
  1375. parent.Callable(pos++, "Member")
  1376. .Arg(0, "row")
  1377. .Add(1, std::move(key))
  1378. .Seal();
  1379. }
  1380. return parent;
  1381. })
  1382. .Seal()
  1383. .Add(1, ExpandType(pos, *keyType, ctx))
  1384. .Seal()
  1385. .Lambda(1)
  1386. .Param("key")
  1387. .Callable("Just")
  1388. .List(0)
  1389. .Arg(0, "key")
  1390. .Do(filterPayloads)
  1391. .Seal()
  1392. .Seal()
  1393. .Seal()
  1394. .Seal()
  1395. .Seal()
  1396. .Seal()
  1397. .Build():
  1398. ctx.Builder(pos)
  1399. .Callable(optional ? "Map" : "FlatMap")
  1400. .Add(0, std::move(list))
  1401. .Lambda(1)
  1402. .Param("row")
  1403. .Callable("StrictCast")
  1404. .List(0)
  1405. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1406. ui32 pos = 0;
  1407. for (auto& key : keys) {
  1408. parent.Callable(pos++, "Member")
  1409. .Arg(0, "row")
  1410. .Add(1, std::move(key))
  1411. .Seal();
  1412. }
  1413. return parent;
  1414. })
  1415. .Seal()
  1416. .Add(1, ExpandType(pos, *keyType, ctx))
  1417. .Seal()
  1418. .Seal()
  1419. .Seal()
  1420. .Build();
  1421. }
  1422. if (optional && filter) {
  1423. list = payload ?
  1424. ctx.Builder(pos)
  1425. .Callable("Filter")
  1426. .Add(0, std::move(list))
  1427. .Lambda(1)
  1428. .Param("row")
  1429. .Callable(0, "Exists")
  1430. .Callable(0, "Nth")
  1431. .Arg(0, "row")
  1432. .Atom(1, 0U)
  1433. .Seal()
  1434. .Seal()
  1435. .Seal()
  1436. .Seal()
  1437. .Build():
  1438. ctx.Builder(pos)
  1439. .Callable("Filter")
  1440. .Add(0, std::move(list))
  1441. .Lambda(1)
  1442. .Param("row")
  1443. .Callable(0, "Exists")
  1444. .Arg(0, "row")
  1445. .Seal()
  1446. .Seal()
  1447. .Seal()
  1448. .Build();
  1449. }
  1450. return list;
  1451. }
  1452. template <bool Squeeze>
  1453. TExprNode::TPtr MakeDictForJoin(TExprNode::TPtr&& list, bool payload, bool multi, TExprContext& ctx) {
  1454. return payload ?
  1455. ctx.Builder(list->Pos())
  1456. .Callable(Squeeze ? "SqueezeToDict" : "ToDict")
  1457. .Add(0, std::move(list))
  1458. .Lambda(1)
  1459. .Param("row")
  1460. .Callable("Nth")
  1461. .Arg(0, "row")
  1462. .Atom(1, 0U)
  1463. .Seal()
  1464. .Seal()
  1465. .Lambda(2)
  1466. .Param("row")
  1467. .Callable("Nth")
  1468. .Arg(0, "row")
  1469. .Atom(1, 1U)
  1470. .Seal()
  1471. .Seal()
  1472. .List(3)
  1473. .Atom(0, multi ? "Many" : "One", TNodeFlags::Default)
  1474. .Atom(1, "Hashed", TNodeFlags::Default)
  1475. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1476. if constexpr (Squeeze)
  1477. parent.Atom(2, "Compact", TNodeFlags::Default);
  1478. return parent;
  1479. })
  1480. .Seal()
  1481. .Seal()
  1482. .Build():
  1483. ctx.Builder(list->Pos())
  1484. .Callable(Squeeze ? "SqueezeToDict" : "ToDict")
  1485. .Add(0, std::move(list))
  1486. .Lambda(1)
  1487. .Param("row")
  1488. .Arg("row")
  1489. .Seal()
  1490. .Lambda(2)
  1491. .Param("stub")
  1492. .Callable("Void").Seal()
  1493. .Seal()
  1494. .List(3)
  1495. .Atom(0, multi ? "Many" : "One", TNodeFlags::Default)
  1496. .Atom(1, "Hashed", TNodeFlags::Default)
  1497. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1498. if constexpr (Squeeze)
  1499. parent.Atom(2, "Compact", TNodeFlags::Default);
  1500. return parent;
  1501. })
  1502. .Seal()
  1503. .Seal()
  1504. .Build();
  1505. }
  1506. template TExprNode::TPtr MakeDictForJoin<true>(TExprNode::TPtr&& list, bool payload, bool multi, TExprContext& ctx);
  1507. template TExprNode::TPtr MakeDictForJoin<false>(TExprNode::TPtr&& list, bool payload, bool multi, TExprContext& ctx);
  1508. TExprNode::TPtr MakeCrossJoin(TPositionHandle pos, TExprNode::TPtr left, TExprNode::TPtr right, TExprContext& ctx) {
  1509. return ctx.Builder(pos)
  1510. .List()
  1511. .Atom(0, "Cross")
  1512. .Add(1, left)
  1513. .Add(2, right)
  1514. .List(3)
  1515. .Seal()
  1516. .List(4)
  1517. .Seal()
  1518. .List(5)
  1519. .Seal()
  1520. .Seal()
  1521. .Build();
  1522. }
  1523. TExprNode::TPtr PreparePredicate(TExprNode::TPtr predicate, TExprContext& ctx) {
  1524. auto originalPredicate = predicate;
  1525. bool isPg = false;
  1526. if (predicate->IsCallable("ToPg")) {
  1527. isPg = true;
  1528. predicate = predicate->ChildPtr(0);
  1529. }
  1530. if (!predicate->IsCallable("Or")) {
  1531. return originalPredicate;
  1532. }
  1533. if (predicate->ChildrenSize() == 1) {
  1534. return originalPredicate;
  1535. }
  1536. // try to extract common And parts from Or
  1537. TVector<TExprNode::TListType> andParts;
  1538. for (ui32 i = 0; i < predicate->ChildrenSize(); ++i) {
  1539. TExprNode::TListType res;
  1540. bool isPg;
  1541. GatherAndTerms(predicate->ChildPtr(i), res, isPg, ctx);
  1542. YQL_ENSURE(!isPg); // direct child for Or
  1543. andParts.emplace_back(std::move(res));
  1544. }
  1545. THashMap<const TExprNode*, ui32> commonParts;
  1546. for (ui32 j = 0; j < andParts[0].size(); ++j) {
  1547. commonParts[andParts[0][j].Get()] = j;
  1548. }
  1549. for (ui32 i = 1; i < andParts.size(); ++i) {
  1550. THashSet<const TExprNode*> found;
  1551. for (ui32 j = 0; j < andParts[i].size(); ++j) {
  1552. found.insert(andParts[i][j].Get());
  1553. }
  1554. // remove
  1555. for (auto it = commonParts.begin(); it != commonParts.end();) {
  1556. if (found.contains(it->first)) {
  1557. ++it;
  1558. } else {
  1559. commonParts.erase(it++);
  1560. }
  1561. }
  1562. }
  1563. if (commonParts.size() == 0) {
  1564. return originalPredicate;
  1565. }
  1566. // rebuild commonParts in order of original And
  1567. TVector<ui32> idx;
  1568. for (const auto& x : commonParts) {
  1569. idx.push_back(x.second);
  1570. }
  1571. Sort(idx);
  1572. TExprNode::TListType andArgs;
  1573. for (ui32 i : idx) {
  1574. andArgs.push_back(andParts[0][i]);
  1575. }
  1576. TExprNode::TListType orArgs;
  1577. for (ui32 i = 0; i < andParts.size(); ++i) {
  1578. TExprNode::TListType restAndArgs;
  1579. for (ui32 j = 0; j < andParts[i].size(); ++j) {
  1580. if (commonParts.contains(andParts[i][j].Get())) {
  1581. continue;
  1582. }
  1583. restAndArgs.push_back(andParts[i][j]);
  1584. }
  1585. if (restAndArgs.size() >= 1) {
  1586. orArgs.push_back(ctx.NewCallable(predicate->Pos(), "And", std::move(restAndArgs)));
  1587. }
  1588. }
  1589. if (orArgs.size() >= 1) {
  1590. andArgs.push_back(ctx.NewCallable(predicate->Pos(), "Or", std::move(orArgs)));
  1591. }
  1592. auto ret = ctx.NewCallable(predicate->Pos(), "And", std::move(andArgs));
  1593. if (isPg) {
  1594. ret = ctx.NewCallable(predicate->Pos(), "ToPg", { ret });
  1595. }
  1596. return ret;
  1597. }
  1598. void GatherAndTermsImpl(const TExprNode::TPtr& predicate, TExprNode::TListType& andTerms, TExprContext& ctx) {
  1599. auto pred = PreparePredicate(predicate, ctx);
  1600. if (!pred->IsCallable("And")) {
  1601. andTerms.emplace_back(pred);
  1602. return;
  1603. }
  1604. for (ui32 i = 0; i < pred->ChildrenSize(); ++i) {
  1605. GatherAndTermsImpl(pred->ChildPtr(i), andTerms, ctx);
  1606. }
  1607. }
  1608. void GatherAndTerms(const TExprNode::TPtr& predicate, TExprNode::TListType& andTerms, bool& isPg, TExprContext& ctx) {
  1609. isPg = false;
  1610. if (predicate->IsCallable("ToPg")) {
  1611. isPg = true;
  1612. GatherAndTermsImpl(predicate->HeadPtr(), andTerms, ctx);
  1613. } else {
  1614. GatherAndTermsImpl(predicate, andTerms, ctx);
  1615. }
  1616. }
  1617. TExprNode::TPtr FuseAndTerms(TPositionHandle position, const TExprNode::TListType& andTerms, const TExprNode::TPtr& exclude, bool isPg, TExprContext& ctx) {
  1618. TExprNode::TPtr prevAndNode = nullptr;
  1619. TNodeSet added;
  1620. for (const auto& otherAndTerm : andTerms) {
  1621. if (otherAndTerm == exclude) {
  1622. continue;
  1623. }
  1624. if (!added.insert(otherAndTerm.Get()).second) {
  1625. continue;
  1626. }
  1627. if (!prevAndNode) {
  1628. prevAndNode = otherAndTerm;
  1629. } else {
  1630. prevAndNode = ctx.NewCallable(position, "And", { prevAndNode, otherAndTerm });
  1631. }
  1632. }
  1633. if (isPg) {
  1634. return ctx.NewCallable(position, "ToPg", { prevAndNode });
  1635. } else {
  1636. return prevAndNode;
  1637. }
  1638. }
  1639. bool IsEquality(TExprNode::TPtr predicate, TExprNode::TPtr& left, TExprNode::TPtr& right) {
  1640. if (predicate->IsCallable("Coalesce")) {
  1641. if (predicate->Tail().IsCallable("Bool") && IsFalse(predicate->Tail().Head().Content())) {
  1642. predicate = predicate->HeadPtr();
  1643. } else {
  1644. return false;
  1645. }
  1646. }
  1647. if (predicate->IsCallable("FromPg")) {
  1648. predicate = predicate->HeadPtr();
  1649. }
  1650. if (predicate->IsCallable("==")) {
  1651. left = predicate->ChildPtr(0);
  1652. right = predicate->ChildPtr(1);
  1653. return true;
  1654. }
  1655. if (predicate->IsCallable("PgResolvedOp") &&
  1656. (predicate->Head().Content() == "=")) {
  1657. left = predicate->ChildPtr(2);
  1658. right = predicate->ChildPtr(3);
  1659. return true;
  1660. }
  1661. return false;
  1662. }
  1663. void GatherJoinInputs(const TExprNode::TPtr& expr, const TExprNode& row,
  1664. const TParentsMap& parentsMap, const THashMap<TString, TString>& backRenameMap,
  1665. const TJoinLabels& labels, TSet<ui32>& inputs, TSet<TStringBuf>& usedFields) {
  1666. usedFields.clear();
  1667. if (!HaveFieldsSubset(expr, row, usedFields, parentsMap, false)) {
  1668. const auto inputStructType = RemoveOptionalType(row.GetTypeAnn())->Cast<TStructExprType>();
  1669. for (const auto& i : inputStructType->GetItems()) {
  1670. usedFields.insert(i->GetName());
  1671. }
  1672. }
  1673. for (auto x : usedFields) {
  1674. // rename used fields
  1675. if (auto renamed = backRenameMap.FindPtr(x)) {
  1676. x = *renamed;
  1677. }
  1678. TStringBuf part1;
  1679. TStringBuf part2;
  1680. SplitTableName(x, part1, part2);
  1681. inputs.insert(*labels.FindInputIndex(part1));
  1682. if (inputs.size() == labels.Inputs.size()) {
  1683. break;
  1684. }
  1685. }
  1686. }
  1687. } // namespace NYql