yql_join.cpp 73 KB

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