yql_join.cpp 72 KB

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