query.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. #include "node.h"
  2. #include "context.h"
  3. #include <yql/essentials/ast/yql_type_string.h>
  4. #include <yql/essentials/core/sql_types/yql_callable_names.h>
  5. #include <yql/essentials/providers/common/provider/yql_provider_names.h>
  6. #include <library/cpp/charset/ci_string.h>
  7. #include <util/digest/fnv.h>
  8. using namespace NYql;
  9. namespace NSQLTranslationV0 {
  10. class TUniqueTableKey: public ITableKeys {
  11. public:
  12. TUniqueTableKey(TPosition pos, const TString& cluster, const TDeferredAtom& name, const TString& view)
  13. : ITableKeys(pos)
  14. , Cluster(cluster)
  15. , Name(name)
  16. , View(view)
  17. , Full(name.GetRepr())
  18. {
  19. if (!View.empty()) {
  20. Full += ":" + View;
  21. }
  22. }
  23. const TString* GetTableName() const override {
  24. return Name.GetLiteral() ? &Full : nullptr;
  25. }
  26. TNodePtr BuildKeys(TContext& ctx, ITableKeys::EBuildKeysMode mode) override {
  27. if (View == "@") {
  28. auto key = Y("TempTable", Name.Build());
  29. return key;
  30. }
  31. bool tableScheme = mode == ITableKeys::EBuildKeysMode::CREATE;
  32. if (tableScheme && !View.empty()) {
  33. ctx.Error(Pos) << "Table view can not be created with CREATE TABLE clause";
  34. return nullptr;
  35. }
  36. auto path = ctx.GetPrefixedPath(Cluster, Name);
  37. if (!path) {
  38. return nullptr;
  39. }
  40. auto key = Y("Key", Q(Y(Q(tableScheme ? "tablescheme" : "table"), Y("String", path))));
  41. if (!View.empty()) {
  42. key = L(key, Q(Y(Q("view"), Y("String", BuildQuotedAtom(Pos, View)))));
  43. }
  44. if (mode == ITableKeys::EBuildKeysMode::INPUT &&
  45. IsQueryMode(ctx.Settings.Mode) &&
  46. ctx.GetClusterProvider(Cluster).GetRef() != "kikimr" &&
  47. ctx.GetClusterProvider(Cluster).GetRef() != "rtmr") {
  48. key = Y("MrTableConcat", key);
  49. }
  50. return key;
  51. }
  52. private:
  53. TString Cluster;
  54. TDeferredAtom Name;
  55. TString View;
  56. TString Full;
  57. };
  58. TNodePtr BuildTableKey(TPosition pos, const TString& cluster, const TDeferredAtom& name, const TString& view) {
  59. return new TUniqueTableKey(pos, cluster, name, view);
  60. }
  61. class TPrepTableKeys: public ITableKeys {
  62. public:
  63. TPrepTableKeys(TPosition pos, const TString& cluster, const TString& func, const TVector<TTableArg>& args)
  64. : ITableKeys(pos)
  65. , Cluster(cluster)
  66. , Func(func)
  67. , Args(args)
  68. {
  69. }
  70. void ExtractTableName(TContext&ctx, TTableArg& arg) {
  71. MakeTableFromExpression(ctx, arg.Expr, arg.Id);
  72. }
  73. TNodePtr BuildKeys(TContext& ctx, ITableKeys::EBuildKeysMode mode) override {
  74. if (mode == ITableKeys::EBuildKeysMode::CREATE) {
  75. // TODO: allow creation of multiple tables
  76. ctx.Error(Pos) << "Mutiple table creation is not implemented yet";
  77. return nullptr;
  78. }
  79. TCiString func(Func);
  80. if (func == "concat_strict") {
  81. auto tuple = Y();
  82. for (auto& arg: Args) {
  83. ExtractTableName(ctx, arg);
  84. TNodePtr key;
  85. if (arg.HasAt) {
  86. key = Y("TempTable", arg.Id.Build());
  87. } else {
  88. auto path = ctx.GetPrefixedPath(Cluster, arg.Id);
  89. if (!path) {
  90. return nullptr;
  91. }
  92. key = Y("Key", Q(Y(Q("table"), Y("String", path))));
  93. if (!arg.View.empty()) {
  94. key = L(key, Q(Y(Q("view"), Y("String", BuildQuotedAtom(Pos, arg.View)))));
  95. }
  96. }
  97. tuple = L(tuple, key);
  98. }
  99. return Q(tuple);
  100. }
  101. else if (func == "concat") {
  102. auto concat = Y("MrTableConcat");
  103. for (auto& arg : Args) {
  104. ExtractTableName(ctx, arg);
  105. TNodePtr key;
  106. if (arg.HasAt) {
  107. key = Y("TempTable", arg.Id.Build());
  108. } else {
  109. auto path = ctx.GetPrefixedPath(Cluster, arg.Id);
  110. if (!path) {
  111. return nullptr;
  112. }
  113. key = Y("Key", Q(Y(Q("table"), Y("String", path))));
  114. if (!arg.View.empty()) {
  115. key = L(key, Q(Y(Q("view"), Y("String", BuildQuotedAtom(Pos, arg.View)))));
  116. }
  117. }
  118. concat = L(concat, key);
  119. }
  120. return concat;
  121. }
  122. else if (func == "range" || func == "range_strict" || func == "like" || func == "like_strict" ||
  123. func == "regexp" || func == "regexp_strict" || func == "filter" || func == "filter_strict") {
  124. bool isRange = func.StartsWith("range");
  125. bool isFilter = func.StartsWith("filter");
  126. size_t minArgs = isRange ? 1 : 2;
  127. size_t maxArgs = isRange ? 5 : 4;
  128. if (Args.size() < minArgs || Args.size() > maxArgs) {
  129. ctx.Error(Pos) << Func << " requires from " << minArgs << " to " << maxArgs << " arguments, but got: " << Args.size();
  130. return nullptr;
  131. }
  132. for (ui32 index=0; index < Args.size(); ++index) {
  133. auto& arg = Args[index];
  134. if (arg.HasAt) {
  135. ctx.Error(Pos) << "Temporary tables are not supported here";
  136. return nullptr;
  137. }
  138. if (!arg.View.empty()) {
  139. TStringBuilder sb;
  140. sb << "Use the last argument of " << Func << " to specify a VIEW." << Endl;
  141. if (isRange) {
  142. sb << "Possible arguments are: prefix, from, to, suffix, view." << Endl;
  143. } else if (isFilter) {
  144. sb << "Possible arguments are: prefix, filtering callable, suffix, view." << Endl;
  145. } else {
  146. sb << "Possible arguments are: prefix, pattern, suffix, view." << Endl;
  147. }
  148. sb << "Pass [] to arguments you want to skip.";
  149. ctx.Error(Pos) << sb;
  150. return nullptr;
  151. }
  152. if (!func.StartsWith("filter") || index != 1) {
  153. ExtractTableName(ctx, arg);
  154. }
  155. }
  156. auto path = ctx.GetPrefixedPath(Cluster, Args[0].Id);
  157. if (!path) {
  158. return nullptr;
  159. }
  160. auto range = Y(func.EndsWith("_strict") ? "MrTableRangeStrict" : "MrTableRange", path);
  161. TNodePtr predicate;
  162. TDeferredAtom suffix;
  163. if (func.StartsWith("range")) {
  164. TDeferredAtom min;
  165. TDeferredAtom max;
  166. if (Args.size() > 1) {
  167. min = Args[1].Id;
  168. }
  169. if (Args.size() > 2) {
  170. max = Args[2].Id;
  171. }
  172. if (Args.size() > 3) {
  173. suffix = Args[3].Id;
  174. }
  175. if (min.Empty() && max.Empty()) {
  176. predicate = BuildLambda(Pos, Y("item"), Y("Bool", Q("true")));
  177. }
  178. else {
  179. auto minPred = !min.Empty() ? Y(">=", "item", Y("String", min.Build())) : nullptr;
  180. auto maxPred = !max.Empty() ? Y("<=", "item", Y("String", max.Build())) : nullptr;
  181. if (!minPred) {
  182. predicate = BuildLambda(Pos, Y("item"), maxPred);
  183. } else if (!maxPred) {
  184. predicate = BuildLambda(Pos, Y("item"), minPred);
  185. } else {
  186. predicate = BuildLambda(Pos, Y("item"), Y("And", minPred, maxPred));
  187. }
  188. }
  189. } else {
  190. if (Args.size() > 2) {
  191. suffix = Args[2].Id;
  192. }
  193. if (func.StartsWith("regexp")) {
  194. auto pattern = Args[1].Id;
  195. auto udf = Y("Udf", Q("Pcre.BacktrackingGrep"), Y("String", pattern.Build()));
  196. predicate = BuildLambda(Pos, Y("item"), Y("Apply", udf, "item"));
  197. } else if (func.StartsWith("like")) {
  198. auto pattern = Args[1].Id;
  199. auto convertedPattern = Y("Apply", Y("Udf", Q("Re2.PatternFromLike")),
  200. Y("String", pattern.Build()));
  201. auto udf = Y("Udf", Q("Re2.Match"), Q(Y(convertedPattern, Y("Null"))));
  202. predicate = BuildLambda(Pos, Y("item"), Y("Apply", udf, "item"));
  203. } else {
  204. predicate = BuildLambda(Pos, Y("item"), Y("Apply", Args[1].Expr, "item"));
  205. }
  206. }
  207. range = L(range, predicate);
  208. range = L(range, suffix.Build() ? suffix.Build() : BuildQuotedAtom(Pos, ""));
  209. auto key = Y("Key", Q(Y(Q("table"), range)));
  210. if (Args.size() == maxArgs) {
  211. const auto& lastArg = Args.back();
  212. if (!lastArg.View.empty()) {
  213. ctx.Error(Pos) << Func << " requires that view should be set as last argument";
  214. return nullptr;
  215. }
  216. if (!lastArg.Id.Empty()) {
  217. key = L(key, Q(Y(Q("view"), Y("String", lastArg.Id.Build()))));
  218. }
  219. }
  220. return key;
  221. } else if (func == "each" || func == "each_strict") {
  222. auto each = Y(func == "each" ? "MrTableEach" : "MrTableEachStrict");
  223. for (auto& arg : Args) {
  224. if (arg.HasAt) {
  225. ctx.Error(Pos) << "Temporary tables are not supported here";
  226. return nullptr;
  227. }
  228. auto type = Y("ListType", Y("DataType", Q("String")));
  229. auto key = Y("Key", Q(Y(Q("table"), Y("EvaluateExpr",
  230. Y("EnsureType", Y("Coalesce", arg.Expr, Y("List", type)), type)))));
  231. if (!arg.View.empty()) {
  232. key = L(key, Q(Y(Q("view"), Y("String", BuildQuotedAtom(Pos, arg.View)))));
  233. }
  234. each = L(each, key);
  235. }
  236. return each;
  237. }
  238. else if (func == "folder") {
  239. size_t minArgs = 1;
  240. size_t maxArgs = 2;
  241. if (Args.size() < minArgs || Args.size() > maxArgs) {
  242. ctx.Error(Pos) << Func << " requires from " << minArgs << " to " << maxArgs << " arguments, but found: " << Args.size();
  243. return nullptr;
  244. }
  245. for (ui32 index = 0; index < Args.size(); ++index) {
  246. auto& arg = Args[index];
  247. if (arg.HasAt) {
  248. ctx.Error(Pos) << "Temporary tables are not supported here";
  249. return nullptr;
  250. }
  251. if (!arg.View.empty()) {
  252. ctx.Error(Pos) << Func << " doesn't supports views";
  253. return nullptr;
  254. }
  255. ExtractTableName(ctx, arg);
  256. }
  257. auto folder = Y("MrFolder");
  258. folder = L(folder, Args[0].Id.Build());
  259. folder = L(folder, Args.size() > 1 ? Args[1].Id.Build() : BuildQuotedAtom(Pos, ""));
  260. return folder;
  261. }
  262. ctx.Error(Pos) << "Unknown table name preprocessor: " << Func;
  263. return nullptr;
  264. }
  265. private:
  266. TString Cluster;
  267. TString Func;
  268. TVector<TTableArg> Args;
  269. };
  270. TNodePtr BuildTableKeys(TPosition pos, const TString& cluster, const TString& func, const TVector<TTableArg>& args) {
  271. return new TPrepTableKeys(pos, cluster, func, args);
  272. }
  273. class TInputOptions final: public TAstListNode {
  274. public:
  275. TInputOptions(TPosition pos, const TVector<TString>& hints)
  276. : TAstListNode(pos)
  277. , Hints(hints)
  278. {
  279. }
  280. bool DoInit(TContext& ctx, ISource* src) override {
  281. Y_UNUSED(src);
  282. TSet<TString> used;
  283. for (auto& hint: Hints) {
  284. TMaybe<TIssue> normalizeError = NormalizeName(Pos, hint);
  285. if (!normalizeError.Empty()) {
  286. ctx.Error() << normalizeError->GetMessage();
  287. ctx.IncrementMonCounter("sql_errors", "NormalizeHintError");
  288. return false;
  289. }
  290. TNodePtr option;
  291. if (used.insert(hint).second) {
  292. option = Y(BuildQuotedAtom(Pos, hint));
  293. }
  294. if (option) {
  295. Nodes.push_back(Q(option));
  296. }
  297. }
  298. return true;
  299. }
  300. TPtr DoClone() const final {
  301. return {};
  302. }
  303. private:
  304. TVector<TString> Hints;
  305. };
  306. TNodePtr BuildInputOptions(TPosition pos, const TVector<TString>& hints) {
  307. if (hints.empty()) {
  308. return nullptr;
  309. }
  310. return new TInputOptions(pos, hints);
  311. }
  312. class TInputTablesNode final: public TAstListNode {
  313. public:
  314. TInputTablesNode(TPosition pos, const TTableList& tables, bool inSubquery)
  315. : TAstListNode(pos)
  316. , Tables(tables)
  317. , InSubquery(inSubquery)
  318. {}
  319. bool DoInit(TContext& ctx, ISource* src) override {
  320. THashSet<TString> tables;
  321. for (auto& tr: Tables) {
  322. if (!tables.insert(tr.RefName).second) {
  323. continue;
  324. }
  325. if (!tr.Check(ctx)) {
  326. return false;
  327. }
  328. auto tableKeys = tr.Keys->GetTableKeys();
  329. auto keys = tableKeys->BuildKeys(ctx, ITableKeys::EBuildKeysMode::INPUT);
  330. ctx.PushBlockShortcuts();
  331. if (!keys || !keys->Init(ctx, src)) {
  332. return false;
  333. }
  334. keys = ctx.GroundBlockShortcutsForExpr(keys);
  335. auto service = tr.ServiceName(ctx);
  336. auto fields = Y("Void");
  337. auto source = Y("DataSource", BuildQuotedAtom(Pos, service), BuildQuotedAtom(Pos, tr.Cluster));
  338. auto options = tr.Options ? Q(tr.Options) : Q(Y());
  339. Add(Y("let", "x", keys->Y(TString(ReadName), "world", source, keys, fields, options)));
  340. if (service != YtProviderName) {
  341. if (InSubquery) {
  342. ctx.Error() << "Using of system '" << service << "' is not allowed in SUBQUERY";
  343. return false;
  344. }
  345. Add(Y("let", "world", Y(TString(LeftName), "x")));
  346. }
  347. Add(Y("let", tr.RefName, Y(TString(RightName), "x")));
  348. ctx.UsedClusters.insert(tr.Cluster);
  349. }
  350. return TAstListNode::DoInit(ctx, src);
  351. }
  352. TPtr DoClone() const final {
  353. return {};
  354. }
  355. private:
  356. TTableList Tables;
  357. const bool InSubquery;
  358. };
  359. TNodePtr BuildInputTables(TPosition pos, const TTableList& tables, bool inSubquery) {
  360. return new TInputTablesNode(pos, tables, inSubquery);
  361. }
  362. class TCreateTableNode final: public TAstListNode {
  363. public:
  364. TCreateTableNode(TPosition pos, const TTableRef& tr, const TVector<TColumnSchema>& columns,
  365. const TVector<TIdentifier>& pkColumns, const TVector<TIdentifier>& partitionByColumns,
  366. const TVector<std::pair<TIdentifier, bool>>& orderByColumns)
  367. : TAstListNode(pos)
  368. , Table(tr)
  369. , Columns(columns)
  370. , PkColumns(pkColumns)
  371. , PartitionByColumns(partitionByColumns)
  372. , OrderByColumns(orderByColumns)
  373. {}
  374. bool DoInit(TContext& ctx, ISource* src) override {
  375. if (!Table.Check(ctx)) {
  376. return false;
  377. }
  378. auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
  379. ctx.PushBlockShortcuts();
  380. if (!keys || !keys->Init(ctx, src)) {
  381. return false;
  382. }
  383. keys = ctx.GroundBlockShortcutsForExpr(keys);
  384. if (!PkColumns.empty() || !PartitionByColumns.empty() || !OrderByColumns.empty()) {
  385. THashSet<TString> columnsSet;
  386. for (auto& col : Columns) {
  387. columnsSet.insert(col.Name);
  388. }
  389. for (auto& keyColumn : PkColumns) {
  390. if (!columnsSet.contains(keyColumn.Name)) {
  391. ctx.Error(keyColumn.Pos) << "Undefined column: " << keyColumn.Name;
  392. return false;
  393. }
  394. }
  395. for (auto& keyColumn : PartitionByColumns) {
  396. if (!columnsSet.contains(keyColumn.Name)) {
  397. ctx.Error(keyColumn.Pos) << "Undefined column: " << keyColumn.Name;
  398. return false;
  399. }
  400. }
  401. for (auto& keyColumn : OrderByColumns) {
  402. if (!columnsSet.contains(keyColumn.first.Name)) {
  403. ctx.Error(keyColumn.first.Pos) << "Undefined column: " << keyColumn.first.Name;
  404. return false;
  405. }
  406. }
  407. }
  408. auto columns = Y();
  409. for (auto& col: Columns) {
  410. auto type = ParseType(TypeByAlias(col.Type, !col.IsTypeString), *ctx.Pool, ctx.Issues, col.Pos);
  411. if (!type) {
  412. return false;
  413. }
  414. Y_ASSERT(type->IsList());
  415. Y_ASSERT(type->GetChildrenCount() > 1);
  416. auto typeName = type->GetChild(0);
  417. Y_ASSERT(typeName->IsAtom());
  418. if (typeName->GetContent() == "OptionalType") {
  419. ctx.Error(col.Pos) << "CREATE TABLE clause requires non-optional column types in scheme";
  420. return false;
  421. }
  422. if (col.Nullable) {
  423. type = TAstNode::NewList(
  424. col.Pos,
  425. *ctx.Pool,
  426. TAstNode::NewLiteralAtom(
  427. col.Pos,
  428. "OptionalType",
  429. *ctx.Pool
  430. ),
  431. type
  432. );
  433. }
  434. columns = L(columns, Q(Y(BuildQuotedAtom(Pos, col.Name), AstNode(type))));
  435. }
  436. auto opts = Y();
  437. if (Table.Options) {
  438. if (!Table.Options->Init(ctx, src)) {
  439. return false;
  440. }
  441. opts = Table.Options;
  442. }
  443. opts = L(opts, Q(Y(Q("mode"), Q("create"))));
  444. opts = L(opts, Q(Y(Q("columns"), Q(columns))));
  445. const auto serviceName = to_lower(Table.ServiceName(ctx));
  446. if (serviceName == RtmrProviderName) {
  447. if (!PkColumns.empty() && !PartitionByColumns.empty()) {
  448. ctx.Error() << "Only one of PRIMARY KEY or PARTITION BY constraints may be specified";
  449. return false;
  450. }
  451. } else {
  452. if (!PartitionByColumns.empty() || !OrderByColumns.empty()) {
  453. ctx.Error() << "PARTITION BY and ORDER BY are supported only for " << RtmrProviderName << " provider";
  454. return false;
  455. }
  456. }
  457. if (!PkColumns.empty()) {
  458. auto primaryKey = Y();
  459. for (auto& col : PkColumns) {
  460. primaryKey = L(primaryKey, BuildQuotedAtom(col.Pos, col.Name));
  461. }
  462. opts = L(opts, Q(Y(Q("primarykey"), Q(primaryKey))));
  463. if (!OrderByColumns.empty()) {
  464. ctx.Error() << "PRIMARY KEY cannot be used with ORDER BY, use PARTITION BY instead";
  465. return false;
  466. }
  467. } else {
  468. if (!PartitionByColumns.empty()) {
  469. auto partitionBy = Y();
  470. for (auto& col : PartitionByColumns) {
  471. partitionBy = L(partitionBy, BuildQuotedAtom(col.Pos, col.Name));
  472. }
  473. opts = L(opts, Q(Y(Q("partitionby"), Q(partitionBy))));
  474. }
  475. if (!OrderByColumns.empty()) {
  476. auto orderBy = Y();
  477. for (auto& col : OrderByColumns) {
  478. orderBy = L(orderBy, Q(Y(BuildQuotedAtom(col.first.Pos, col.first.Name), col.second ? Q("1") : Q("0"))));
  479. }
  480. opts = L(opts, Q(Y(Q("orderby"), Q(orderBy))));
  481. }
  482. }
  483. Add("block", Q(Y(
  484. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.ServiceName(ctx)), BuildQuotedAtom(Pos, Table.Cluster))),
  485. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  486. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  487. )));
  488. ctx.UsedClusters.insert(Table.Cluster);
  489. return TAstListNode::DoInit(ctx, src);
  490. }
  491. TPtr DoClone() const final {
  492. return {};
  493. }
  494. private:
  495. TTableRef Table;
  496. TVector<TColumnSchema> Columns;
  497. TVector<TIdentifier> PkColumns;
  498. TVector<TIdentifier> PartitionByColumns;
  499. TVector<std::pair<TIdentifier, bool>> OrderByColumns; // column, is desc?
  500. };
  501. TNodePtr BuildCreateTable(TPosition pos, const TTableRef& tr, const TVector<TColumnSchema>& columns,
  502. const TVector<TIdentifier>& pkColumns, const TVector<TIdentifier>& partitionByColumns,
  503. const TVector<std::pair<TIdentifier, bool>>& orderByColumns)
  504. {
  505. return new TCreateTableNode(pos, tr, columns, pkColumns, partitionByColumns, orderByColumns);
  506. }
  507. class TAlterTableNode final: public TAstListNode {
  508. public:
  509. TAlterTableNode(TPosition pos, const TTableRef& tr, const TVector<TColumnSchema>& columns, EAlterTableIntentnt intent)
  510. : TAstListNode(pos)
  511. , Table(tr)
  512. , Columns(columns)
  513. , Intent(intent)
  514. {}
  515. bool DoInit(TContext& ctx, ISource* src) override {
  516. if (!Table.Check(ctx)) {
  517. return false;
  518. }
  519. auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
  520. ctx.PushBlockShortcuts();
  521. if (!keys || !keys->Init(ctx, src)) {
  522. return false;
  523. }
  524. keys = ctx.GroundBlockShortcutsForExpr(keys);
  525. auto actions = Y();
  526. if (Intent == EAlterTableIntentnt::DropColumn) {
  527. auto columns = Y();
  528. for (auto& col : Columns) {
  529. columns = L(columns, BuildQuotedAtom(Pos, col.Name));
  530. }
  531. actions = L(actions, Q(Y(Q("dropColumns"), Q(columns))));
  532. } else {
  533. auto columns = Y();
  534. for (auto& col: Columns) {
  535. auto type = ParseType(TypeByAlias(col.Type, !col.IsTypeString), *ctx.Pool, ctx.Issues, col.Pos);
  536. if (!type) {
  537. return false;
  538. }
  539. Y_ASSERT(type->IsList());
  540. Y_ASSERT(type->GetChildrenCount() > 1);
  541. auto typeName = type->GetChild(0);
  542. Y_ASSERT(typeName->IsAtom());
  543. if (typeName->GetContent() == "OptionalType") {
  544. ctx.Error(col.Pos) << "ALTER TABLE clause requires non-optional column types in scheme";
  545. return false;
  546. }
  547. if (col.Nullable) {
  548. type = TAstNode::NewList(
  549. col.Pos,
  550. *ctx.Pool,
  551. TAstNode::NewLiteralAtom(
  552. col.Pos,
  553. "OptionalType",
  554. *ctx.Pool
  555. ),
  556. type
  557. );
  558. }
  559. columns = L(columns, Q(Y(BuildQuotedAtom(Pos, col.Name), AstNode(type))));
  560. }
  561. actions = L(actions, Q(Y(Q("addColumns"), Q(columns))));
  562. }
  563. auto opts = Y();
  564. opts = L(opts, Q(Y(Q("mode"), Q("alter"))));
  565. opts = L(opts, Q(Y(Q("actions"), Q(actions))));
  566. Add("block", Q(Y(
  567. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.ServiceName(ctx)), BuildQuotedAtom(Pos, Table.Cluster))),
  568. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  569. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  570. )));
  571. ctx.UsedClusters.insert(Table.Cluster);
  572. return TAstListNode::DoInit(ctx, src);
  573. }
  574. TPtr DoClone() const final {
  575. return {};
  576. }
  577. private:
  578. TTableRef Table;
  579. TVector<TColumnSchema> Columns;
  580. EAlterTableIntentnt Intent;
  581. };
  582. TNodePtr BuildAlterTable(TPosition pos, const TTableRef& tr, const TVector<TColumnSchema>& columns, EAlterTableIntentnt intent)
  583. {
  584. return new TAlterTableNode(pos, tr, columns, intent);
  585. }
  586. class TDropTableNode final: public TAstListNode {
  587. public:
  588. TDropTableNode(TPosition pos, const TTableRef& tr)
  589. : TAstListNode(pos)
  590. , Table(tr)
  591. {
  592. FakeSource = BuildFakeSource(pos);
  593. }
  594. bool DoInit(TContext& ctx, ISource* src) override {
  595. Y_UNUSED(src);
  596. if (!Table.Check(ctx)) {
  597. return false;
  598. }
  599. auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::DROP);
  600. ctx.PushBlockShortcuts();
  601. if (!keys || !keys->Init(ctx, FakeSource.Get())) {
  602. return false;
  603. }
  604. keys = ctx.GroundBlockShortcutsForExpr(keys);
  605. Add("block", Q(Y(
  606. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.ServiceName(ctx)), BuildQuotedAtom(Pos, Table.Cluster))),
  607. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(Y(Q(Y(Q("mode"), Q("drop"))))))),
  608. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  609. )));
  610. ctx.UsedClusters.insert(Table.Cluster);
  611. return TAstListNode::DoInit(ctx, FakeSource.Get());
  612. }
  613. TPtr DoClone() const final {
  614. return {};
  615. }
  616. private:
  617. TTableRef Table;
  618. TSourcePtr FakeSource;
  619. };
  620. TNodePtr BuildDropTable(TPosition pos, const TTableRef& tr) {
  621. return new TDropTableNode(pos, tr);
  622. }
  623. static const TMap<EWriteColumnMode, TString> columnModeToStrMapMR {
  624. {EWriteColumnMode::Default, ""},
  625. {EWriteColumnMode::Insert, "append"},
  626. {EWriteColumnMode::Renew, "renew"}
  627. };
  628. static const TMap<EWriteColumnMode, TString> columnModeToStrMapStat {
  629. {EWriteColumnMode::Upsert, "upsert"}
  630. };
  631. static const TMap<EWriteColumnMode, TString> columnModeToStrMapKikimr {
  632. {EWriteColumnMode::Default, ""},
  633. {EWriteColumnMode::Insert, "insert_abort"},
  634. {EWriteColumnMode::InsertOrAbort, "insert_abort"},
  635. {EWriteColumnMode::InsertOrIgnore, "insert_ignore"},
  636. {EWriteColumnMode::InsertOrRevert, "insert_revert"},
  637. {EWriteColumnMode::Upsert, "upsert"},
  638. {EWriteColumnMode::Replace, "replace"},
  639. {EWriteColumnMode::Update, "update"},
  640. {EWriteColumnMode::UpdateOn, "update_on"},
  641. {EWriteColumnMode::Delete, "delete"},
  642. {EWriteColumnMode::DeleteOn, "delete_on"},
  643. };
  644. class TWriteTableNode final: public TAstListNode {
  645. public:
  646. TWriteTableNode(TPosition pos, const TString& label, const TTableRef& table, EWriteColumnMode mode,
  647. TNodePtr options)
  648. : TAstListNode(pos)
  649. , Label(label)
  650. , Table(table)
  651. , Mode(mode)
  652. , Options(options)
  653. {}
  654. bool DoInit(TContext& ctx, ISource* src) override {
  655. if (!Table.Check(ctx)) {
  656. return false;
  657. }
  658. auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::WRITE);
  659. ctx.PushBlockShortcuts();
  660. if (!keys || !keys->Init(ctx, src)) {
  661. return false;
  662. }
  663. keys = ctx.GroundBlockShortcutsForExpr(keys);
  664. const auto serviceName = to_lower(Table.ServiceName(ctx));
  665. auto getModesMap = [] (const TString& serviceName) -> const TMap<EWriteColumnMode, TString>& {
  666. if (serviceName == KikimrProviderName) {
  667. return columnModeToStrMapKikimr;
  668. } else if (serviceName == StatProviderName) {
  669. return columnModeToStrMapStat;
  670. } else {
  671. return columnModeToStrMapMR;
  672. }
  673. };
  674. auto options = Y();
  675. if (Options) {
  676. if (!Options->Init(ctx, src)) {
  677. return false;
  678. }
  679. options = L(Options);
  680. }
  681. if (Mode != EWriteColumnMode::Default) {
  682. auto modeStr = getModesMap(serviceName).FindPtr(Mode);
  683. options->Add(Q(Y(Q("mode"), Q(modeStr ? *modeStr : "unsupported"))));
  684. }
  685. Add("block", Q((Y(
  686. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.ServiceName(ctx)), BuildQuotedAtom(Pos, Table.Cluster))),
  687. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Label, Q(options))),
  688. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  689. ))));
  690. ctx.UsedClusters.insert(Table.Cluster);
  691. return TAstListNode::DoInit(ctx, src);
  692. }
  693. TPtr DoClone() const final {
  694. return {};
  695. }
  696. private:
  697. TString Label;
  698. TTableRef Table;
  699. EWriteColumnMode Mode;
  700. TNodePtr Options;
  701. };
  702. TNodePtr BuildWriteTable(TPosition pos, const TString& label, const TTableRef& table, EWriteColumnMode mode, TNodePtr options)
  703. {
  704. return new TWriteTableNode(pos, label, table, mode, std::move(options));
  705. }
  706. class TClustersSinkOperationBase: public TAstListNode {
  707. protected:
  708. TClustersSinkOperationBase(TPosition pos, const TSet<TString>& clusters)
  709. : TAstListNode(pos)
  710. , Clusters(clusters) {}
  711. virtual TPtr ProduceOperation(TContext& ctx, const TString& sinkName, const TString& service) = 0;
  712. bool DoInit(TContext& ctx, ISource* src) override {
  713. auto block(Y());
  714. auto clusters = &Clusters;
  715. if (Clusters.empty()) {
  716. clusters = &ctx.UsedClusters;
  717. }
  718. if (clusters->empty() && !ctx.CurrCluster.empty()) {
  719. clusters->insert(ctx.CurrCluster);
  720. }
  721. for (auto& cluster: *clusters) {
  722. TString normalizedClusterName;
  723. auto service = ctx.GetClusterProvider(cluster, normalizedClusterName);
  724. if (!service) {
  725. ctx.Error(ctx.Pos()) << "Unknown cluster: " << cluster;
  726. return false;
  727. }
  728. auto sinkName = normalizedClusterName + "_sink";
  729. auto op = ProduceOperation(ctx, sinkName, *service);
  730. if (!op) {
  731. return false;
  732. }
  733. block = L(block, Y("let", sinkName, Y("DataSink", BuildQuotedAtom(Pos, *service), BuildQuotedAtom(Pos, normalizedClusterName))));
  734. block = L(block, op);
  735. }
  736. clusters->clear();
  737. block = L(block, Y("return", "world"));
  738. Add("block", Q(block));
  739. return TAstListNode::DoInit(ctx, src);
  740. }
  741. TPtr DoClone() const final {
  742. return {};
  743. }
  744. private:
  745. TSet<TString> Clusters;
  746. };
  747. class TCommitClustersNode: public TClustersSinkOperationBase {
  748. public:
  749. TCommitClustersNode(TPosition pos, const TSet<TString>& clusters)
  750. : TClustersSinkOperationBase(pos, clusters) {}
  751. TPtr ProduceOperation(TContext& ctx, const TString& sinkName, const TString& service) override {
  752. Y_UNUSED(ctx);
  753. Y_UNUSED(service);
  754. return Y("let", "world", Y(TString(CommitName), "world", sinkName));
  755. }
  756. };
  757. TNodePtr BuildCommitClusters(TPosition pos, const TSet<TString>& clusters) {
  758. return new TCommitClustersNode(pos, clusters);
  759. }
  760. class TRollbackClustersNode: public TClustersSinkOperationBase {
  761. public:
  762. TRollbackClustersNode(TPosition pos, const TSet<TString>& clusters)
  763. : TClustersSinkOperationBase(pos, clusters) {}
  764. TPtr ProduceOperation(TContext& ctx, const TString& sinkName, const TString& service) override {
  765. if (service != KikimrProviderName) {
  766. ctx.Error(ctx.Pos()) << "ROLLBACK isn't supported for provider: " << TStringBuf(service);
  767. return nullptr;
  768. }
  769. return Y("let", "world", Y(TString(CommitName), "world", sinkName, Q(Y(Q(Y(Q("mode"), Q("rollback")))))));
  770. }
  771. };
  772. TNodePtr BuildRollbackClusters(TPosition pos, const TSet<TString>& clusters) {
  773. return new TRollbackClustersNode(pos, clusters);
  774. }
  775. class TWriteResultNode final: public TAstListNode {
  776. public:
  777. TWriteResultNode(TPosition pos, const TString& label, TNodePtr settings, const TSet<TString>& clusters)
  778. : TAstListNode(pos)
  779. , Label(label)
  780. , Settings(settings)
  781. , CommitClusters(BuildCommitClusters(Pos, clusters))
  782. {}
  783. bool DoInit(TContext& ctx, ISource* src) override {
  784. auto block(Y(
  785. Y("let", "result_sink", Y("DataSink", Q(TString(ResultProviderName)))),
  786. Y("let", "world", Y(TString(WriteName), "world", "result_sink", Y("Key"), Label, Q(Settings)))
  787. ));
  788. if (ctx.PragmaAutoCommit) {
  789. block = L(block, Y("let", "world", CommitClusters));
  790. }
  791. block = L(block, Y("return", Y(TString(CommitName), "world", "result_sink")));
  792. Add("block", Q(block));
  793. return TAstListNode::DoInit(ctx, src);
  794. }
  795. TPtr DoClone() const final {
  796. return {};
  797. }
  798. private:
  799. TString Label;
  800. TNodePtr Settings;
  801. TNodePtr CommitClusters;
  802. };
  803. TNodePtr BuildWriteResult(TPosition pos, const TString& label, TNodePtr settings, const TSet<TString>& clusters) {
  804. return new TWriteResultNode(pos, label, settings, clusters);
  805. }
  806. class TYqlProgramNode: public TAstListNode {
  807. public:
  808. TYqlProgramNode(TPosition pos, const TVector<TNodePtr>& blocks, bool topLevel)
  809. : TAstListNode(pos)
  810. , Blocks(blocks)
  811. , TopLevel(topLevel)
  812. {}
  813. bool DoInit(TContext& ctx, ISource* src) override {
  814. bool hasError = false;
  815. if (TopLevel) {
  816. for (auto& var: ctx.Variables) {
  817. if (!var.second->Init(ctx, src)) {
  818. hasError = true;
  819. continue;
  820. }
  821. Add(Y("declare", var.first, var.second));
  822. }
  823. for (const auto& lib : ctx.Libraries) {
  824. Add(Y("library",
  825. new TAstAtomNodeImpl(Pos, lib, TNodeFlags::ArbitraryContent)));
  826. }
  827. Add(Y("import", "aggregate_module", BuildQuotedAtom(Pos, "/lib/yql/aggregate.yqls")));
  828. Add(Y("import", "window_module", BuildQuotedAtom(Pos, "/lib/yql/window.yqls")));
  829. for (const auto& module : ctx.Settings.ModuleMapping) {
  830. TString moduleName(module.first + "_module");
  831. moduleName.to_lower();
  832. Add(Y("import", moduleName, BuildQuotedAtom(Pos, module.second)));
  833. }
  834. for (const auto& moduleAlias : ctx.ImportModuleAliases) {
  835. Add(Y("import", moduleAlias.second, BuildQuotedAtom(Pos, moduleAlias.first)));
  836. }
  837. for (const auto& x : ctx.SimpleUdfs) {
  838. Add(Y("let", x.second, Y("Udf", BuildQuotedAtom(Pos, x.first))));
  839. }
  840. for (auto& nodes: ctx.NamedNodes) {
  841. if (src || ctx.Exports.contains(nodes.first)) {
  842. auto& node = nodes.second.top();
  843. ctx.PushBlockShortcuts();
  844. if (!node->Init(ctx, src)) {
  845. hasError = true;
  846. continue;
  847. }
  848. node = ctx.GroundBlockShortcutsForExpr(node);
  849. // Some constants may be used directly by YQL code and need to be translated without reference from SQL AST
  850. if (node->IsConstant() || ctx.Exports.contains(nodes.first)) {
  851. Add(Y("let", BuildAtom(node->GetPos(), nodes.first), node));
  852. }
  853. }
  854. }
  855. if (ctx.Settings.Mode != NSQLTranslation::ESqlMode::LIBRARY) {
  856. auto configSource = Y("DataSource", BuildQuotedAtom(Pos, TString(ConfigProviderName)));
  857. auto resultSink = Y("DataSink", BuildQuotedAtom(Pos, TString(ResultProviderName)));
  858. for (const auto& warningPragma : ctx.WarningPolicy.GetRules()) {
  859. Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  860. BuildQuotedAtom(Pos, "Warning"), BuildQuotedAtom(Pos, warningPragma.GetPattern()),
  861. BuildQuotedAtom(Pos, to_lower(ToString(warningPragma.GetAction()))))));
  862. }
  863. if (ctx.ResultSizeLimit > 0) {
  864. Add(Y("let", "world", Y(TString(ConfigureName), "world", resultSink,
  865. BuildQuotedAtom(Pos, "SizeLimit"), BuildQuotedAtom(Pos, ToString(ctx.ResultSizeLimit)))));
  866. }
  867. if (!ctx.PragmaPullUpFlatMapOverJoin) {
  868. Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  869. BuildQuotedAtom(Pos, "DisablePullUpFlatMapOverJoin"))));
  870. }
  871. }
  872. }
  873. for (auto& block: Blocks) {
  874. if (block->SubqueryAlias()) {
  875. continue;
  876. }
  877. if (!block->Init(ctx, nullptr)) {
  878. hasError = true;
  879. continue;
  880. }
  881. }
  882. for (auto& block: Blocks) {
  883. const auto subqueryAliasPtr = block->SubqueryAlias();
  884. if (subqueryAliasPtr) {
  885. if (block->UsedSubquery()) {
  886. const auto& ref = block->GetLabel();
  887. YQL_ENSURE(!ref.empty());
  888. Add(block);
  889. Add(Y("let", "world", Y("Nth", *subqueryAliasPtr, Q("0"))));
  890. Add(Y("let", ref, Y("Nth", *subqueryAliasPtr, Q("1"))));
  891. }
  892. } else {
  893. const auto& ref = block->GetLabel();
  894. Add(Y("let", ref ? ref : "world", block));
  895. }
  896. }
  897. if (TopLevel) {
  898. if (ctx.UniversalAliases) {
  899. decltype(Nodes) preparedNodes;
  900. preparedNodes.swap(Nodes);
  901. for (auto aliasPair : ctx.UniversalAliases) {
  902. Add(Y("let", aliasPair.first, aliasPair.second));
  903. }
  904. Nodes.insert(Nodes.end(), preparedNodes.begin(), preparedNodes.end());
  905. }
  906. for (const auto& symbol: ctx.Exports) {
  907. Add(Y("export", symbol));
  908. }
  909. }
  910. if (!TopLevel || ctx.Settings.Mode != NSQLTranslation::ESqlMode::LIBRARY) {
  911. Add(Y("return", "world"));
  912. }
  913. return !hasError;
  914. }
  915. TPtr DoClone() const final {
  916. return {};
  917. }
  918. private:
  919. TVector<TNodePtr> Blocks;
  920. const bool TopLevel;
  921. };
  922. TNodePtr BuildQuery(TPosition pos, const TVector<TNodePtr>& blocks, bool topLevel) {
  923. return new TYqlProgramNode(pos, blocks, topLevel);
  924. }
  925. class TPragmaNode final: public INode {
  926. public:
  927. TPragmaNode(TPosition pos, const TString& prefix, const TString& name, const TVector<TDeferredAtom>& values, bool valueDefault)
  928. : INode(pos)
  929. , Prefix(prefix)
  930. , Name(name)
  931. , Values(values)
  932. , ValueDefault(valueDefault)
  933. {
  934. FakeSource = BuildFakeSource(pos);
  935. }
  936. bool DoInit(TContext& ctx, ISource* src) override {
  937. Y_UNUSED(src);
  938. TString serviceName;
  939. TString cluster;
  940. if (std::find(Providers.cbegin(), Providers.cend(), Prefix) != Providers.cend()) {
  941. cluster = "$all";
  942. serviceName = Prefix;
  943. } else {
  944. serviceName = *ctx.GetClusterProvider(Prefix, cluster);
  945. }
  946. auto datasource = Y("DataSource", BuildQuotedAtom(Pos, serviceName));
  947. if (Prefix != ConfigProviderName) {
  948. datasource = L(datasource, BuildQuotedAtom(Pos, cluster));
  949. }
  950. Node = Y();
  951. Node = L(Node, AstNode(TString(ConfigureName)));
  952. Node = L(Node, AstNode(TString(TStringBuf("world"))));
  953. Node = L(Node, datasource);
  954. if (Name == TStringBuf("flags")) {
  955. for (ui32 i = 0; i < Values.size(); ++i) {
  956. Node = L(Node, Values[i].Build());
  957. }
  958. }
  959. else if (Name == TStringBuf("AddFileByUrl") || Name == TStringBuf("AddFolderByUrl") || Name == TStringBuf("ImportUdfs")) {
  960. Node = L(Node, BuildQuotedAtom(Pos, Name));
  961. for (ui32 i = 0; i < Values.size(); ++i) {
  962. Node = L(Node, Values[i].Build());
  963. }
  964. }
  965. else if (Name == TStringBuf("auth")) {
  966. Node = L(Node, BuildQuotedAtom(Pos, "Auth"));
  967. Node = L(Node, Values.empty() ? BuildQuotedAtom(Pos, TString()) : Values.front().Build());
  968. }
  969. else {
  970. Node = L(Node, BuildQuotedAtom(Pos, "Attr"));
  971. Node = L(Node, BuildQuotedAtom(Pos, Name));
  972. if (!ValueDefault) {
  973. Node = L(Node, Values.empty() ? BuildQuotedAtom(Pos, TString()) : Values.front().Build());
  974. }
  975. }
  976. ctx.PushBlockShortcuts();
  977. if (!Node->Init(ctx, FakeSource.Get())) {
  978. return false;
  979. }
  980. Node = ctx.GroundBlockShortcutsForExpr(Node);
  981. return true;
  982. }
  983. TAstNode* Translate(TContext& ctx) const override {
  984. return Node->Translate(ctx);
  985. }
  986. TPtr DoClone() const final {
  987. return {};
  988. }
  989. private:
  990. TString Prefix;
  991. TString Name;
  992. TVector<TDeferredAtom> Values;
  993. bool ValueDefault;
  994. TNodePtr Node;
  995. TSourcePtr FakeSource;
  996. };
  997. TNodePtr BuildPragma(TPosition pos, const TString& prefix, const TString& name, const TVector<TDeferredAtom>& values, bool valueDefault) {
  998. return new TPragmaNode(pos, prefix, name, values, valueDefault);
  999. }
  1000. class TSqlLambda final: public TAstListNode {
  1001. public:
  1002. TSqlLambda(TPosition pos, TVector<TString>&& args, TVector<TNodePtr>&& exprSeq)
  1003. : TAstListNode(pos)
  1004. , Args(args)
  1005. , ExprSeq(exprSeq)
  1006. {
  1007. FakeSource = BuildFakeSource(pos);
  1008. }
  1009. bool DoInit(TContext& ctx, ISource* src) override {
  1010. Y_UNUSED(src);
  1011. for (auto& exprPtr: ExprSeq) {
  1012. ctx.PushBlockShortcuts();
  1013. if (!exprPtr->Init(ctx, FakeSource.Get())) {
  1014. return {};
  1015. }
  1016. const auto label = exprPtr->GetLabel();
  1017. exprPtr = ctx.GroundBlockShortcutsForExpr(exprPtr);
  1018. exprPtr->SetLabel(label);
  1019. }
  1020. YQL_ENSURE(!ExprSeq.empty());
  1021. auto body = Y();
  1022. auto end = ExprSeq.end() - 1;
  1023. for (auto iter = ExprSeq.begin(); iter != end; ++iter) {
  1024. auto exprPtr = *iter;
  1025. const auto& label = exprPtr->GetLabel();
  1026. YQL_ENSURE(label);
  1027. body = L(body, Y("let", label, exprPtr));
  1028. }
  1029. body = Y("block", Q(L(body, Y("return", *end))));
  1030. auto args = Y();
  1031. for (const auto& arg: Args) {
  1032. args = L(args, BuildAtom(GetPos(), arg, NYql::TNodeFlags::Default));
  1033. }
  1034. Add("lambda", Q(args), body);
  1035. return TAstListNode::DoInit(ctx, src);
  1036. }
  1037. TPtr DoClone() const final {
  1038. return {};
  1039. }
  1040. void DoUpdateState() const override {
  1041. State.Set(ENodeState::Const);
  1042. }
  1043. private:
  1044. TVector<TString> Args;
  1045. TVector<TNodePtr> ExprSeq;
  1046. TSourcePtr FakeSource;
  1047. };
  1048. TNodePtr BuildSqlLambda(TPosition pos, TVector<TString>&& args, TVector<TNodePtr>&& exprSeq) {
  1049. return new TSqlLambda(pos, std::move(args), std::move(exprSeq));
  1050. }
  1051. class TEvaluateIf final : public TAstListNode {
  1052. public:
  1053. TEvaluateIf(TPosition pos, TNodePtr predicate, TNodePtr thenNode, TNodePtr elseNode)
  1054. : TAstListNode(pos)
  1055. , Predicate(predicate)
  1056. , ThenNode(thenNode)
  1057. , ElseNode(elseNode)
  1058. {
  1059. FakeSource = BuildFakeSource(pos);
  1060. }
  1061. bool DoInit(TContext& ctx, ISource* src) override {
  1062. ctx.PushBlockShortcuts();
  1063. if (!Predicate->Init(ctx, FakeSource.Get())) {
  1064. return{};
  1065. }
  1066. auto predicate = ctx.GroundBlockShortcutsForExpr(Predicate);
  1067. Add("EvaluateIf!");
  1068. Add("world");
  1069. Add(Y("EvaluateExpr", Y("EnsureType", Y("Coalesce", predicate, Y("Bool", Q("false"))), Y("DataType", Q("Bool")))));
  1070. ctx.PushBlockShortcuts();
  1071. if (!ThenNode->Init(ctx, FakeSource.Get())) {
  1072. return{};
  1073. }
  1074. auto thenNode = ctx.GroundBlockShortcutsForExpr(ThenNode);
  1075. Add(thenNode);
  1076. if (ElseNode) {
  1077. ctx.PushBlockShortcuts();
  1078. if (!ElseNode->Init(ctx, FakeSource.Get())) {
  1079. return{};
  1080. }
  1081. auto elseNode = ctx.GroundBlockShortcutsForExpr(ElseNode);
  1082. Add(elseNode);
  1083. }
  1084. return TAstListNode::DoInit(ctx, src);
  1085. }
  1086. TPtr DoClone() const final {
  1087. return {};
  1088. }
  1089. private:
  1090. TNodePtr Predicate;
  1091. TNodePtr ThenNode;
  1092. TNodePtr ElseNode;
  1093. TSourcePtr FakeSource;
  1094. };
  1095. TNodePtr BuildEvaluateIfNode(TPosition pos, TNodePtr predicate, TNodePtr thenNode, TNodePtr elseNode) {
  1096. return new TEvaluateIf(pos, predicate, thenNode, elseNode);
  1097. }
  1098. class TEvaluateFor final : public TAstListNode {
  1099. public:
  1100. TEvaluateFor(TPosition pos, TNodePtr list, TNodePtr bodyNode, TNodePtr elseNode)
  1101. : TAstListNode(pos)
  1102. , List(list)
  1103. , BodyNode(bodyNode)
  1104. , ElseNode(elseNode)
  1105. {
  1106. FakeSource = BuildFakeSource(pos);
  1107. }
  1108. bool DoInit(TContext& ctx, ISource* src) override {
  1109. ctx.PushBlockShortcuts();
  1110. if (!List->Init(ctx, FakeSource.Get())) {
  1111. return{};
  1112. }
  1113. auto list = ctx.GroundBlockShortcutsForExpr(List);
  1114. Add("EvaluateFor!");
  1115. Add("world");
  1116. Add(Y("EvaluateExpr", list));
  1117. ctx.PushBlockShortcuts();
  1118. if (!BodyNode->Init(ctx, FakeSource.Get())) {
  1119. return{};
  1120. }
  1121. auto bodyNode = ctx.GroundBlockShortcutsForExpr(BodyNode);
  1122. Add(bodyNode);
  1123. if (ElseNode) {
  1124. ctx.PushBlockShortcuts();
  1125. if (!ElseNode->Init(ctx, FakeSource.Get())) {
  1126. return{};
  1127. }
  1128. auto elseNode = ctx.GroundBlockShortcutsForExpr(ElseNode);
  1129. Add(elseNode);
  1130. }
  1131. return TAstListNode::DoInit(ctx, src);
  1132. }
  1133. TPtr DoClone() const final {
  1134. return{};
  1135. }
  1136. private:
  1137. TNodePtr List;
  1138. TNodePtr BodyNode;
  1139. TNodePtr ElseNode;
  1140. TSourcePtr FakeSource;
  1141. };
  1142. TNodePtr BuildEvaluateForNode(TPosition pos, TNodePtr list, TNodePtr bodyNode, TNodePtr elseNode) {
  1143. return new TEvaluateFor(pos, list, bodyNode, elseNode);
  1144. }
  1145. } // namespace NSQLTranslationV0