select.cpp 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371
  1. #include "sql.h"
  2. #include "node.h"
  3. #include "context.h"
  4. #include <yql/essentials/utils/yql_panic.h>
  5. #include <library/cpp/charset/ci_string.h>
  6. using namespace NYql;
  7. namespace NSQLTranslationV0 {
  8. class TSubqueryNode: public INode {
  9. public:
  10. TSubqueryNode(TSourcePtr&& source, const TString& alias, bool inSubquery, int ensureTupleSize)
  11. : INode(source->GetPos())
  12. , Source(std::move(source))
  13. , Alias(alias)
  14. , InSubquery(inSubquery)
  15. , EnsureTupleSize(ensureTupleSize)
  16. {
  17. YQL_ENSURE(!Alias.empty());
  18. }
  19. ISource* GetSource() override {
  20. return Source.Get();
  21. }
  22. bool DoInit(TContext& ctx, ISource* src) override {
  23. YQL_ENSURE(!src, "Source not expected for subquery node");
  24. Source->UseAsInner();
  25. if (!Source->Init(ctx, nullptr)) {
  26. return false;
  27. }
  28. TTableList tableList;
  29. Source->GetInputTables(tableList);
  30. auto tables = BuildInputTables(Pos, tableList, InSubquery);
  31. if (!tables->Init(ctx, Source.Get())) {
  32. return false;
  33. }
  34. auto source = Source->Build(ctx);
  35. if (!source) {
  36. return false;
  37. }
  38. if (EnsureTupleSize != -1) {
  39. source = Y("EnsureTupleSize", source, Q(ToString(EnsureTupleSize)));
  40. }
  41. Node = Y("let", Alias, Y("block", Q(L(tables, Y("return", Q(Y("world", source)))))));
  42. IsUsed = true;
  43. return true;
  44. }
  45. void DoUpdateState() const override {
  46. State.Set(ENodeState::Const, true);
  47. }
  48. bool UsedSubquery() const override {
  49. return IsUsed;
  50. }
  51. TAstNode* Translate(TContext& ctx) const override {
  52. Y_DEBUG_ABORT_UNLESS(Node);
  53. return Node->Translate(ctx);
  54. }
  55. const TString* SubqueryAlias() const override {
  56. return &Alias;
  57. }
  58. TPtr DoClone() const final {
  59. return {};
  60. }
  61. protected:
  62. TSourcePtr Source;
  63. TNodePtr Node;
  64. const TString Alias;
  65. const bool InSubquery;
  66. const int EnsureTupleSize;
  67. bool IsUsed = false;
  68. };
  69. TNodePtr BuildSubquery(TSourcePtr source, const TString& alias, bool inSubquery, int ensureTupleSize) {
  70. return new TSubqueryNode(std::move(source), alias, inSubquery, ensureTupleSize);
  71. }
  72. class TSourceNode: public INode {
  73. public:
  74. TSourceNode(TPosition pos, TSourcePtr&& source, bool checkExist)
  75. : INode(pos)
  76. , Source(std::move(source))
  77. , CheckExist(checkExist)
  78. {}
  79. ISource* GetSource() override {
  80. return Source.Get();
  81. }
  82. bool DoInit(TContext& ctx, ISource* src) override {
  83. if (AsInner) {
  84. Source->UseAsInner();
  85. }
  86. if (!Source->Init(ctx, src)) {
  87. return false;
  88. }
  89. Node = Source->Build(ctx);
  90. if (!Node) {
  91. return false;
  92. }
  93. if (src) {
  94. if (IsSubquery()) {
  95. /// should be not used?
  96. auto columnsPtr = Source->GetColumns();
  97. if (!columnsPtr || columnsPtr->All || columnsPtr->QualifiedAll || columnsPtr->List.size() != 1) {
  98. ctx.Error(Pos) << "Source used in expression should contain one concrete column";
  99. return false;
  100. }
  101. Node = Y("Member", Y("SqlAccess", Q("dict"), Y("Take", Node, Y("Uint64", Q("1"))), Y("Uint64", Q("0"))), Q(columnsPtr->List.front()));
  102. }
  103. src->AddDependentSource(Source.Get());
  104. }
  105. return true;
  106. }
  107. bool IsSubquery() const {
  108. return !AsInner && Source->IsSelect() && !CheckExist;
  109. }
  110. void DoUpdateState() const override {
  111. State.Set(ENodeState::Const, IsSubquery());
  112. }
  113. TAstNode* Translate(TContext& ctx) const override {
  114. Y_DEBUG_ABORT_UNLESS(Node);
  115. return Node->Translate(ctx);
  116. }
  117. TPtr DoClone() const final {
  118. return new TSourceNode(Pos, Source->CloneSource(), CheckExist);
  119. }
  120. protected:
  121. TSourcePtr Source;
  122. TNodePtr Node;
  123. bool CheckExist;
  124. };
  125. TNodePtr BuildSourceNode(TPosition pos, TSourcePtr source, bool checkExist) {
  126. return new TSourceNode(pos, std::move(source), checkExist);
  127. }
  128. class TFakeSource: public ISource {
  129. public:
  130. TFakeSource(TPosition pos)
  131. : ISource(pos)
  132. {}
  133. bool IsFake() const override {
  134. return true;
  135. }
  136. bool AddFilter(TContext& ctx, TNodePtr filter) override {
  137. Y_UNUSED(filter);
  138. ctx.Error(Pos) << "Source does not allow filtering";
  139. return false;
  140. }
  141. TNodePtr Build(TContext& ctx) override {
  142. Y_UNUSED(ctx);
  143. return Y("AsList", Y("Uint32", Q("0")));
  144. }
  145. bool AddGroupKey(TContext& ctx, const TString& column) override {
  146. Y_UNUSED(column);
  147. ctx.Error(Pos) << "Source does not allow grouping";
  148. return false;
  149. }
  150. bool AddAggregation(TContext& ctx, TAggregationPtr aggr) override {
  151. Y_UNUSED(aggr);
  152. ctx.Error(Pos) << "Source does not allow aggregation";
  153. return false;
  154. }
  155. bool IsGroupByColumn(const TString& column) const override {
  156. Y_UNUSED(column);
  157. return false;
  158. }
  159. TNodePtr BuildFilter(TContext& ctx, const TString& label, const TNodePtr& groundNode) override {
  160. Y_UNUSED(ctx);
  161. Y_UNUSED(label);
  162. Y_UNUSED(groundNode);
  163. return nullptr;
  164. }
  165. TNodePtr BuildAggregation(const TString& label) override {
  166. Y_UNUSED(label);
  167. return nullptr;
  168. }
  169. TPtr DoClone() const final {
  170. return new TFakeSource(Pos);
  171. }
  172. };
  173. TSourcePtr BuildFakeSource(TPosition pos) {
  174. return new TFakeSource(pos);
  175. }
  176. class TNodeSource: public ISource {
  177. public:
  178. TNodeSource(TPosition pos, const TNodePtr& node)
  179. : ISource(pos)
  180. , Node(node)
  181. {
  182. YQL_ENSURE(Node);
  183. FakeSource = BuildFakeSource(pos);
  184. }
  185. void AllColumns() final {
  186. UseAllColumns = true;
  187. }
  188. TMaybe<bool> AddColumn(TContext& ctx, TColumnNode& column) final {
  189. Y_UNUSED(ctx);
  190. if (UseAllColumns) {
  191. return true;
  192. }
  193. if (column.IsAsterisk()) {
  194. AllColumns();
  195. } else {
  196. Columns.push_back(*column.GetColumnName());
  197. }
  198. return true;
  199. }
  200. TNodePtr Build(TContext& ctx) final {
  201. ctx.PushBlockShortcuts();
  202. if (!Node->Init(ctx, FakeSource.Get())) {
  203. return {};
  204. }
  205. Node = ctx.GroundBlockShortcutsForExpr(Node);
  206. auto nodeAst = AstNode(Node);
  207. if (UseAllColumns) {
  208. return nodeAst;
  209. } else {
  210. auto members = Y();
  211. for (auto& column : Columns) {
  212. members = L(members, BuildQuotedAtom(Pos, column));
  213. }
  214. return Y(ctx.UseUnordered(*this) ? "OrderedMap" : "Map", nodeAst, BuildLambda(Pos, Y("row"), Y("SelectMembers", "row", Q(members))));
  215. }
  216. }
  217. TPtr DoClone() const final {
  218. return new TNodeSource(Pos, Node);
  219. }
  220. private:
  221. TNodePtr Node;
  222. TSourcePtr FakeSource;
  223. TVector<TString> Columns;
  224. bool UseAllColumns = false;
  225. };
  226. TSourcePtr BuildNodeSource(TPosition pos, const TNodePtr& node) {
  227. return new TNodeSource(pos, node);
  228. }
  229. class IProxySource: public ISource {
  230. protected:
  231. IProxySource(TPosition pos, ISource* src)
  232. : ISource(pos)
  233. , Source(src)
  234. {}
  235. void AllColumns() override {
  236. Y_DEBUG_ABORT_UNLESS(Source);
  237. return Source->AllColumns();
  238. }
  239. const TColumns* GetColumns() const override {
  240. Y_DEBUG_ABORT_UNLESS(Source);
  241. return Source->GetColumns();
  242. }
  243. void GetInputTables(TTableList& tableList) const override {
  244. Source->GetInputTables(tableList);
  245. ISource::GetInputTables(tableList);
  246. }
  247. TMaybe<bool> AddColumn(TContext& ctx, TColumnNode& column) override {
  248. Y_DEBUG_ABORT_UNLESS(Source);
  249. const TString label(Source->GetLabel());
  250. Source->SetLabel(Label);
  251. const auto ret = Source->AddColumn(ctx, column);
  252. Source->SetLabel(label);
  253. return ret;
  254. }
  255. bool ShouldUseSourceAsColumn(const TString& source) override {
  256. return Source->ShouldUseSourceAsColumn(source);
  257. }
  258. bool IsStream() const override {
  259. Y_DEBUG_ABORT_UNLESS(Source);
  260. return Source->IsStream();
  261. }
  262. bool IsOrdered() const override {
  263. Y_DEBUG_ABORT_UNLESS(Source);
  264. return Source->IsOrdered();
  265. }
  266. TWriteSettings GetWriteSettings() const override {
  267. Y_DEBUG_ABORT_UNLESS(Source);
  268. return Source->GetWriteSettings();
  269. }
  270. protected:
  271. void SetSource(ISource* source) {
  272. Source = source;
  273. }
  274. ISource* Source;
  275. };
  276. class IRealSource: public ISource {
  277. protected:
  278. IRealSource(TPosition pos)
  279. : ISource(pos)
  280. {
  281. }
  282. void AllColumns() override {
  283. Columns.SetAll();
  284. }
  285. const TColumns* GetColumns() const override {
  286. return &Columns;
  287. }
  288. TMaybe<bool> AddColumn(TContext& ctx, TColumnNode& column) override {
  289. auto& label = *column.GetSourceName();
  290. if (!label.empty() && label != GetLabel()) {
  291. if (column.IsReliable()) {
  292. ctx.Error(column.GetPos()) << "Unknown correlation name: " << label;
  293. }
  294. return {};
  295. }
  296. if (column.IsAsterisk()) {
  297. return true;
  298. }
  299. const auto* name = column.GetColumnName();
  300. if (name && !Columns.IsColumnPossible(ctx, *name) && !IsAlias(EExprSeat::GroupBy, *name)) {
  301. if (column.IsReliable()) {
  302. TStringBuilder sb;
  303. sb << "Column " << *name << " is not in source column set";
  304. if (const auto mistype = FindColumnMistype(*name)) {
  305. sb << ". Did you mean " << mistype.GetRef() << "?";
  306. }
  307. ctx.Error(column.GetPos()) << sb;
  308. }
  309. return {};
  310. }
  311. return true;
  312. }
  313. TMaybe<TString> FindColumnMistype(const TString& name) const override {
  314. auto result = FindMistypeIn(Columns.Real, name);
  315. if (!result) {
  316. auto result = FindMistypeIn(Columns.Artificial, name);
  317. }
  318. return result ? result : ISource::FindColumnMistype(name);
  319. }
  320. protected:
  321. TColumns Columns;
  322. };
  323. class TMuxSource: public ISource {
  324. public:
  325. TMuxSource(TPosition pos, TVector<TSourcePtr>&& sources)
  326. : ISource(pos)
  327. , Sources(std::move(sources))
  328. {
  329. YQL_ENSURE(Sources.size() > 1);
  330. }
  331. void AllColumns() final {
  332. for (auto& source: Sources) {
  333. source->AllColumns();
  334. }
  335. }
  336. const TColumns* GetColumns() const final {
  337. // Columns are equal in all sources. Return from the first one
  338. return Sources.front()->GetColumns();
  339. }
  340. void GetInputTables(TTableList& tableList) const final {
  341. for (auto& source: Sources) {
  342. source->GetInputTables(tableList);
  343. }
  344. ISource::GetInputTables(tableList);
  345. }
  346. bool IsStream() const final {
  347. return AnyOf(Sources, [] (const TSourcePtr& s) { return s->IsStream(); });
  348. }
  349. bool DoInit(TContext& ctx, ISource* src) final {
  350. for (auto& source: Sources) {
  351. if (AsInner) {
  352. source->UseAsInner();
  353. }
  354. ctx.PushBlockShortcuts();
  355. if (src) {
  356. src->AddDependentSource(source.Get());
  357. }
  358. if (!source->Init(ctx, src)) {
  359. return false;
  360. }
  361. if (!source->InitFilters(ctx)) {
  362. return false;
  363. }
  364. FiltersGrounds.push_back(ctx.GroundBlockShortcuts(Pos));
  365. }
  366. return true;
  367. }
  368. TMaybe<bool> AddColumn(TContext& ctx, TColumnNode& column) final {
  369. for (auto& source: Sources) {
  370. if (!source->AddColumn(ctx, column)) {
  371. return {};
  372. }
  373. }
  374. return true;
  375. }
  376. TNodePtr Build(TContext& ctx) final {
  377. TNodePtr block;
  378. auto muxArgs = Y();
  379. for (size_t i = 0; i < Sources.size(); ++i) {
  380. auto& source = Sources[i];
  381. auto input = source->Build(ctx);
  382. auto ref = ctx.MakeName("src");
  383. muxArgs->Add(ref);
  384. if (block) {
  385. block = L(block, Y("let", ref, input));
  386. } else {
  387. block = Y(Y("let", ref, input));
  388. }
  389. auto filter = source->BuildFilter(ctx, ref, FiltersGrounds[i]);
  390. if (filter) {
  391. block = L(block, Y("let", ref, filter));
  392. }
  393. }
  394. return GroundWithExpr(block, Y("Mux", Q(muxArgs)));
  395. }
  396. bool AddFilter(TContext& ctx, TNodePtr filter) final {
  397. Y_UNUSED(filter);
  398. ctx.Error() << "Filter is not allowed for multiple sources";
  399. return false;
  400. }
  401. TPtr DoClone() const final {
  402. // Don't clone FiltersGrounds container because it will be initialized in DoInit of cloned object
  403. return new TMuxSource(Pos, CloneContainer(Sources));
  404. }
  405. protected:
  406. TVector<TSourcePtr> Sources;
  407. TVector<TNodePtr> FiltersGrounds;
  408. };
  409. TSourcePtr BuildMuxSource(TPosition pos, TVector<TSourcePtr>&& sources) {
  410. return new TMuxSource(pos, std::move(sources));
  411. }
  412. class TSubqueryRefNode: public IRealSource {
  413. public:
  414. TSubqueryRefNode(const TNodePtr& subquery, const TString& alias, int tupleIndex)
  415. : IRealSource(subquery->GetPos())
  416. , Subquery(subquery)
  417. , Alias(alias)
  418. , TupleIndex(tupleIndex)
  419. {
  420. YQL_ENSURE(subquery->GetSource());
  421. }
  422. ISource* GetSource() override {
  423. return this;
  424. }
  425. bool DoInit(TContext& ctx, ISource* src) override {
  426. // independent subquery should not connect source
  427. Subquery->UseAsInner();
  428. if (!Subquery->Init(ctx, nullptr)) {
  429. return false;
  430. }
  431. Columns = *Subquery->GetSource()->GetColumns();
  432. Node = BuildAtom(Pos, Alias, TNodeFlags::Default);
  433. if (TupleIndex != -1) {
  434. Node = Y("Nth", Node, Q(ToString(TupleIndex)));
  435. }
  436. if (!Node->Init(ctx, src)) {
  437. return false;
  438. }
  439. if (src && Subquery->GetSource()->IsSelect()) {
  440. auto columnsPtr = &Columns;
  441. if (!columnsPtr || columnsPtr->All || columnsPtr->QualifiedAll || columnsPtr->List.size() != 1) {
  442. ctx.Error(Pos) << "Source used in expression should contain one concrete column";
  443. return false;
  444. }
  445. Node = Y("Member", Y("SqlAccess", Q("dict"), Y("Take", Node, Y("Uint64", Q("1"))), Y("Uint64", Q("0"))), Q(columnsPtr->List.front()));
  446. }
  447. return true;
  448. }
  449. TNodePtr Build(TContext& ctx) override {
  450. Y_UNUSED(ctx);
  451. return Node;
  452. }
  453. bool IsStream() const override {
  454. return Subquery->GetSource()->IsStream();
  455. }
  456. void DoUpdateState() const override {
  457. State.Set(ENodeState::Const, true);
  458. }
  459. TAstNode* Translate(TContext& ctx) const override {
  460. Y_DEBUG_ABORT_UNLESS(Node);
  461. return Node->Translate(ctx);
  462. }
  463. TPtr DoClone() const final {
  464. return new TSubqueryRefNode(Subquery, Alias, TupleIndex);
  465. }
  466. protected:
  467. TNodePtr Subquery;
  468. const TString Alias;
  469. const int TupleIndex;
  470. TNodePtr Node;
  471. };
  472. TNodePtr BuildSubqueryRef(TNodePtr subquery, const TString& alias, int tupleIndex) {
  473. return new TSubqueryRefNode(std::move(subquery), alias, tupleIndex);
  474. }
  475. class TTableSource: public IRealSource {
  476. public:
  477. TTableSource(TPosition pos, const TTableRef& table, bool stream, const TString& label)
  478. : IRealSource(pos)
  479. , Table(table)
  480. , Stream(stream)
  481. {
  482. SetLabel(label.empty() ? Table.ShortName() : label);
  483. }
  484. void GetInputTables(TTableList& tableList) const override {
  485. tableList.push_back(Table);
  486. ISource::GetInputTables(tableList);
  487. }
  488. bool ShouldUseSourceAsColumn(const TString& source) override {
  489. return source && source != GetLabel();
  490. }
  491. TMaybe<bool> AddColumn(TContext& ctx, TColumnNode& column) override {
  492. Columns.Add(column.GetColumnName(), column.GetCountHint(), column.IsArtificial(), column.IsReliable());
  493. if (!IRealSource::AddColumn(ctx, column)) {
  494. return {};
  495. }
  496. return false;
  497. }
  498. bool SetSamplingOptions(
  499. TContext& ctx,
  500. TPosition pos,
  501. ESampleMode mode,
  502. TNodePtr samplingRate,
  503. TNodePtr samplingSeed) override {
  504. Y_UNUSED(pos);
  505. TString modeName;
  506. if (!samplingSeed) {
  507. samplingSeed = Y("Int32", Q("0"));
  508. }
  509. switch (mode) {
  510. case ESampleMode::Auto:
  511. modeName = "bernoulli";
  512. samplingRate = Y("*", samplingRate, Y("Double", Q("100")));
  513. break;
  514. case ESampleMode::Bernoulli:
  515. modeName = "bernoulli";
  516. break;
  517. case ESampleMode::System:
  518. modeName = "system";
  519. break;
  520. }
  521. samplingRate = Y("Ensure", samplingRate, Y(">", samplingRate, Y("Double", Q("0"))), Y("String", Q("Expected sampling rate to be positive")));
  522. samplingRate = Y("Ensure", samplingRate, Y("<=", samplingRate, Y("Double", Q("100"))), Y("String", Q("Sampling rate is over 100%")));
  523. auto sampleSettings = Q(Y(Q(modeName), Y("EvaluateAtom", Y("ToString", samplingRate)), Y("EvaluateAtom", Y("ToString", samplingSeed))));
  524. auto sampleOption = Q(Y(Q("sample"), sampleSettings));
  525. if (Table.Options) {
  526. if (!Table.Options->Init(ctx, this)) {
  527. return false;
  528. }
  529. Table.Options = L(Table.Options, sampleOption);
  530. } else {
  531. Table.Options = Y(sampleOption);
  532. }
  533. return true;
  534. }
  535. TNodePtr Build(TContext& ctx) override {
  536. if (!Table.Keys->Init(ctx, nullptr)) {
  537. return nullptr;
  538. }
  539. return AstNode(Table.RefName);
  540. }
  541. bool IsStream() const override {
  542. return Stream;
  543. }
  544. TPtr DoClone() const final {
  545. return new TTableSource(Pos, Table, Stream, GetLabel());
  546. }
  547. bool IsTableSource() const override {
  548. return true;
  549. }
  550. protected:
  551. TTableRef Table;
  552. const bool Stream;
  553. };
  554. TSourcePtr BuildTableSource(TPosition pos, const TTableRef& table, bool stream, const TString& label) {
  555. return new TTableSource(pos, table, stream, label);
  556. }
  557. class TInnerSource: public IProxySource {
  558. public:
  559. TInnerSource(TPosition pos, TNodePtr node, const TString& label)
  560. : IProxySource(pos, nullptr)
  561. , Node(node)
  562. {
  563. SetLabel(label);
  564. }
  565. bool ShouldUseSourceAsColumn(const TString& source) override {
  566. return source && source != GetLabel();
  567. }
  568. TMaybe<bool> AddColumn(TContext& ctx, TColumnNode& column) override {
  569. if (const TString* columnName = column.GetColumnName()) {
  570. if (columnName && IsExprAlias(*columnName)) {
  571. return true;
  572. }
  573. }
  574. return IProxySource::AddColumn(ctx, column);
  575. }
  576. bool DoInit(TContext& ctx, ISource* src) override {
  577. auto source = Node->GetSource();
  578. if (!source) {
  579. NewSource = TryMakeSourceFromExpression(ctx, Node);
  580. source = NewSource.Get();
  581. }
  582. if (!source) {
  583. ctx.Error(Pos) << "Invalid inner source node";
  584. return false;
  585. }
  586. source->SetLabel(Label);
  587. if (!NewSource) {
  588. Node->UseAsInner();
  589. if (!Node->Init(ctx, src)) {
  590. return false;
  591. }
  592. }
  593. SetSource(source);
  594. if (NewSource && !NewSource->Init(ctx, src)) {
  595. return false;
  596. }
  597. return ISource::DoInit(ctx, source);
  598. }
  599. TNodePtr Build(TContext& ctx) override {
  600. Y_UNUSED(ctx);
  601. return NewSource ? NewSource->Build(ctx) : Node;
  602. }
  603. TPtr DoClone() const final {
  604. return new TInnerSource(Pos, SafeClone(Node), GetLabel());
  605. }
  606. protected:
  607. TNodePtr Node;
  608. TSourcePtr NewSource;
  609. };
  610. TSourcePtr BuildInnerSource(TPosition pos, TNodePtr node, const TString& label) {
  611. return new TInnerSource(pos, node, label);
  612. }
  613. /// \todo move to reduce.cpp? or mapreduce.cpp?
  614. class TReduceSource: public IRealSource {
  615. public:
  616. TReduceSource(TPosition pos,
  617. ReduceMode mode,
  618. TSourcePtr source,
  619. TVector<TSortSpecificationPtr>&& orderBy,
  620. TVector<TNodePtr>&& keys,
  621. TVector<TNodePtr>&& args,
  622. TNodePtr udf,
  623. TNodePtr having,
  624. const TWriteSettings& settings)
  625. : IRealSource(pos)
  626. , Mode(mode)
  627. , Source(std::move(source))
  628. , OrderBy(std::move(orderBy))
  629. , Keys(std::move(keys))
  630. , Args(std::move(args))
  631. , Udf(udf)
  632. , Having(having)
  633. , Settings(settings)
  634. {
  635. YQL_ENSURE(!Keys.empty());
  636. YQL_ENSURE(Source);
  637. }
  638. void GetInputTables(TTableList& tableList) const override {
  639. Source->GetInputTables(tableList);
  640. ISource::GetInputTables(tableList);
  641. }
  642. bool DoInit(TContext& ctx, ISource* src) final {
  643. if (AsInner) {
  644. Source->UseAsInner();
  645. }
  646. ctx.PushBlockShortcuts();
  647. YQL_ENSURE(!src);
  648. if (!Source->Init(ctx, src)) {
  649. return false;
  650. }
  651. if (!Source->InitFilters(ctx)) {
  652. return false;
  653. }
  654. FiltersGround = ctx.GroundBlockShortcuts(Pos);
  655. src = Source.Get();
  656. for (auto& key: Keys) {
  657. if (!key->Init(ctx, src)) {
  658. return false;
  659. }
  660. auto keyNamePtr = key->GetColumnName();
  661. YQL_ENSURE(keyNamePtr);
  662. if (!src->AddGroupKey(ctx, *keyNamePtr)) {
  663. return false;
  664. }
  665. }
  666. ctx.PushBlockShortcuts();
  667. if (Having && !Having->Init(ctx, nullptr)) {
  668. return false;
  669. }
  670. HavingGround = ctx.GroundBlockShortcuts(Pos);
  671. /// SIN: verify reduce one argument
  672. if (Args.size() != 1) {
  673. ctx.Error(Pos) << "REDUCE requires exactly one UDF argument";
  674. return false;
  675. }
  676. ctx.PushBlockShortcuts();
  677. if (!Args[0]->Init(ctx, src)) {
  678. return false;
  679. }
  680. ExprGround = ctx.GroundBlockShortcuts(Pos);
  681. ctx.PushBlockShortcuts();
  682. for (auto orderSpec: OrderBy) {
  683. if (!orderSpec->OrderExpr->Init(ctx, src)) {
  684. return false;
  685. }
  686. }
  687. OrderByGround = ctx.GroundBlockShortcuts(Pos);
  688. if (!Udf->Init(ctx, src)) {
  689. return false;
  690. }
  691. if (Udf->GetLabel().empty()) {
  692. Columns.SetAll();
  693. } else {
  694. Columns.Add(&Udf->GetLabel(), false);
  695. }
  696. return true;
  697. }
  698. TNodePtr Build(TContext& ctx) final {
  699. auto input = Source->Build(ctx);
  700. if (!input) {
  701. return nullptr;
  702. }
  703. auto keysTuple = Y();
  704. if (Keys.size() == 1) {
  705. keysTuple = Y("Member", "row", BuildQuotedAtom(Pos, *Keys.back()->GetColumnName()));
  706. }
  707. else {
  708. for (const auto& key: Keys) {
  709. keysTuple = L(keysTuple, Y("Member", "row", BuildQuotedAtom(Pos, *key->GetColumnName())));
  710. }
  711. keysTuple = Q(keysTuple);
  712. }
  713. auto extractKey = Y("SqlExtractKey", "row", BuildLambda(Pos, Y("row"), keysTuple));
  714. auto extractKeyLambda = BuildLambda(Pos, Y("row"), extractKey);
  715. TNodePtr processPartitions;
  716. switch (Mode) {
  717. case ReduceMode::ByAll: {
  718. auto columnPtr = Args[0]->GetColumnName();
  719. TNodePtr expr = BuildAtom(Pos, "partitionStream");
  720. if (!columnPtr || *columnPtr != "*") {
  721. expr = Y("Map", "partitionStream", BuildLambda(Pos, Y("keyPair"), Q(L(Y(),\
  722. Y("Nth", "keyPair", Q(ToString("0"))),\
  723. Y("Map", Y("Nth", "keyPair", Q(ToString("1"))), BuildLambda(Pos, Y("row"),
  724. GroundWithExpr(ExprGround, Args[0])))))));
  725. }
  726. processPartitions = Y("ToSequence", Y("Apply", Udf, expr));
  727. break;
  728. }
  729. case ReduceMode::ByPartition: {
  730. processPartitions = Y("SqlReduce", "partitionStream", extractKeyLambda, Udf,
  731. BuildLambda(Pos, Y("row"), GroundWithExpr(ExprGround, Args[0])));
  732. break;
  733. }
  734. default:
  735. YQL_ENSURE(false, "Unexpected REDUCE mode");
  736. }
  737. TNodePtr sortDirection;
  738. auto sortKeySelector = OrderByGround;
  739. FillSortParts(OrderBy, sortDirection, sortKeySelector);
  740. if (!OrderBy.empty()) {
  741. sortKeySelector = BuildLambda(Pos, Y("row"), Y("SqlExtractKey", "row", sortKeySelector));
  742. }
  743. auto partitionByKey = Y(Mode == ReduceMode::ByAll ? "PartitionByKey" : "PartitionsByKeys", "core", extractKeyLambda,
  744. sortDirection, sortKeySelector, BuildLambda(Pos, Y("partitionStream"), processPartitions));
  745. auto block(Y(Y("let", "core", input)));
  746. auto filter = Source->BuildFilter(ctx, "core", FiltersGround);
  747. if (filter) {
  748. block = L(block, Y("let", "core", filter));
  749. }
  750. block = L(block, Y("let", "core", Y("AutoDemux", partitionByKey)));
  751. if (Having) {
  752. block = L(block, Y("let", "core",
  753. Y("Filter", "core", BuildLambda(Pos, Y("row"), GroundWithExpr(HavingGround, Y("Coalesce", Having, Y("Bool", Q("false"))))))
  754. ));
  755. }
  756. return Y("block", Q(L(block, Y("return", "core"))));
  757. }
  758. TWriteSettings GetWriteSettings() const final {
  759. return Settings;
  760. }
  761. TPtr DoClone() const final {
  762. return new TReduceSource(Pos, Mode, Source->CloneSource(), CloneContainer(OrderBy),
  763. CloneContainer(Keys), CloneContainer(Args), SafeClone(Udf), SafeClone(Having), Settings);
  764. }
  765. private:
  766. ReduceMode Mode;
  767. TSourcePtr Source;
  768. TVector<TSortSpecificationPtr> OrderBy;
  769. TVector<TNodePtr> Keys;
  770. TVector<TNodePtr> Args;
  771. TNodePtr Udf;
  772. TNodePtr Having;
  773. const TWriteSettings Settings;
  774. TNodePtr ExprGround;
  775. TNodePtr FiltersGround;
  776. TNodePtr OrderByGround;
  777. TNodePtr HavingGround;
  778. };
  779. TSourcePtr BuildReduce(TPosition pos,
  780. ReduceMode mode,
  781. TSourcePtr source,
  782. TVector<TSortSpecificationPtr>&& orderBy,
  783. TVector<TNodePtr>&& keys,
  784. TVector<TNodePtr>&& args,
  785. TNodePtr udf,
  786. TNodePtr having,
  787. const TWriteSettings& settings) {
  788. return new TReduceSource(pos, mode, std::move(source), std::move(orderBy), std::move(keys), std::move(args), udf, having, settings);
  789. }
  790. class TCompositeSelect: public IRealSource {
  791. public:
  792. TCompositeSelect(TPosition pos, TSourcePtr source, const TWriteSettings& settings)
  793. : IRealSource(pos)
  794. , Source(std::move(source))
  795. , Settings(settings)
  796. {
  797. YQL_ENSURE(Source);
  798. }
  799. void SetSubselects(TVector<TSourcePtr>&& subselects, TSet<TString>&& groupingCols) {
  800. Subselects = std::move(subselects);
  801. GroupingCols = std::move(groupingCols);
  802. Y_DEBUG_ABORT_UNLESS(Subselects.size() > 1);
  803. }
  804. void GetInputTables(TTableList& tableList) const override {
  805. for (const auto& select: Subselects) {
  806. select->GetInputTables(tableList);
  807. }
  808. ISource::GetInputTables(tableList);
  809. }
  810. bool DoInit(TContext& ctx, ISource* src) override {
  811. if (AsInner) {
  812. Source->UseAsInner();
  813. }
  814. ctx.PushBlockShortcuts();
  815. if (src) {
  816. src->AddDependentSource(Source.Get());
  817. }
  818. if (!Source->Init(ctx, src)) {
  819. return false;
  820. }
  821. if (!Source->InitFilters(ctx)) {
  822. return false;
  823. }
  824. FiltersGround = ctx.GroundBlockShortcuts(Pos);
  825. for (const auto& select: Subselects) {
  826. select->SetLabel(Label);
  827. if (AsInner) {
  828. select->UseAsInner();
  829. }
  830. if (!select->Init(ctx, Source.Get())) {
  831. return false;
  832. }
  833. }
  834. return true;
  835. }
  836. TMaybe<bool> AddColumn(TContext& ctx, TColumnNode& column) override {
  837. for (const auto& select: Subselects) {
  838. if (!select->AddColumn(ctx, column)) {
  839. return {};
  840. }
  841. }
  842. return true;
  843. }
  844. TNodePtr Build(TContext& ctx) override {
  845. auto input = Source->Build(ctx);
  846. auto block(Y(Y("let", "composite", input)));
  847. auto filter = Source->BuildFilter(ctx, "composite", FiltersGround);
  848. if (filter) {
  849. block = L(block, Y("let", "composite", filter));
  850. }
  851. TNodePtr compositeNode = Y("UnionAll");
  852. for (const auto& select: Subselects) {
  853. auto addNode = select->Build(ctx);
  854. if (!addNode) {
  855. return nullptr;
  856. }
  857. compositeNode->Add(addNode);
  858. }
  859. return GroundWithExpr(block, compositeNode);
  860. }
  861. bool IsGroupByColumn(const TString& column) const override {
  862. return GroupingCols.contains(column);
  863. }
  864. const TSet<TString>& GetGroupingCols() const {
  865. return GroupingCols;
  866. }
  867. TNodePtr BuildSort(TContext& ctx, const TString& label) override {
  868. return Subselects.front()->BuildSort(ctx, label);
  869. }
  870. bool IsOrdered() const override {
  871. return Subselects.front()->IsOrdered();
  872. }
  873. const TColumns* GetColumns() const override{
  874. return Subselects.front()->GetColumns();
  875. }
  876. ISource* RealSource() const {
  877. return Source.Get();
  878. }
  879. TWriteSettings GetWriteSettings() const override {
  880. return Settings;
  881. }
  882. TNodePtr DoClone() const final {
  883. auto newSource = MakeIntrusive<TCompositeSelect>(Pos, Source->CloneSource(), Settings);
  884. newSource->SetSubselects(CloneContainer(Subselects), TSet<TString>(GroupingCols));
  885. return newSource;
  886. }
  887. private:
  888. TSourcePtr Source;
  889. const TWriteSettings Settings;
  890. TVector<TSourcePtr> Subselects;
  891. TSet<TString> GroupingCols;
  892. TNodePtr FiltersGround;
  893. };
  894. /// \todo simplify class
  895. class TSelectCore: public IRealSource {
  896. public:
  897. TSelectCore(
  898. TPosition pos,
  899. TSourcePtr source,
  900. const TVector<TNodePtr>& groupByExpr,
  901. const TVector<TNodePtr>& groupBy,
  902. const TVector<TSortSpecificationPtr>& orderBy,
  903. TNodePtr having,
  904. TWinSpecs& winSpecs,
  905. THoppingWindowSpecPtr hoppingWindowSpec,
  906. const TVector<TNodePtr>& terms,
  907. bool distinct,
  908. const TVector<TNodePtr>& without,
  909. bool stream,
  910. const TWriteSettings& settings
  911. )
  912. : IRealSource(pos)
  913. , Source(std::move(source))
  914. , GroupByExpr(groupByExpr)
  915. , GroupBy(groupBy)
  916. , OrderBy(orderBy)
  917. , Having(having)
  918. , WinSpecs(winSpecs)
  919. , Terms(terms)
  920. , Without(without)
  921. , Distinct(distinct)
  922. , HoppingWindowSpec(hoppingWindowSpec)
  923. , Stream(stream)
  924. , Settings(settings)
  925. {
  926. }
  927. void GetInputTables(TTableList& tableList) const override {
  928. Source->GetInputTables(tableList);
  929. ISource::GetInputTables(tableList);
  930. }
  931. bool IsComparableExpression(TContext& ctx, const TNodePtr& expr, const char* sqlConstruction) {
  932. if (expr->IsConstant()) {
  933. ctx.Error(expr->GetPos()) << "Unable to " << sqlConstruction << " constant expression";
  934. return false;
  935. }
  936. if (expr->IsAggregated() && !expr->HasState(ENodeState::AggregationKey)) {
  937. ctx.Error(expr->GetPos()) << "Unable to " << sqlConstruction << " aggregated values";
  938. return false;
  939. }
  940. if (expr->GetSourceName()) {
  941. return true;
  942. }
  943. if (expr->GetOpName().empty()) {
  944. ctx.Error(expr->GetPos()) << "You should use in " << sqlConstruction << " column name, qualified field, callable function or expression";
  945. return false;
  946. }
  947. return true;
  948. }
  949. bool DoInit(TContext& ctx, ISource* initSrc) override {
  950. if (AsInner) {
  951. Source->UseAsInner();
  952. }
  953. if (!Source->Init(ctx, initSrc)) {
  954. return false;
  955. }
  956. if (Stream && !Source->IsStream()) {
  957. ctx.Error(Pos) << "SELECT STREAM is unsupported for non-streaming sources";
  958. return false;
  959. }
  960. if (!Stream && Source->IsStream() && !ctx.PragmaDirectRead) {
  961. ctx.Error(Pos) << "SELECT STREAM must be used for streaming sources";
  962. return false;
  963. }
  964. ctx.PushBlockShortcuts();
  965. auto src = Source.Get();
  966. bool hasError = false;
  967. for (auto& expr: GroupByExpr) {
  968. if (!expr->Init(ctx, src) || !IsComparableExpression(ctx, expr, "GROUP BY")) {
  969. hasError = true;
  970. continue;
  971. }
  972. }
  973. if (!src->AddExpressions(ctx, GroupByExpr, EExprSeat::GroupBy)) {
  974. hasError = true;
  975. }
  976. GroupByExprGround = ctx.GroundBlockShortcuts(Pos);
  977. /// grouped expressions are available in filters
  978. ctx.PushBlockShortcuts();
  979. if (!Source->InitFilters(ctx)) {
  980. hasError = true;
  981. }
  982. FiltersGround = ctx.GroundBlockShortcuts(Pos);
  983. const bool isJoin = Source->GetJoin();
  984. for (auto& expr: GroupBy) {
  985. if (!expr->Init(ctx, src)) {
  986. hasError = true;
  987. continue;
  988. }
  989. auto keyNamePtr = expr->GetColumnName();
  990. if (keyNamePtr && expr->GetLabel().empty()) {
  991. auto usedColumn = *keyNamePtr;
  992. auto sourceNamePtr = expr->GetSourceName();
  993. auto columnNode = dynamic_cast<TColumnNode*>(expr.Get());
  994. if (isJoin && (!columnNode || !columnNode->IsArtificial())) {
  995. if (!sourceNamePtr || sourceNamePtr->empty()) {
  996. ctx.Error(expr->GetPos()) << "Columns in GROUP BY should have correlation name, error in key: " << usedColumn;
  997. hasError = true;
  998. continue;
  999. }
  1000. usedColumn = DotJoin(*sourceNamePtr, usedColumn);
  1001. }
  1002. if (!src->AddGroupKey(ctx, usedColumn)) {
  1003. hasError = true;
  1004. continue;
  1005. }
  1006. }
  1007. }
  1008. ctx.PushBlockShortcuts();
  1009. if (Having && !Having->Init(ctx, src)) {
  1010. hasError = true;
  1011. }
  1012. HavingGround = ctx.GroundBlockShortcuts(Pos);
  1013. src->AddWindowSpecs(WinSpecs);
  1014. if (!InitSelect(ctx, src, isJoin, hasError)) {
  1015. return false;
  1016. }
  1017. src->FinishColumns();
  1018. Aggregate = src->BuildAggregation("core");
  1019. if (src->IsFlattenByColumns() || src->IsFlattenColumns()) {
  1020. Flatten = src->IsFlattenByColumns() ?
  1021. src->BuildFlattenByColumns("row") :
  1022. src->BuildFlattenColumns("row");
  1023. if (!Flatten || !Flatten->Init(ctx, src)) {
  1024. hasError = true;
  1025. }
  1026. }
  1027. if (GroupByExpr) {
  1028. auto sourcePreaggregate = src->BuildPreaggregatedMap(ctx);
  1029. if (!sourcePreaggregate) {
  1030. hasError = true;
  1031. } else {
  1032. PreaggregatedMap = !GroupByExprGround ? sourcePreaggregate :
  1033. Y("block", Q(L(GroupByExprGround, Y("return", sourcePreaggregate))));
  1034. }
  1035. }
  1036. if (Aggregate) {
  1037. if (!Aggregate->Init(ctx, src)) {
  1038. hasError = true;
  1039. }
  1040. if (Having) {
  1041. Aggregate = Y(
  1042. "Filter",
  1043. Aggregate,
  1044. BuildLambda(Pos, Y("row"), GroundWithExpr(HavingGround, Y("Coalesce", Having, Y("Bool", Q("false")))))
  1045. );
  1046. }
  1047. } else if (Having) {
  1048. ctx.Error(Having->GetPos()) << "HAVING with meaning GROUP BY () should be with aggregation function.";
  1049. hasError = true;
  1050. } else if (!Distinct && !GroupBy.empty()) {
  1051. ctx.Error(Pos) << "No aggregations were specified";
  1052. hasError = true;
  1053. }
  1054. if (hasError) {
  1055. return false;
  1056. }
  1057. if (src->IsCalcOverWindow()) {
  1058. if (src->IsExprSeat(EExprSeat::WindowPartitionBy, EExprType::WithExpression)) {
  1059. PrewindowMap = src->BuildPrewindowMap(ctx, WinSpecsPartitionByGround);
  1060. if (!PrewindowMap) {
  1061. hasError = true;
  1062. }
  1063. }
  1064. CalcOverWindow = src->BuildCalcOverWindow(ctx, "core", WinSpecsOrderByGround);
  1065. if (!CalcOverWindow) {
  1066. hasError = true;
  1067. }
  1068. }
  1069. if (hasError) {
  1070. return false;
  1071. }
  1072. return true;
  1073. }
  1074. TNodePtr Build(TContext& ctx) override {
  1075. auto input = Source->Build(ctx);
  1076. if (!input) {
  1077. return nullptr;
  1078. }
  1079. TNodePtr terms = BuildColumnsTerms(ctx);
  1080. bool ordered = ctx.UseUnordered(*this);
  1081. auto block(Y(Y("let", "core", input)));
  1082. if (Flatten) {
  1083. block = L(block, Y("let", "core", Y(ordered ? "OrderedFlatMap" : "FlatMap", "core", BuildLambda(Pos, Y("row"), Flatten, "res"))));
  1084. }
  1085. if (PreaggregatedMap) {
  1086. block = L(block, Y("let", "core", Y("FlatMap", "core", BuildLambda(Pos, Y("row"), PreaggregatedMap))));
  1087. if (Source->IsCompositeSource() && !Columns.QualifiedAll) {
  1088. block = L(block, Y("let", "preaggregated", "core"));
  1089. }
  1090. } else if (Source->IsCompositeSource() && !Columns.QualifiedAll) {
  1091. block = L(block, Y("let", "origcore", "core"));
  1092. }
  1093. auto filter = Source->BuildFilter(ctx, "core", FiltersGround);
  1094. if (filter) {
  1095. block = L(block, Y("let", "core", filter));
  1096. }
  1097. if (Aggregate) {
  1098. block = L(block, Y("let", "core", Aggregate));
  1099. ordered = false;
  1100. }
  1101. if (PrewindowMap) {
  1102. block = L(block, Y("let", "core", PrewindowMap));
  1103. }
  1104. if (CalcOverWindow) {
  1105. block = L(block, Y("let", "core", CalcOverWindow));
  1106. }
  1107. block = L(block, Y("let", "core", Y("EnsurePersistable", Y(ordered ? "OrderedFlatMap" : "FlatMap", "core", BuildLambda(Pos, Y("row"), terms, "res")))));
  1108. return Y("block", Q(L(block, Y("return", "core"))));
  1109. }
  1110. TNodePtr BuildSort(TContext& ctx, const TString& label) override {
  1111. Y_UNUSED(ctx);
  1112. if (OrderBy.empty()) {
  1113. return nullptr;
  1114. }
  1115. return Y("let", label, BuildSortSpec(OrderBy, label, OrderByGround));
  1116. }
  1117. bool IsSelect() const override {
  1118. return true;
  1119. }
  1120. bool IsStream() const override {
  1121. return Stream;
  1122. }
  1123. bool IsOrdered() const override {
  1124. return !OrderBy.empty();
  1125. }
  1126. TWriteSettings GetWriteSettings() const override {
  1127. return Settings;
  1128. }
  1129. TMaybe<bool> AddColumn(TContext& ctx, TColumnNode& column) override {
  1130. if (OrderByInit && Source->GetJoin()) {
  1131. column.SetAsNotReliable();
  1132. auto maybeExist = IRealSource::AddColumn(ctx, column);
  1133. if (maybeExist && maybeExist.GetRef()) {
  1134. return true;
  1135. }
  1136. return Source->AddColumn(ctx, column);
  1137. }
  1138. return IRealSource::AddColumn(ctx, column);
  1139. }
  1140. TNodePtr PrepareWithout(const TNodePtr& base) {
  1141. auto terms = base;
  1142. if (Without) {
  1143. for (auto without: Without) {
  1144. auto name = *without->GetColumnName();
  1145. if (Source && Source->GetJoin()) {
  1146. name = DotJoin(*without->GetSourceName(), name);
  1147. }
  1148. terms = L(terms, Y("let", "row", Y("RemoveMember", "row", Q(name))));
  1149. }
  1150. }
  1151. if (Source) {
  1152. for (auto column : Source->GetTmpWindowColumns()) {
  1153. terms = L(terms, Y("let", "row", Y("RemoveMember", "row", Q(column))));
  1154. }
  1155. }
  1156. return terms;
  1157. }
  1158. TNodePtr DoClone() const final {
  1159. TWinSpecs newSpecs;
  1160. for (auto cur: WinSpecs) {
  1161. newSpecs.emplace(cur.first, cur.second->Clone());
  1162. }
  1163. return new TSelectCore(Pos, Source->CloneSource(), CloneContainer(GroupByExpr),
  1164. CloneContainer(GroupBy), CloneContainer(OrderBy), SafeClone(Having), newSpecs, SafeClone(HoppingWindowSpec),
  1165. CloneContainer(Terms), Distinct, Without, Stream, Settings);
  1166. }
  1167. private:
  1168. bool InitSelect(TContext& ctx, ISource* src, bool isJoin, bool& hasError) {
  1169. for (auto iter: WinSpecs) {
  1170. auto winSpec = *iter.second;
  1171. ctx.PushBlockShortcuts();
  1172. for (auto& partitionNode: winSpec.Partitions) {
  1173. auto invalidPartitionNodeFunc = [&]() {
  1174. ctx.Error(partitionNode->GetPos()) << "Expected either column name, either alias" <<
  1175. " or expression with alias for PARTITION BY expression in WINDOWS clause";
  1176. hasError = true;
  1177. };
  1178. if (!partitionNode->GetLabel() && !partitionNode->GetColumnName()) {
  1179. invalidPartitionNodeFunc();
  1180. continue;
  1181. }
  1182. if (!partitionNode->Init(ctx, src)) {
  1183. hasError = true;
  1184. continue;
  1185. }
  1186. if (!partitionNode->GetLabel() && !partitionNode->GetColumnName()) {
  1187. invalidPartitionNodeFunc();
  1188. continue;
  1189. }
  1190. }
  1191. WinSpecsPartitionByGround = ctx.GroundBlockShortcuts(Pos, WinSpecsPartitionByGround);
  1192. if (!src->AddExpressions(ctx, winSpec.Partitions, EExprSeat::WindowPartitionBy)) {
  1193. hasError = true;
  1194. }
  1195. ctx.PushBlockShortcuts();
  1196. for (auto orderSpec: winSpec.OrderBy) {
  1197. if (!orderSpec->OrderExpr->Init(ctx, src)) {
  1198. hasError = true;
  1199. }
  1200. }
  1201. WinSpecsOrderByGround = ctx.GroundBlockShortcuts(Pos, WinSpecsOrderByGround);
  1202. }
  1203. if (HoppingWindowSpec) {
  1204. ctx.PushBlockShortcuts();
  1205. if (!HoppingWindowSpec->TimeExtractor->Init(ctx, src)) {
  1206. hasError = true;
  1207. }
  1208. HoppingWindowSpec->TimeExtractor = ctx.GroundBlockShortcutsForExpr(HoppingWindowSpec->TimeExtractor);
  1209. src->SetHoppingWindowSpec(HoppingWindowSpec);
  1210. }
  1211. ctx.PushBlockShortcuts();
  1212. for (auto& term: Terms) {
  1213. if (!term->Init(ctx, src)) {
  1214. hasError = true;
  1215. continue;
  1216. }
  1217. auto column = term->GetColumnName();
  1218. if (Distinct) {
  1219. if (!column) {
  1220. ctx.Error(Pos) << "SELECT DISTINCT requires a list of column references";
  1221. hasError = true;
  1222. continue;
  1223. }
  1224. if (term->IsAsterisk()) {
  1225. ctx.Error(Pos) << "SELECT DISTINCT * is not implemented yet";
  1226. hasError = true;
  1227. continue;
  1228. }
  1229. auto columnName = *column;
  1230. if (isJoin) {
  1231. auto sourceNamePtr = term->GetSourceName();
  1232. if (!sourceNamePtr || sourceNamePtr->empty()) {
  1233. if (src->IsGroupByColumn(columnName)) {
  1234. ctx.Error(term->GetPos()) << ErrorDistinctByGroupKey(columnName);
  1235. hasError = true;
  1236. continue;
  1237. } else {
  1238. ctx.Error(term->GetPos()) << ErrorDistinctWithoutCorrelation(columnName);
  1239. hasError = true;
  1240. continue;
  1241. }
  1242. }
  1243. columnName = DotJoin(*sourceNamePtr, columnName);
  1244. }
  1245. if (src->IsGroupByColumn(columnName)) {
  1246. ctx.Error(term->GetPos()) << ErrorDistinctByGroupKey(columnName);
  1247. hasError = true;
  1248. continue;
  1249. }
  1250. if (!src->AddGroupKey(ctx, columnName)) {
  1251. hasError = true;
  1252. continue;
  1253. }
  1254. GroupBy.push_back(BuildColumn(Pos, columnName));
  1255. }
  1256. TString label(term->GetLabel());
  1257. bool hasName = true;
  1258. if (label.empty()) {
  1259. auto source = term->GetSourceName();
  1260. if (term->IsAsterisk() && !source->empty()) {
  1261. Columns.QualifiedAll = true;
  1262. label = DotJoin(*source, "*");
  1263. } else if (column) {
  1264. label = isJoin && source && *source ? DotJoin(*source, *column) : *column;
  1265. } else {
  1266. label = TStringBuilder() << "column" << Columns.List.size();
  1267. hasName = false;
  1268. }
  1269. }
  1270. if (!Columns.Add(&label, false, false, true, hasName)) {
  1271. ctx.Error(Pos) << "Duplicate column: " << label;
  1272. hasError = true;
  1273. continue;
  1274. }
  1275. }
  1276. TermsGround = ctx.GroundBlockShortcuts(Pos);
  1277. if (Columns.All || Columns.QualifiedAll) {
  1278. Source->AllColumns();
  1279. if (Columns.All && isJoin && ctx.SimpleColumns) {
  1280. Columns.All = false;
  1281. Columns.QualifiedAll = true;
  1282. const auto pos = Terms.front()->GetPos();
  1283. Terms.clear();
  1284. for (const auto& source: Source->GetJoin()->GetJoinLabels()) {
  1285. auto withDot = DotJoin(source, "*");
  1286. Columns.Add(&withDot, false);
  1287. Terms.push_back(BuildColumn(pos, "*", source));
  1288. }
  1289. }
  1290. }
  1291. for (const auto& without: Without) {
  1292. auto namePtr = without->GetColumnName();
  1293. auto sourcePtr = without->GetSourceName();
  1294. YQL_ENSURE(namePtr && *namePtr);
  1295. if (isJoin && !(sourcePtr && *sourcePtr)) {
  1296. ctx.Error(without->GetPos()) << "Expected correlation name for WITHOUT in JOIN";
  1297. hasError = true;
  1298. continue;
  1299. }
  1300. }
  1301. if (Having && !Having->Init(ctx, src)) {
  1302. hasError = true;
  1303. }
  1304. if (!src->IsCompositeSource() && !Distinct && !Columns.All && src->HasAggregations()) {
  1305. /// verify select aggregation compatibility
  1306. TVector<TNodePtr> exprs(Terms);
  1307. if (Having) {
  1308. exprs.push_back(Having);
  1309. }
  1310. for (const auto& iter: WinSpecs) {
  1311. for (const auto& sortSpec: iter.second->OrderBy) {
  1312. exprs.push_back(sortSpec->OrderExpr);
  1313. }
  1314. }
  1315. if (!ValidateAllNodesForAggregation(ctx, exprs)) {
  1316. hasError = true;
  1317. }
  1318. }
  1319. const auto label = GetLabel();
  1320. ctx.PushBlockShortcuts();
  1321. for (const auto& sortSpec: OrderBy) {
  1322. auto& expr = sortSpec->OrderExpr;
  1323. SetLabel(Source->GetLabel());
  1324. OrderByInit = true;
  1325. if (!expr->Init(ctx, this)) {
  1326. hasError = true;
  1327. continue;
  1328. }
  1329. OrderByInit = false;
  1330. if (!IsComparableExpression(ctx, expr, "ORDER BY")) {
  1331. hasError = true;
  1332. continue;
  1333. }
  1334. }
  1335. OrderByGround = ctx.GroundBlockShortcuts(Pos);
  1336. SetLabel(label);
  1337. return true;
  1338. }
  1339. TNodePtr BuildColumnsTerms(TContext& ctx) {
  1340. TNodePtr terms;
  1341. if (Columns.All) {
  1342. Y_DEBUG_ABORT_UNLESS(Columns.List.empty());
  1343. terms = PrepareWithout(Y());
  1344. if (ctx.EnableSystemColumns) {
  1345. terms = L(terms, Y("let", "res", Y("AsList", Y("RemoveSystemMembers", "row"))));
  1346. } else {
  1347. terms = L(terms, (Y("let", "res", Y("AsList", "row"))));
  1348. }
  1349. } else if (!Columns.List.empty()) {
  1350. Y_DEBUG_ABORT_UNLESS(Columns.List.size() == Terms.size());
  1351. const bool isJoin = Source->GetJoin();
  1352. terms = TermsGround ? TermsGround : Y();
  1353. if (Source->IsCompositeSource() && !Columns.QualifiedAll) {
  1354. auto compositeSrcPtr = static_cast<TCompositeSelect*>(Source->GetCompositeSource());
  1355. if (compositeSrcPtr) {
  1356. const auto& groupings = compositeSrcPtr->GetGroupingCols();
  1357. for (const auto& column: groupings) {
  1358. bool isAggregated = false;
  1359. for (const auto& group: GroupBy) {
  1360. const auto columnName = group->GetColumnName();
  1361. if (columnName && *columnName == column) {
  1362. isAggregated = true;
  1363. break;
  1364. }
  1365. }
  1366. if (isAggregated) {
  1367. continue;
  1368. }
  1369. const TString tableName = PreaggregatedMap ? "preaggregated" : "origcore";
  1370. terms = L(terms, Y("let", "row", Y("AddMember", "row", BuildQuotedAtom(Pos, column), Y("Nothing", Y("MatchType",
  1371. Y("StructMemberType", Y("ListItemType", Y("TypeOf", tableName)), Q(column)),
  1372. Q("Optional"), Y("lambda", Q(Y("item")), "item"), Y("lambda", Q(Y("item")), Y("OptionalType", "item")))))));
  1373. }
  1374. }
  1375. }
  1376. TNodePtr structObj = nullptr;
  1377. auto column = Columns.List.begin();
  1378. for (auto& term: Terms) {
  1379. if (!term->IsAsterisk()) {
  1380. if (!structObj) {
  1381. structObj = Y("AsStruct");
  1382. }
  1383. structObj = L(structObj, Q(Y(BuildQuotedAtom(Pos, *column), term)));
  1384. }
  1385. ++column;
  1386. }
  1387. terms = structObj ? L(terms, Y("let", "res", structObj)) : Y(Y("let", "res", Y("AsStruct")));
  1388. terms = PrepareWithout(terms);
  1389. if (Columns.QualifiedAll) {
  1390. if (ctx.SimpleColumns && !isJoin) {
  1391. terms = L(terms, Y("let", "res", Y("FlattenMembers", Q(Y(BuildQuotedAtom(Pos, ""), "res")),
  1392. Q(Y(BuildQuotedAtom(Pos, ""), "row")))));
  1393. } else {
  1394. if (isJoin && ctx.SimpleColumns) {
  1395. const auto& sameKeyMap = Source->GetJoin()->GetSameKeysMap();
  1396. if (sameKeyMap) {
  1397. terms = L(terms, Y("let", "flatSameKeys", "row"));
  1398. for (const auto& sameKeysPair: sameKeyMap) {
  1399. const auto& column = sameKeysPair.first;
  1400. auto keys = Y("Coalesce");
  1401. auto sameSourceIter = sameKeysPair.second.begin();
  1402. for (auto end = sameKeysPair.second.end(); sameSourceIter != end; ++sameSourceIter) {
  1403. auto addKeyNode = Q(DotJoin(*sameSourceIter, column));
  1404. keys = L(keys, Y("TryMember", "row", addKeyNode, Y("Null")));
  1405. }
  1406. terms = L(terms, Y("let", "flatSameKeys", Y("AddMember", "flatSameKeys", Q(column), keys)));
  1407. sameSourceIter = sameKeysPair.second.begin();
  1408. for (auto end = sameKeysPair.second.end(); sameSourceIter != end; ++sameSourceIter) {
  1409. auto removeKeyNode = Q(DotJoin(*sameSourceIter, column));
  1410. terms = L(terms, Y("let", "flatSameKeys", Y("ForceRemoveMember", "flatSameKeys", removeKeyNode)));
  1411. }
  1412. }
  1413. terms = L(terms, Y("let", "row", "flatSameKeys"));
  1414. }
  1415. }
  1416. auto members = isJoin ? Y() : Y("FlattenMembers");
  1417. for (auto& term: Terms) {
  1418. if (term->IsAsterisk()) {
  1419. auto sourceName = term->GetSourceName();
  1420. YQL_ENSURE(*sourceName && !sourceName->empty());
  1421. if (isJoin) {
  1422. members = L(members, BuildQuotedAtom(Pos, *sourceName + "."));
  1423. } else {
  1424. auto prefix = ctx.SimpleColumns ? "" : *sourceName + ".";
  1425. members = L(members, Q(Y(Q(prefix), "row")));
  1426. }
  1427. }
  1428. }
  1429. if (isJoin) {
  1430. members = Y(ctx.SimpleColumns ? "DivePrefixMembers" : "SelectMembers", "row", Q(members));
  1431. }
  1432. terms = L(terms, Y("let", "res", Y("FlattenMembers", Q(Y(BuildQuotedAtom(Pos, ""), "res")),
  1433. Q(Y(BuildQuotedAtom(Pos, ""), members)))));
  1434. if (isJoin && ctx.SimpleColumns) {
  1435. for (const auto& sameKeysPair: Source->GetJoin()->GetSameKeysMap()) {
  1436. const auto& column = sameKeysPair.first;
  1437. auto addMemberKeyNode = Y("Member", "row", Q(column));
  1438. terms = L(terms, Y("let", "res", Y("AddMember", "res", Q(column), addMemberKeyNode)));
  1439. }
  1440. }
  1441. }
  1442. }
  1443. terms = L(terms, Y("let", "res", Y("AsList", "res")));
  1444. }
  1445. return terms;
  1446. }
  1447. private:
  1448. TSourcePtr Source;
  1449. TVector<TNodePtr> GroupByExpr;
  1450. TVector<TNodePtr> GroupBy;
  1451. TVector<TSortSpecificationPtr> OrderBy;
  1452. TNodePtr Having;
  1453. TWinSpecs WinSpecs;
  1454. TNodePtr Flatten;
  1455. TNodePtr PreaggregatedMap;
  1456. TNodePtr PrewindowMap;
  1457. TNodePtr Aggregate;
  1458. TNodePtr CalcOverWindow;
  1459. TNodePtr FiltersGround;
  1460. TNodePtr TermsGround;
  1461. TNodePtr GroupByExprGround;
  1462. TNodePtr HavingGround;
  1463. TNodePtr OrderByGround;
  1464. TNodePtr WinSpecsPartitionByGround;
  1465. TNodePtr WinSpecsOrderByGround;
  1466. TVector<TNodePtr> Terms;
  1467. TVector<TNodePtr> Without;
  1468. const bool Distinct;
  1469. bool OrderByInit = false;
  1470. THoppingWindowSpecPtr HoppingWindowSpec;
  1471. const bool Stream;
  1472. const TWriteSettings Settings;
  1473. };
  1474. class TProcessSource: public IRealSource {
  1475. public:
  1476. TProcessSource(
  1477. TPosition pos,
  1478. TSourcePtr source,
  1479. TNodePtr with,
  1480. TVector<TNodePtr>&& terms,
  1481. bool listCall,
  1482. bool stream,
  1483. const TWriteSettings& settings
  1484. )
  1485. : IRealSource(pos)
  1486. , Source(std::move(source))
  1487. , With(with)
  1488. , Terms(std::move(terms))
  1489. , ListCall(listCall)
  1490. , Stream(stream)
  1491. , Settings(settings)
  1492. {
  1493. }
  1494. void GetInputTables(TTableList& tableList) const override {
  1495. Source->GetInputTables(tableList);
  1496. ISource::GetInputTables(tableList);
  1497. }
  1498. bool DoInit(TContext& ctx, ISource* initSrc) override {
  1499. if (AsInner) {
  1500. Source->UseAsInner();
  1501. }
  1502. if (!Source->Init(ctx, initSrc)) {
  1503. return false;
  1504. }
  1505. if (Stream && !Source->IsStream()) {
  1506. ctx.Error(Pos) << "PROCESS STREAM is unsupported for non-streaming sources";
  1507. return false;
  1508. }
  1509. if (!Stream && Source->IsStream() && !ctx.PragmaDirectRead) {
  1510. ctx.Error(Pos) << "PROCESS STREAM must be used for streaming sources";
  1511. return false;
  1512. }
  1513. auto src = Source.Get();
  1514. if (!With) {
  1515. src->AllColumns();
  1516. Columns.SetAll();
  1517. src->FinishColumns();
  1518. return true;
  1519. }
  1520. /// grouped expressions are available in filters
  1521. ctx.PushBlockShortcuts();
  1522. if (!Source->InitFilters(ctx)) {
  1523. return false;
  1524. }
  1525. FiltersGround = ctx.GroundBlockShortcuts(Pos);
  1526. // Use fake source in case of list process to restrict column access.
  1527. TSourcePtr fakeSource;
  1528. if (ListCall) {
  1529. fakeSource = BuildFakeSource(src->GetPos());
  1530. src->AllColumns();
  1531. }
  1532. auto processSource = ListCall ? fakeSource.Get() : src;
  1533. Y_DEBUG_ABORT_UNLESS(processSource != nullptr);
  1534. ctx.PushBlockShortcuts();
  1535. if (!With->Init(ctx, processSource)) {
  1536. return false;
  1537. }
  1538. if (With->GetLabel().empty()) {
  1539. Columns.SetAll();
  1540. } else {
  1541. if (ListCall) {
  1542. ctx.Error(With->GetPos()) << "Label is not allowed to use with $ROWS";
  1543. return false;
  1544. }
  1545. Columns.Add(&With->GetLabel(), false);
  1546. }
  1547. bool hasError = false;
  1548. auto produce = Y(ListCall ? "SqlProcess" : "Apply", With);
  1549. TMaybe<ui32> listPosIndex;
  1550. ui32 termIndex = 0;
  1551. for (auto& term: Terms) {
  1552. if (ListCall) {
  1553. if (auto atom = dynamic_cast<TAstAtomNode*>(term.Get())) {
  1554. if (atom->GetContent() == "inputRowsList") {
  1555. listPosIndex = termIndex;
  1556. }
  1557. }
  1558. }
  1559. ++termIndex;
  1560. if (!term->GetLabel().empty()) {
  1561. ctx.Error(term->GetPos()) << "Labels are not allowed for PROCESS terms";
  1562. hasError = true;
  1563. continue;
  1564. }
  1565. if (!term->Init(ctx, processSource)) {
  1566. hasError = true;
  1567. continue;
  1568. }
  1569. produce = L(produce, term);
  1570. }
  1571. if (ListCall) {
  1572. produce = L(produce, Q(ToString(*listPosIndex)));
  1573. }
  1574. if (!produce->Init(ctx, src)) {
  1575. hasError = true;
  1576. }
  1577. produce = ctx.GroundBlockShortcutsForExpr(produce);
  1578. TVector<TNodePtr>(1, produce).swap(Terms);
  1579. src->FinishColumns();
  1580. if (hasError) {
  1581. return false;
  1582. }
  1583. return true;
  1584. }
  1585. TNodePtr Build(TContext& ctx) override {
  1586. auto input = Source->Build(ctx);
  1587. if (!input) {
  1588. return nullptr;
  1589. }
  1590. if (!With) {
  1591. return input;
  1592. }
  1593. TString inputLabel = ListCall ? "inputRowsList" : "core";
  1594. auto block(Y(Y("let", inputLabel, input)));
  1595. auto filter = Source->BuildFilter(ctx, inputLabel, FiltersGround);
  1596. if (filter) {
  1597. block = L(block, Y("let", inputLabel, filter));
  1598. }
  1599. if (ListCall) {
  1600. block = L(block, Y("let", "core", Terms[0]));
  1601. } else {
  1602. auto terms = BuildColumnsTerms(ctx);
  1603. block = L(block, Y("let", "core", Y(ctx.UseUnordered(*this) ? "OrderedFlatMap" : "FlatMap", "core", BuildLambda(Pos, Y("row"), terms, "res"))));
  1604. }
  1605. block = L(block, Y("let", "core", Y("AutoDemux", Y("EnsurePersistable", "core"))));
  1606. return Y("block", Q(L(block, Y("return", "core"))));
  1607. }
  1608. bool IsSelect() const override {
  1609. return false;
  1610. }
  1611. bool IsStream() const override {
  1612. return Stream;
  1613. }
  1614. TWriteSettings GetWriteSettings() const override {
  1615. return Settings;
  1616. }
  1617. TNodePtr DoClone() const final {
  1618. return new TProcessSource(Pos, Source->CloneSource(), SafeClone(With),
  1619. CloneContainer(Terms), ListCall, Stream, Settings);
  1620. }
  1621. private:
  1622. TNodePtr BuildColumnsTerms(TContext& ctx) {
  1623. Y_UNUSED(ctx);
  1624. TNodePtr terms;
  1625. Y_DEBUG_ABORT_UNLESS(Terms.size() == 1);
  1626. if (Columns.All) {
  1627. terms = Y(Y("let", "res", Y("ToSequence", Terms.front())));
  1628. } else {
  1629. Y_DEBUG_ABORT_UNLESS(Columns.List.size() == Terms.size());
  1630. terms = TermsGround ? TermsGround : Y();
  1631. terms = L(terms, Y("let", "res",
  1632. L(Y("AsStruct"), Q(Y(BuildQuotedAtom(Pos, Columns.List.front()), Terms.front())))));
  1633. terms = L(terms, Y("let", "res", Y("Just", "res")));
  1634. }
  1635. return terms;
  1636. }
  1637. private:
  1638. TSourcePtr Source;
  1639. TNodePtr With;
  1640. TNodePtr FiltersGround;
  1641. TNodePtr TermsGround;
  1642. TVector<TNodePtr> Terms;
  1643. const bool ListCall;
  1644. const bool Stream;
  1645. const TWriteSettings Settings;
  1646. };
  1647. TSourcePtr BuildProcess(
  1648. TPosition pos,
  1649. TSourcePtr source,
  1650. TNodePtr with,
  1651. TVector<TNodePtr>&& terms,
  1652. bool listCall,
  1653. bool stream,
  1654. const TWriteSettings& settings
  1655. ) {
  1656. return new TProcessSource(pos, std::move(source), with, std::move(terms), listCall, stream, settings);
  1657. }
  1658. class TNestedProxySource: public IProxySource {
  1659. public:
  1660. TNestedProxySource(TPosition pos, const TVector<TNodePtr>& groupBy, TSourcePtr source)
  1661. : IProxySource(pos, source.Get())
  1662. , CompositeSelect(nullptr)
  1663. , Holder(std::move(source))
  1664. , GroupBy(groupBy)
  1665. {}
  1666. TNestedProxySource(TCompositeSelect* compositeSelect, const TVector<TNodePtr>& groupBy)
  1667. : IProxySource(compositeSelect->GetPos(), compositeSelect->RealSource())
  1668. , CompositeSelect(compositeSelect)
  1669. , GroupBy(groupBy)
  1670. {}
  1671. bool DoInit(TContext& ctx, ISource* src) override {
  1672. return Source->Init(ctx, src);
  1673. }
  1674. TNodePtr Build(TContext& ctx) override {
  1675. return CompositeSelect ? BuildAtom(Pos, "composite", TNodeFlags::Default) : Source->Build(ctx);
  1676. }
  1677. bool InitFilters(TContext& ctx) override {
  1678. return CompositeSelect ? true : Source->InitFilters(ctx);
  1679. }
  1680. TNodePtr BuildFilter(TContext& ctx, const TString& label, const TNodePtr& groundNode) override {
  1681. return CompositeSelect ? nullptr : Source->BuildFilter(ctx, label, groundNode);
  1682. }
  1683. bool IsCompositeSource() const override {
  1684. return true;
  1685. }
  1686. ISource* GetCompositeSource() override {
  1687. return CompositeSelect;
  1688. }
  1689. bool CalculateGroupingHint(TContext& ctx, const TVector<TString>& columns, ui64& hint) const override {
  1690. Y_UNUSED(ctx);
  1691. hint = 0;
  1692. if (GroupByColumns.empty()) {
  1693. for (const auto& groupByNode: GroupBy) {
  1694. auto namePtr = groupByNode->GetColumnName();
  1695. YQL_ENSURE(namePtr);
  1696. GroupByColumns.insert(*namePtr);
  1697. }
  1698. }
  1699. for (const auto& column: columns) {
  1700. hint <<= 1;
  1701. if (!GroupByColumns.contains(column)) {
  1702. hint += 1;
  1703. }
  1704. }
  1705. return true;
  1706. }
  1707. void FinishColumns() override {
  1708. Source->FinishColumns();
  1709. }
  1710. TMaybe<bool> AddColumn(TContext& ctx, TColumnNode& column) override {
  1711. return Source->AddColumn(ctx, column);
  1712. }
  1713. TPtr DoClone() const final {
  1714. return Holder.Get() ? new TNestedProxySource(Pos, CloneContainer(GroupBy), Holder->CloneSource()) :
  1715. new TNestedProxySource(CompositeSelect, CloneContainer(GroupBy));
  1716. }
  1717. private:
  1718. TCompositeSelect* CompositeSelect;
  1719. TSourcePtr Holder;
  1720. TVector<TNodePtr> GroupBy;
  1721. mutable TSet<TString> GroupByColumns;
  1722. };
  1723. TSourcePtr BuildSelectCore(
  1724. TContext& ctx,
  1725. TPosition pos,
  1726. TSourcePtr source,
  1727. const TVector<TNodePtr>& groupByExpr,
  1728. const TVector<TNodePtr>& groupBy,
  1729. const TVector<TSortSpecificationPtr>& orderBy,
  1730. TNodePtr having,
  1731. TWinSpecs&& winSpecs,
  1732. THoppingWindowSpecPtr hoppingWindowSpec,
  1733. TVector<TNodePtr>&& terms,
  1734. bool distinct,
  1735. TVector<TNodePtr>&& without,
  1736. bool stream,
  1737. const TWriteSettings& settings
  1738. ) {
  1739. if (groupBy.empty() || !groupBy.front()->ContentListPtr()) {
  1740. return new TSelectCore(pos, std::move(source), groupByExpr, groupBy, orderBy, having, winSpecs, hoppingWindowSpec, terms, distinct, without, stream, settings);
  1741. }
  1742. if (groupBy.size() == 1) {
  1743. /// actualy no big idea to use grouping function in this case (result allways 0)
  1744. auto contentPtr = groupBy.front()->ContentListPtr();
  1745. TSourcePtr proxySource = new TNestedProxySource(pos, *contentPtr, std::move(source));
  1746. return BuildSelectCore(ctx, pos, std::move(proxySource), groupByExpr, *contentPtr, orderBy, having, std::move(winSpecs),
  1747. hoppingWindowSpec, std::move(terms), distinct, std::move(without), stream, settings);
  1748. }
  1749. /// \todo some smart merge logic, generalize common part of grouping (expr, flatten, etc)?
  1750. TIntrusivePtr<TCompositeSelect> compositeSelect = new TCompositeSelect(pos, std::move(source), settings);
  1751. size_t totalGroups = 0;
  1752. TVector<TSourcePtr> subselects;
  1753. TSet<TString> groupingCols;
  1754. for (auto& grouping: groupBy) {
  1755. auto contentPtr = grouping->ContentListPtr();
  1756. TVector<TNodePtr> cache(1, nullptr);
  1757. if (!contentPtr) {
  1758. cache[0] = grouping;
  1759. contentPtr = &cache;
  1760. }
  1761. for (const auto& elem: *contentPtr) {
  1762. auto namePtr = elem->GetColumnName();
  1763. if (namePtr && !namePtr->empty()) {
  1764. groupingCols.insert(*namePtr);
  1765. }
  1766. }
  1767. TSourcePtr proxySource = new TNestedProxySource(compositeSelect.Get(), *contentPtr);
  1768. if (!subselects.empty()) {
  1769. /// clone terms for others usage
  1770. TVector<TNodePtr> termsCopy;
  1771. for (const auto& term: terms) {
  1772. termsCopy.emplace_back(term->Clone());
  1773. }
  1774. std::swap(terms, termsCopy);
  1775. }
  1776. totalGroups += contentPtr->size();
  1777. TSelectCore* selectCore = new TSelectCore(pos, std::move(proxySource), CloneContainer(groupByExpr),
  1778. *contentPtr, orderBy, SafeClone(having), winSpecs, hoppingWindowSpec, terms, distinct, without, stream, settings);
  1779. subselects.emplace_back(selectCore);
  1780. }
  1781. if (totalGroups > ctx.PragmaGroupByLimit) {
  1782. ctx.Error(pos) << "Unable to GROUP BY more than " << ctx.PragmaGroupByLimit << " groups, you try use " << totalGroups << " groups";
  1783. return nullptr;
  1784. }
  1785. compositeSelect->SetSubselects(std::move(subselects), std::move(groupingCols));
  1786. return compositeSelect;
  1787. }
  1788. class TUnionAll: public IRealSource {
  1789. public:
  1790. TUnionAll(TPosition pos, TVector<TSourcePtr>&& sources)
  1791. : IRealSource(pos)
  1792. , Sources(std::move(sources))
  1793. {
  1794. }
  1795. const TColumns* GetColumns() const override {
  1796. return IRealSource::GetColumns();
  1797. }
  1798. void GetInputTables(TTableList& tableList) const override {
  1799. for (auto& x : Sources) {
  1800. x->GetInputTables(tableList);
  1801. }
  1802. ISource::GetInputTables(tableList);
  1803. }
  1804. bool DoInit(TContext& ctx, ISource* src) override {
  1805. for (auto& s: Sources) {
  1806. s->UseAsInner();
  1807. if (!s->Init(ctx, src)) {
  1808. return false;
  1809. }
  1810. auto c = s->GetColumns();
  1811. Y_DEBUG_ABORT_UNLESS(c);
  1812. Columns.Merge(*c);
  1813. }
  1814. return true;
  1815. }
  1816. TNodePtr Build(TContext& ctx) override {
  1817. auto res = Y("UnionAll");
  1818. for (auto& s: Sources) {
  1819. auto input = s->Build(ctx);
  1820. if (!input) {
  1821. return nullptr;
  1822. }
  1823. res->Add(input);
  1824. }
  1825. return res;
  1826. }
  1827. bool IsStream() const override {
  1828. for (auto& s: Sources) {
  1829. if (!s->IsStream()) {
  1830. return false;
  1831. }
  1832. }
  1833. return true;
  1834. }
  1835. TNodePtr DoClone() const final {
  1836. return MakeIntrusive<TUnionAll>(Pos, CloneContainer(Sources));
  1837. }
  1838. private:
  1839. TVector<TSourcePtr> Sources;
  1840. };
  1841. TSourcePtr BuildUnionAll(TPosition pos, TVector<TSourcePtr>&& sources) {
  1842. return new TUnionAll(pos, std::move(sources));
  1843. }
  1844. class TOverWindowSource: public IProxySource {
  1845. public:
  1846. TOverWindowSource(TPosition pos, const TString& windowName, ISource* origSource)
  1847. : IProxySource(pos, origSource)
  1848. , WindowName(windowName)
  1849. {
  1850. Source->SetLabel(origSource->GetLabel());
  1851. }
  1852. TString MakeLocalName(const TString& name) override {
  1853. return Source->MakeLocalName(name);
  1854. }
  1855. void AddTmpWindowColumn(const TString& column) override {
  1856. return Source->AddTmpWindowColumn(column);
  1857. }
  1858. bool AddAggregation(TContext& ctx, TAggregationPtr aggr) override {
  1859. if (aggr->IsOverWindow()) {
  1860. return Source->AddAggregationOverWindow(ctx, WindowName, aggr);
  1861. }
  1862. return Source->AddAggregation(ctx, aggr);
  1863. }
  1864. bool AddFuncOverWindow(TContext& ctx, TNodePtr expr) override {
  1865. return Source->AddFuncOverWindow(ctx, WindowName, expr);
  1866. }
  1867. bool IsOverWindowSource() const override {
  1868. return true;
  1869. }
  1870. TMaybe<bool> AddColumn(TContext& ctx, TColumnNode& column) override {
  1871. return Source->AddColumn(ctx, column);
  1872. }
  1873. TNodePtr Build(TContext& ctx) override {
  1874. Y_UNUSED(ctx);
  1875. Y_ABORT("Unexpected call");
  1876. }
  1877. const TString* GetWindowName() const override {
  1878. return &WindowName;
  1879. }
  1880. TWindowSpecificationPtr FindWindowSpecification(TContext& ctx, const TString& windowName) const override {
  1881. return Source->FindWindowSpecification(ctx, windowName);
  1882. }
  1883. TNodePtr DoClone() const final {
  1884. return {};
  1885. }
  1886. private:
  1887. const TString WindowName;
  1888. };
  1889. TSourcePtr BuildOverWindowSource(TPosition pos, const TString& windowName, ISource* origSource) {
  1890. return new TOverWindowSource(pos, windowName, origSource);
  1891. }
  1892. class TSkipTakeNode final: public TAstListNode {
  1893. public:
  1894. TSkipTakeNode(TPosition pos, const TNodePtr& skip, const TNodePtr& take)
  1895. : TAstListNode(pos)
  1896. {
  1897. TNodePtr select(AstNode("select"));
  1898. if (skip) {
  1899. select = Y("Skip", select, skip);
  1900. }
  1901. Add("let", "select", Y("Take", select, take));
  1902. }
  1903. TPtr DoClone() const final {
  1904. return {};
  1905. }
  1906. };
  1907. TNodePtr BuildSkipTake(TPosition pos, const TNodePtr& skip, const TNodePtr& take) {
  1908. return new TSkipTakeNode(pos, skip, take);
  1909. }
  1910. class TSelect: public IProxySource {
  1911. public:
  1912. TSelect(TPosition pos, TSourcePtr source, TNodePtr skipTake)
  1913. : IProxySource(pos, source.Get())
  1914. , Source(std::move(source))
  1915. , SkipTake(skipTake)
  1916. {}
  1917. bool DoInit(TContext& ctx, ISource* src) override {
  1918. Source->SetLabel(Label);
  1919. if (AsInner) {
  1920. Source->UseAsInner();
  1921. }
  1922. if (!Source->Init(ctx, src)) {
  1923. return false;
  1924. }
  1925. src = Source.Get();
  1926. if (SkipTake) {
  1927. ctx.PushBlockShortcuts();
  1928. FakeSource.Reset(new TFakeSource(SkipTake->GetPos()));
  1929. if (!SkipTake->Init(ctx, FakeSource.Get())) {
  1930. return false;
  1931. }
  1932. SkipTakeGround = ctx.GroundBlockShortcuts(ctx.Pos());
  1933. }
  1934. return true;
  1935. }
  1936. TNodePtr Build(TContext& ctx) override {
  1937. auto input = Source->Build(ctx);
  1938. if (!input) {
  1939. return nullptr;
  1940. }
  1941. const auto label = "select";
  1942. auto block(Y(Y("let", label, input)));
  1943. auto sortNode = Source->BuildSort(ctx, label);
  1944. if (sortNode) {
  1945. if (AsInner && !SkipTake) {
  1946. ctx.Warning(sortNode->GetPos(), TIssuesIds::YQL_ORDER_BY_WITHOUT_LIMIT_IN_SUBQUERY) << "ORDER BY without LIMIT in subquery will be ignored";
  1947. } else {
  1948. block = L(block, sortNode);
  1949. }
  1950. }
  1951. if (SkipTake) {
  1952. if (SkipTakeGround) {
  1953. block = L(block, SkipTake->Y("let", "select", SkipTake->Y("block", SkipTake->Q(
  1954. SkipTake->L(SkipTake->L(SkipTakeGround, SkipTake), Y("return", "select"))))));
  1955. } else {
  1956. block = L(block, SkipTake);
  1957. }
  1958. }
  1959. block = L(block, Y("return", label));
  1960. return Y("block", Q(block));
  1961. }
  1962. bool IsSelect() const override {
  1963. return Source->IsSelect();
  1964. }
  1965. TPtr DoClone() const final {
  1966. return MakeIntrusive<TSelect>(Pos, Source->CloneSource(), SafeClone(SkipTake));
  1967. }
  1968. protected:
  1969. TSourcePtr Source;
  1970. TNodePtr SkipTake;
  1971. TNodePtr SkipTakeGround;
  1972. THolder<TFakeSource> FakeSource;
  1973. };
  1974. TSourcePtr BuildSelect(TPosition pos, TSourcePtr source, TNodePtr skipTake) {
  1975. return new TSelect(pos, std::move(source), skipTake);
  1976. }
  1977. class TSelectResultNode final: public TAstListNode {
  1978. public:
  1979. TSelectResultNode(TPosition pos, TSourcePtr source, bool writeResult, bool inSubquery)
  1980. : TAstListNode(pos)
  1981. , Source(std::move(source))
  1982. , WriteResult(writeResult)
  1983. , InSubquery(inSubquery)
  1984. {
  1985. YQL_ENSURE(Source, "Invalid source node");
  1986. FakeSource = BuildFakeSource(pos);
  1987. }
  1988. bool IsSelect() const override {
  1989. return true;
  1990. }
  1991. bool DoInit(TContext& ctx, ISource* src) override {
  1992. if (!Source->Init(ctx, src)) {
  1993. return false;
  1994. }
  1995. src = Source.Get();
  1996. TTableList tableList;
  1997. Source->GetInputTables(tableList);
  1998. TNodePtr node(BuildInputTables(Pos, tableList, InSubquery));
  1999. if (!node->Init(ctx, src)) {
  2000. return false;
  2001. }
  2002. TSet<TString> clusters;
  2003. for (auto& it: tableList) {
  2004. clusters.insert(it.Cluster);
  2005. }
  2006. auto writeSettings = src->GetWriteSettings();
  2007. bool asRef = ctx.PragmaRefSelect;
  2008. bool asAutoRef = true;
  2009. if (ctx.PragmaSampleSelect) {
  2010. asRef = false;
  2011. asAutoRef = false;
  2012. }
  2013. auto settings = Y(Q(Y(Q("type"))));
  2014. if (writeSettings.Discard) {
  2015. settings = L(settings, Q(Y(Q("discard"))));
  2016. }
  2017. if (!writeSettings.Label.Empty()) {
  2018. auto labelNode = writeSettings.Label.Build();
  2019. if (!writeSettings.Label.GetLiteral()) {
  2020. labelNode = Y("EvaluateAtom", labelNode);
  2021. }
  2022. ctx.PushBlockShortcuts();
  2023. if (!labelNode->Init(ctx, FakeSource.Get())) {
  2024. return false;
  2025. }
  2026. labelNode = ctx.GroundBlockShortcutsForExpr(labelNode);
  2027. settings = L(settings, Q(Y(Q("label"), labelNode)));
  2028. }
  2029. if (asRef) {
  2030. settings = L(settings, Q(Y(Q("ref"))));
  2031. } else if (asAutoRef) {
  2032. settings = L(settings, Q(Y(Q("autoref"))));
  2033. }
  2034. auto columns = Source->GetColumns();
  2035. if (columns && !columns->All && !(columns->QualifiedAll && ctx.SimpleColumns)) {
  2036. auto list = Y();
  2037. for (auto& c: columns->List) {
  2038. if (c.EndsWith('*')) {
  2039. list = L(list, Q(Y(Q("prefix"), BuildQuotedAtom(Pos, c.substr(0, c.size() - 1)))));
  2040. } else {
  2041. list = L(list, BuildQuotedAtom(Pos, c));
  2042. }
  2043. }
  2044. settings = L(settings, Q(Y(Q("columns"), Q(list))));
  2045. }
  2046. if (ctx.ResultRowsLimit > 0) {
  2047. settings = L(settings, Q(Y(Q("take"), Q(ToString(ctx.ResultRowsLimit)))));
  2048. }
  2049. auto output = Source->Build(ctx);
  2050. if (!output) {
  2051. return false;
  2052. }
  2053. node = L(node, Y("let", "output", output));
  2054. if (WriteResult) {
  2055. if (!Source->IsOrdered() && ctx.UseUnordered(*Source)) {
  2056. node = L(node, Y("let", "output", Y("Unordered", "output")));
  2057. }
  2058. auto writeResult(BuildWriteResult(Pos, "output", settings, clusters));
  2059. if (!writeResult->Init(ctx, src)) {
  2060. return false;
  2061. }
  2062. node = L(node, Y("let", "world", writeResult));
  2063. node = L(node, Y("return", "world"));
  2064. } else {
  2065. node = L(node, Y("return", "output"));
  2066. }
  2067. Add("block", Q(node));
  2068. return true;
  2069. }
  2070. TPtr DoClone() const final {
  2071. return {};
  2072. }
  2073. protected:
  2074. TSourcePtr Source;
  2075. const bool WriteResult;
  2076. const bool InSubquery;
  2077. TSourcePtr FakeSource;
  2078. };
  2079. TNodePtr BuildSelectResult(TPosition pos, TSourcePtr source, bool writeResult, bool inSubquery) {
  2080. return new TSelectResultNode(pos, std::move(source), writeResult, inSubquery);
  2081. }
  2082. } // namespace NSQLTranslationV0