query.cpp 138 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758
  1. #include "node.h"
  2. #include "context.h"
  3. #include "object_processing.h"
  4. #include <yql/essentials/ast/yql_type_string.h>
  5. #include <yql/essentials/core/sql_types/yql_callable_names.h>
  6. #include <yql/essentials/providers/common/provider/yql_provider_names.h>
  7. #include <library/cpp/charset/ci_string.h>
  8. #include <util/digest/fnv.h>
  9. using namespace NYql;
  10. namespace NSQLTranslationV1 {
  11. bool ValidateView(TPosition pos, TContext& ctx, TStringBuf service, TViewDescription& view) {
  12. if (view.PrimaryFlag && !(service == KikimrProviderName || service == YdbProviderName)) {
  13. ctx.Error(pos) << "primary view is not supported for " << service << " tables";
  14. return false;
  15. }
  16. return true;
  17. }
  18. class TUniqueTableKey: public ITableKeys {
  19. public:
  20. TUniqueTableKey(TPosition pos, const TString& service, const TDeferredAtom& cluster,
  21. const TDeferredAtom& name, const TViewDescription& view)
  22. : ITableKeys(pos)
  23. , Service(service)
  24. , Cluster(cluster)
  25. , Name(name)
  26. , View(view)
  27. , Full(name.GetRepr())
  28. {
  29. if (!View.ViewName.empty()) {
  30. Full += ":" + View.ViewName;
  31. }
  32. }
  33. bool SetPrimaryView(TContext& ctx, TPosition pos) override {
  34. Y_UNUSED(ctx);
  35. Y_UNUSED(pos);
  36. View = {"", true};
  37. return true;
  38. }
  39. bool SetViewName(TContext& ctx, TPosition pos, const TString& view) override {
  40. Y_UNUSED(ctx);
  41. Y_UNUSED(pos);
  42. Full = Name.GetRepr();
  43. View = {view};
  44. if (!View.empty()) {
  45. Full = ":" + View.ViewName;
  46. }
  47. return true;
  48. }
  49. const TString* GetTableName() const override {
  50. return Name.GetLiteral() ? &Full : nullptr;
  51. }
  52. TNodePtr BuildKeys(TContext& ctx, ITableKeys::EBuildKeysMode mode) override {
  53. if (View == TViewDescription{"@"}) {
  54. auto key = Y("TempTable", Name.Build());
  55. return key;
  56. }
  57. bool tableScheme = mode == ITableKeys::EBuildKeysMode::CREATE;
  58. if (tableScheme && !View.empty()) {
  59. ctx.Error(Pos) << "Table view can not be created with CREATE TABLE clause";
  60. return nullptr;
  61. }
  62. auto path = ctx.GetPrefixedPath(Service, Cluster, Name);
  63. if (!path) {
  64. return nullptr;
  65. }
  66. auto key = Y("Key", Q(Y(Q(tableScheme ? "tablescheme" : "table"), Y("String", path))));
  67. key = AddView(key, View);
  68. if (!ValidateView(GetPos(), ctx, Service, View)) {
  69. return nullptr;
  70. }
  71. if (mode == ITableKeys::EBuildKeysMode::INPUT &&
  72. IsQueryMode(ctx.Settings.Mode) &&
  73. Service != KikimrProviderName &&
  74. Service != RtmrProviderName &&
  75. Service != YdbProviderName) {
  76. key = Y("MrTableConcat", key);
  77. }
  78. return key;
  79. }
  80. private:
  81. TString Service;
  82. TDeferredAtom Cluster;
  83. TDeferredAtom Name;
  84. TViewDescription View;
  85. TString Full;
  86. };
  87. TNodePtr BuildTableKey(TPosition pos, const TString& service, const TDeferredAtom& cluster,
  88. const TDeferredAtom& name, const TViewDescription& view) {
  89. return new TUniqueTableKey(pos, service, cluster, name, view);
  90. }
  91. class TTopicKey: public ITableKeys {
  92. public:
  93. TTopicKey(TPosition pos, const TDeferredAtom& cluster, const TDeferredAtom& name)
  94. : ITableKeys(pos)
  95. , Cluster(cluster)
  96. , Name(name)
  97. , Full(name.GetRepr())
  98. {
  99. }
  100. const TString* GetTableName() const override {
  101. return Name.GetLiteral() ? &Full : nullptr;
  102. }
  103. TNodePtr BuildKeys(TContext& ctx, ITableKeys::EBuildKeysMode) override {
  104. const auto path = ctx.GetPrefixedPath(Service, Cluster, Name);
  105. if (!path) {
  106. return nullptr;
  107. }
  108. auto key = Y("Key", Q(Y(Q("topic"), Y("String", path))));
  109. return key;
  110. }
  111. private:
  112. TString Service;
  113. TDeferredAtom Cluster;
  114. TDeferredAtom Name;
  115. TString View;
  116. TString Full;
  117. };
  118. TNodePtr BuildTopicKey(TPosition pos, const TDeferredAtom& cluster, const TDeferredAtom& name) {
  119. return new TTopicKey(pos, cluster, name);
  120. }
  121. static INode::TPtr CreateIndexType(TIndexDescription::EType type, const INode& node) {
  122. switch (type) {
  123. case TIndexDescription::EType::GlobalSync:
  124. return node.Q("syncGlobal");
  125. case TIndexDescription::EType::GlobalAsync:
  126. return node.Q("asyncGlobal");
  127. case TIndexDescription::EType::GlobalSyncUnique:
  128. return node.Q("syncGlobalUnique");
  129. case TIndexDescription::EType::GlobalVectorKmeansTree:
  130. return node.Q("globalVectorKmeansTree");
  131. }
  132. }
  133. enum class ETableSettingsParsingMode {
  134. Create,
  135. Alter
  136. };
  137. static INode::TPtr CreateTableSettings(const TTableSettings& tableSettings, ETableSettingsParsingMode parsingMode, const INode& node) {
  138. // short aliases for member function calls
  139. auto Y = [&node](auto&&... args) { return node.Y(std::forward<decltype(args)>(args)...); };
  140. auto Q = [&node](auto&&... args) { return node.Q(std::forward<decltype(args)>(args)...); };
  141. auto L = [&node](auto&&... args) { return node.L(std::forward<decltype(args)>(args)...); };
  142. auto settings = Y();
  143. if (tableSettings.DataSourcePath) {
  144. settings = L(settings, Q(Y(Q("data_source_path"), tableSettings.DataSourcePath)));
  145. }
  146. if (tableSettings.Location) {
  147. if (tableSettings.Location.IsSet()) {
  148. settings = L(settings, Q(Y(Q("location"), tableSettings.Location.GetValueSet())));
  149. } else {
  150. Y_ENSURE(parsingMode != ETableSettingsParsingMode::Create, "Can't reset LOCATION in create mode");
  151. settings = L(settings, Q(Y(Q("location"))));
  152. }
  153. }
  154. for (const auto& resetableParam : tableSettings.ExternalSourceParameters) {
  155. Y_ENSURE(resetableParam, "Empty parameter");
  156. if (resetableParam.IsSet()) {
  157. const auto& [id, value] = resetableParam.GetValueSet();
  158. settings = L(settings, Q(Y(Q(id.Name), value)));
  159. } else {
  160. Y_ENSURE(parsingMode != ETableSettingsParsingMode::Create,
  161. "Can't reset " << resetableParam.GetValueReset().Name << " in create mode"
  162. );
  163. settings = L(settings, Q(Y(Q(resetableParam.GetValueReset().Name))));
  164. }
  165. }
  166. if (tableSettings.CompactionPolicy) {
  167. settings = L(settings, Q(Y(Q("compactionPolicy"), tableSettings.CompactionPolicy)));
  168. }
  169. if (tableSettings.AutoPartitioningBySize) {
  170. const auto& ref = tableSettings.AutoPartitioningBySize.GetRef();
  171. settings = L(settings, Q(Y(Q("autoPartitioningBySize"), BuildQuotedAtom(ref.Pos, ref.Name))));
  172. }
  173. if (tableSettings.UniformPartitions && parsingMode == ETableSettingsParsingMode::Create) {
  174. settings = L(settings, Q(Y(Q("uniformPartitions"), tableSettings.UniformPartitions)));
  175. }
  176. if (tableSettings.PartitionAtKeys && parsingMode == ETableSettingsParsingMode::Create) {
  177. auto keysDesc = Y();
  178. for (const auto& key : tableSettings.PartitionAtKeys) {
  179. auto columnsDesc = Y();
  180. for (auto column : key) {
  181. columnsDesc = L(columnsDesc, column);
  182. }
  183. keysDesc = L(keysDesc, Q(columnsDesc));
  184. }
  185. settings = L(settings, Q(Y(Q("partitionAtKeys"), Q(keysDesc))));
  186. }
  187. if (tableSettings.PartitionSizeMb) {
  188. settings = L(settings, Q(Y(Q("partitionSizeMb"), tableSettings.PartitionSizeMb)));
  189. }
  190. if (tableSettings.AutoPartitioningByLoad) {
  191. const auto& ref = tableSettings.AutoPartitioningByLoad.GetRef();
  192. settings = L(settings, Q(Y(Q("autoPartitioningByLoad"), BuildQuotedAtom(ref.Pos, ref.Name))));
  193. }
  194. if (tableSettings.MinPartitions) {
  195. settings = L(settings, Q(Y(Q("minPartitions"), tableSettings.MinPartitions)));
  196. }
  197. if (tableSettings.MaxPartitions) {
  198. settings = L(settings, Q(Y(Q("maxPartitions"), tableSettings.MaxPartitions)));
  199. }
  200. if (tableSettings.PartitionCount) {
  201. settings = L(settings, Q(Y(Q("maxPartitions"), tableSettings.PartitionCount)));
  202. settings = L(settings, Q(Y(Q("minPartitions"), tableSettings.PartitionCount)));
  203. }
  204. if (tableSettings.KeyBloomFilter) {
  205. const auto& ref = tableSettings.KeyBloomFilter.GetRef();
  206. settings = L(settings, Q(Y(Q("keyBloomFilter"), BuildQuotedAtom(ref.Pos, ref.Name))));
  207. }
  208. if (tableSettings.ReadReplicasSettings) {
  209. settings = L(settings, Q(Y(Q("readReplicasSettings"), tableSettings.ReadReplicasSettings)));
  210. }
  211. if (const auto& ttl = tableSettings.TtlSettings) {
  212. if (ttl.IsSet()) {
  213. const auto& ttlSettings = ttl.GetValueSet();
  214. auto opts = Y();
  215. opts = L(opts, Q(Y(Q("columnName"), BuildQuotedAtom(ttlSettings.ColumnName.Pos, ttlSettings.ColumnName.Name))));
  216. auto tiersDesc = Y();
  217. for (const auto& tier : ttlSettings.Tiers) {
  218. auto tierDesc = Y();
  219. tierDesc = L(tierDesc, Q(Y(Q("evictionDelay"), tier.EvictionDelay)));
  220. if (tier.StorageName) {
  221. tierDesc = L(tierDesc, Q(Y(Q("storageName"), BuildQuotedAtom(tier.StorageName->Pos, tier.StorageName->Name))));
  222. }
  223. tiersDesc = L(tiersDesc, Q(tierDesc));
  224. }
  225. opts = L(opts, Q(Y(Q("tiers"), Q(tiersDesc))));
  226. if (ttlSettings.ColumnUnit) {
  227. opts = L(opts, Q(Y(Q("columnUnit"), Q(ToString(*ttlSettings.ColumnUnit)))));
  228. }
  229. settings = L(settings, Q(Y(Q("setTtlSettings"), Q(opts))));
  230. } else {
  231. YQL_ENSURE(parsingMode != ETableSettingsParsingMode::Create, "Can't reset TTL settings in create mode");
  232. settings = L(settings, Q(Y(Q("resetTtlSettings"), Q(Y()))));
  233. }
  234. }
  235. if (const auto& tiering = tableSettings.Tiering) {
  236. if (tiering.IsSet()) {
  237. settings = L(settings, Q(Y(Q("setTiering"), tiering.GetValueSet())));
  238. } else {
  239. YQL_ENSURE(parsingMode != ETableSettingsParsingMode::Create, "Can't reset TIERING in create mode");
  240. settings = L(settings, Q(Y(Q("resetTiering"), Q(Y()))));
  241. }
  242. }
  243. if (tableSettings.StoreExternalBlobs) {
  244. const auto& ref = tableSettings.StoreExternalBlobs.GetRef();
  245. settings = L(settings, Q(Y(Q("storeExternalBlobs"), BuildQuotedAtom(ref.Pos, ref.Name))));
  246. }
  247. if (tableSettings.StoreType && parsingMode == ETableSettingsParsingMode::Create) {
  248. const auto& ref = tableSettings.StoreType.GetRef();
  249. settings = L(settings, Q(Y(Q("storeType"), BuildQuotedAtom(ref.Pos, ref.Name))));
  250. }
  251. if (tableSettings.PartitionByHashFunction && parsingMode == ETableSettingsParsingMode::Create) {
  252. settings = L(settings, Q(Y(Q("partitionByHashFunction"), tableSettings.PartitionByHashFunction)));
  253. }
  254. return settings;
  255. }
  256. static INode::TPtr CreateVectorIndexSettings(const TVectorIndexSettings& vectorIndexSettings, const INode& node) {
  257. // short aliases for member function calls
  258. auto Y = [&node](auto&&... args) { return node.Y(std::forward<decltype(args)>(args)...); };
  259. auto Q = [&node](auto&&... args) { return node.Q(std::forward<decltype(args)>(args)...); };
  260. auto L = [&node](auto&&... args) { return node.L(std::forward<decltype(args)>(args)...); };
  261. auto settings = Y();
  262. if (vectorIndexSettings.Distance && vectorIndexSettings.Similarity) {
  263. Y_ENSURE(false, "distance and similarity shouldn't be set at the same time");
  264. } else if (vectorIndexSettings.Distance) {
  265. settings = L(settings, Q(Y(Q("distance"), Q(ToString(*vectorIndexSettings.Distance)))));
  266. } else if (vectorIndexSettings.Similarity) {
  267. settings = L(settings, Q(Y(Q("similarity"), Q(ToString(*vectorIndexSettings.Similarity)))));
  268. } else {
  269. Y_ENSURE(false, "distance or similarity should be set");
  270. }
  271. settings = L(settings, Q(Y(Q("vector_type"), Q(ToString(*vectorIndexSettings.VectorType)))));
  272. settings = L(settings, Q(Y(Q("vector_dimension"), Q(ToString(vectorIndexSettings.VectorDimension)))));
  273. settings = L(settings, Q(Y(Q("clusters"), Q(ToString(vectorIndexSettings.Clusters)))));
  274. settings = L(settings, Q(Y(Q("levels"), Q(ToString(vectorIndexSettings.Levels)))));
  275. return settings;
  276. }
  277. static INode::TPtr CreateIndexDesc(const TIndexDescription& index, ETableSettingsParsingMode parsingMode, const INode& node) {
  278. auto indexColumns = node.Y();
  279. for (const auto& col : index.IndexColumns) {
  280. indexColumns = node.L(indexColumns, BuildQuotedAtom(col.Pos, col.Name));
  281. }
  282. auto dataColumns = node.Y();
  283. for (const auto& col : index.DataColumns) {
  284. dataColumns = node.L(dataColumns, BuildQuotedAtom(col.Pos, col.Name));
  285. }
  286. const auto& indexType = node.Y(node.Q("indexType"), CreateIndexType(index.Type, node));
  287. const auto& indexName = node.Y(node.Q("indexName"), BuildQuotedAtom(index.Name.Pos, index.Name.Name));
  288. auto indexNode = node.Y(
  289. node.Q(indexName),
  290. node.Q(indexType),
  291. node.Q(node.Y(node.Q("indexColumns"), node.Q(indexColumns))),
  292. node.Q(node.Y(node.Q("dataColumns"), node.Q(dataColumns)))
  293. );
  294. if (index.TableSettings.IsSet()) {
  295. const auto& tableSettings = node.Q(node.Y(
  296. node.Q("tableSettings"),
  297. node.Q(CreateTableSettings(index.TableSettings, parsingMode, node))
  298. ));
  299. indexNode = node.L(indexNode, tableSettings);
  300. }
  301. if (const auto* indexSettingsPtr = std::get_if<TVectorIndexSettings>(&index.IndexSettings)) {
  302. const auto& indexSettings = node.Q(node.Y(
  303. node.Q("indexSettings"),
  304. node.Q(CreateVectorIndexSettings(*indexSettingsPtr, node))));
  305. indexNode = node.L(indexNode, indexSettings);
  306. }
  307. return indexNode;
  308. }
  309. static INode::TPtr CreateAlterIndex(const TIndexDescription& index, const INode& node) {
  310. const auto& indexName = node.Y(node.Q("indexName"), BuildQuotedAtom(index.Name.Pos, index.Name.Name));
  311. const auto& tableSettings = node.Y(
  312. node.Q("tableSettings"),
  313. node.Q(CreateTableSettings(index.TableSettings, ETableSettingsParsingMode::Alter, node))
  314. );
  315. return node.Y(
  316. node.Q(indexName),
  317. node.Q(tableSettings)
  318. );
  319. }
  320. static INode::TPtr CreateChangefeedDesc(const TChangefeedDescription& desc, const INode& node) {
  321. auto settings = node.Y();
  322. if (desc.Settings.Mode) {
  323. settings = node.L(settings, node.Q(node.Y(node.Q("mode"), desc.Settings.Mode)));
  324. }
  325. if (desc.Settings.Format) {
  326. settings = node.L(settings, node.Q(node.Y(node.Q("format"), desc.Settings.Format)));
  327. }
  328. if (desc.Settings.InitialScan) {
  329. settings = node.L(settings, node.Q(node.Y(node.Q("initial_scan"), desc.Settings.InitialScan)));
  330. }
  331. if (desc.Settings.VirtualTimestamps) {
  332. settings = node.L(settings, node.Q(node.Y(node.Q("virtual_timestamps"), desc.Settings.VirtualTimestamps)));
  333. }
  334. if (desc.Settings.ResolvedTimestamps) {
  335. settings = node.L(settings, node.Q(node.Y(node.Q("resolved_timestamps"), desc.Settings.ResolvedTimestamps)));
  336. }
  337. if (desc.Settings.RetentionPeriod) {
  338. settings = node.L(settings, node.Q(node.Y(node.Q("retention_period"), desc.Settings.RetentionPeriod)));
  339. }
  340. if (desc.Settings.TopicAutoPartitioning) {
  341. settings = node.L(settings, node.Q(node.Y(node.Q("topic_auto_partitioning"), desc.Settings.TopicAutoPartitioning)));
  342. }
  343. if (desc.Settings.TopicMaxActivePartitions) {
  344. settings = node.L(settings, node.Q(node.Y(node.Q("topic_max_active_partitions"), desc.Settings.TopicMaxActivePartitions)));
  345. }
  346. if (desc.Settings.TopicPartitions) {
  347. settings = node.L(settings, node.Q(node.Y(node.Q("topic_min_active_partitions"), desc.Settings.TopicPartitions)));
  348. }
  349. if (desc.Settings.AwsRegion) {
  350. settings = node.L(settings, node.Q(node.Y(node.Q("aws_region"), desc.Settings.AwsRegion)));
  351. }
  352. if (const auto& sink = desc.Settings.SinkSettings) {
  353. switch (sink->index()) {
  354. case 0: // local
  355. settings = node.L(settings, node.Q(node.Y(node.Q("local"), node.Q(node.Y()))));
  356. break;
  357. default:
  358. YQL_ENSURE(false, "Unexpected sink settings");
  359. }
  360. }
  361. auto state = node.Y();
  362. if (desc.Disable) {
  363. state = node.Q("disable");
  364. }
  365. return node.Y(
  366. node.Q(node.Y(node.Q("name"), BuildQuotedAtom(desc.Name.Pos, desc.Name.Name))),
  367. node.Q(node.Y(node.Q("settings"), node.Q(settings))),
  368. node.Q(node.Y(node.Q("state"), node.Q(state)))
  369. );
  370. }
  371. class TPrepTableKeys: public ITableKeys {
  372. public:
  373. TPrepTableKeys(TPosition pos, const TString& service, const TDeferredAtom& cluster,
  374. const TString& func, const TVector<TTableArg>& args)
  375. : ITableKeys(pos)
  376. , Service(service)
  377. , Cluster(cluster)
  378. , Func(func)
  379. , Args(args)
  380. {
  381. }
  382. void ExtractTableName(TContext&ctx, TTableArg& arg) {
  383. MakeTableFromExpression(Pos, ctx, arg.Expr, arg.Id);
  384. }
  385. TNodePtr BuildKeys(TContext& ctx, ITableKeys::EBuildKeysMode mode) override {
  386. if (mode == ITableKeys::EBuildKeysMode::CREATE) {
  387. // TODO: allow creation of multiple tables
  388. ctx.Error(Pos) << "Mutiple table creation is not implemented yet";
  389. return nullptr;
  390. }
  391. TCiString func(Func);
  392. if (func != "object" && func != "walkfolders") {
  393. for (auto& arg: Args) {
  394. if (arg.Expr->GetLabel()) {
  395. ctx.Error(Pos) << "Named arguments are not supported for table function " << to_upper(Func);
  396. return nullptr;
  397. }
  398. }
  399. }
  400. if (func == "concat_strict") {
  401. auto tuple = Y();
  402. for (auto& arg: Args) {
  403. ExtractTableName(ctx, arg);
  404. TNodePtr key;
  405. if (arg.HasAt) {
  406. key = Y("TempTable", arg.Id.Build());
  407. } else {
  408. auto path = ctx.GetPrefixedPath(Service, Cluster, arg.Id);
  409. if (!path) {
  410. return nullptr;
  411. }
  412. key = Y("Key", Q(Y(Q("table"), Y("String", path))));
  413. key = AddView(key, arg.View);
  414. if (!ValidateView(GetPos(), ctx, Service, arg.View)) {
  415. return nullptr;
  416. }
  417. }
  418. tuple = L(tuple, key);
  419. }
  420. return Q(tuple);
  421. }
  422. else if (func == "concat") {
  423. auto concat = Y("MrTableConcat");
  424. for (auto& arg : Args) {
  425. ExtractTableName(ctx, arg);
  426. TNodePtr key;
  427. if (arg.HasAt) {
  428. key = Y("TempTable", arg.Id.Build());
  429. } else {
  430. auto path = ctx.GetPrefixedPath(Service, Cluster, arg.Id);
  431. if (!path) {
  432. return nullptr;
  433. }
  434. key = Y("Key", Q(Y(Q("table"), Y("String", path))));
  435. key = AddView(key, arg.View);
  436. if (!ValidateView(GetPos(), ctx, Service, arg.View)) {
  437. return nullptr;
  438. }
  439. }
  440. concat = L(concat, key);
  441. }
  442. return concat;
  443. }
  444. else if (func == "range" || func == "range_strict" || func == "like" || func == "like_strict" ||
  445. func == "regexp" || func == "regexp_strict" || func == "filter" || func == "filter_strict") {
  446. bool isRange = func.StartsWith("range");
  447. bool isFilter = func.StartsWith("filter");
  448. size_t minArgs = isRange ? 1 : 2;
  449. size_t maxArgs = isRange ? 5 : 4;
  450. if (Args.size() < minArgs || Args.size() > maxArgs) {
  451. ctx.Error(Pos) << Func << " requires from " << minArgs << " to " << maxArgs << " arguments, but got: " << Args.size();
  452. return nullptr;
  453. }
  454. if (ctx.DiscoveryMode) {
  455. ctx.Error(Pos, TIssuesIds::YQL_NOT_ALLOWED_IN_DISCOVERY) << Func << " is not allowed in Discovery mode";
  456. return nullptr;
  457. }
  458. for (ui32 index=0; index < Args.size(); ++index) {
  459. auto& arg = Args[index];
  460. if (arg.HasAt) {
  461. ctx.Error(Pos) << "Temporary tables are not supported here";
  462. return nullptr;
  463. }
  464. if (!arg.View.empty()) {
  465. TStringBuilder sb;
  466. sb << "Use the last argument of " << Func << " to specify a VIEW." << Endl;
  467. if (isRange) {
  468. sb << "Possible arguments are: prefix, from, to, suffix, view." << Endl;
  469. } else if (isFilter) {
  470. sb << "Possible arguments are: prefix, filtering callable, suffix, view." << Endl;
  471. } else {
  472. sb << "Possible arguments are: prefix, pattern, suffix, view." << Endl;
  473. }
  474. sb << "Pass empty string in arguments if you want to skip.";
  475. ctx.Error(Pos) << sb;
  476. return nullptr;
  477. }
  478. if (!func.StartsWith("filter") || index != 1) {
  479. ExtractTableName(ctx, arg);
  480. }
  481. }
  482. auto path = ctx.GetPrefixedPath(Service, Cluster, Args[0].Id);
  483. if (!path) {
  484. return nullptr;
  485. }
  486. auto range = Y(func.EndsWith("_strict") ? "MrTableRangeStrict" : "MrTableRange", path);
  487. TNodePtr predicate;
  488. TDeferredAtom suffix;
  489. if (func.StartsWith("range")) {
  490. TDeferredAtom min;
  491. TDeferredAtom max;
  492. if (Args.size() > 1) {
  493. min = Args[1].Id;
  494. }
  495. if (Args.size() > 2) {
  496. max = Args[2].Id;
  497. }
  498. if (Args.size() > 3) {
  499. suffix = Args[3].Id;
  500. }
  501. if (min.Empty() && max.Empty()) {
  502. predicate = BuildLambda(Pos, Y("item"), Y("Bool", Q("true")));
  503. }
  504. else {
  505. auto minPred = !min.Empty() ? Y(">=", "item", Y("String", min.Build())) : nullptr;
  506. auto maxPred = !max.Empty() ? Y("<=", "item", Y("String", max.Build())) : nullptr;
  507. if (!minPred) {
  508. predicate = BuildLambda(Pos, Y("item"), maxPred);
  509. } else if (!maxPred) {
  510. predicate = BuildLambda(Pos, Y("item"), minPred);
  511. } else {
  512. predicate = BuildLambda(Pos, Y("item"), Y("And", minPred, maxPred));
  513. }
  514. }
  515. } else {
  516. if (Args.size() > 2) {
  517. suffix = Args[2].Id;
  518. }
  519. if (func.StartsWith("regexp")) {
  520. if (!ctx.PragmaRegexUseRe2) {
  521. ctx.Warning(Pos, TIssuesIds::CORE_LEGACY_REGEX_ENGINE) << "Legacy regex engine works incorrectly with unicode. Use PRAGMA RegexUseRe2='true';";
  522. }
  523. auto pattern = Args[1].Id;
  524. auto udf = ctx.PragmaRegexUseRe2 ?
  525. Y("Udf", Q("Re2.Grep"), Q(Y(Y("String", pattern.Build()), Y("Null")))):
  526. Y("Udf", Q("Pcre.BacktrackingGrep"), Y("String", pattern.Build()));
  527. predicate = BuildLambda(Pos, Y("item"), Y("Apply", udf, "item"));
  528. } else if (func.StartsWith("like")) {
  529. auto pattern = Args[1].Id;
  530. auto convertedPattern = Y("Apply", Y("Udf", Q("Re2.PatternFromLike")),
  531. Y("String", pattern.Build()));
  532. auto udf = Y("Udf", Q("Re2.Match"), Q(Y(convertedPattern, Y("Null"))));
  533. predicate = BuildLambda(Pos, Y("item"), Y("Apply", udf, "item"));
  534. } else {
  535. predicate = BuildLambda(Pos, Y("item"), Y("Apply", Args[1].Expr, "item"));
  536. }
  537. }
  538. range = L(range, predicate);
  539. range = L(range, suffix.Build() ? suffix.Build() : BuildQuotedAtom(Pos, ""));
  540. auto key = Y("Key", Q(Y(Q("table"), range)));
  541. if (Args.size() == maxArgs) {
  542. const auto& lastArg = Args.back();
  543. if (!lastArg.View.empty()) {
  544. ctx.Error(Pos) << Func << " requires that view should be set as last argument";
  545. return nullptr;
  546. }
  547. if (!lastArg.Id.Empty()) {
  548. key = L(key, Q(Y(Q("view"), Y("String", lastArg.Id.Build()))));
  549. }
  550. }
  551. return key;
  552. } else if (func == "each" || func == "each_strict") {
  553. auto each = Y(func == "each" ? "MrTableEach" : "MrTableEachStrict");
  554. for (auto& arg : Args) {
  555. if (arg.HasAt) {
  556. ctx.Error(Pos) << "Temporary tables are not supported here";
  557. return nullptr;
  558. }
  559. auto type = Y("ListType", Y("DataType", Q("String")));
  560. auto key = Y("Key", Q(Y(Q("table"), Y("EvaluateExpr",
  561. Y("EnsureType", Y("Coalesce", arg.Expr,
  562. Y("List", type)), type)))));
  563. key = AddView(key, arg.View);
  564. if (!ValidateView(GetPos(), ctx, Service, arg.View)) {
  565. return nullptr;
  566. }
  567. each = L(each, key);
  568. }
  569. if (ctx.PragmaUseTablePrefixForEach) {
  570. TStringBuf prefixPath = ctx.GetPrefixPath(Service, Cluster);
  571. if (prefixPath) {
  572. each = L(each, BuildQuotedAtom(Pos, TString(prefixPath)));
  573. }
  574. }
  575. return each;
  576. }
  577. else if (func == "folder") {
  578. size_t minArgs = 1;
  579. size_t maxArgs = 2;
  580. if (Args.size() < minArgs || Args.size() > maxArgs) {
  581. ctx.Error(Pos) << Func << " requires from " << minArgs << " to " << maxArgs << " arguments, but found: " << Args.size();
  582. return nullptr;
  583. }
  584. if (ctx.DiscoveryMode) {
  585. ctx.Error(Pos, TIssuesIds::YQL_NOT_ALLOWED_IN_DISCOVERY) << Func << " is not allowed in Discovery mode";
  586. return nullptr;
  587. }
  588. for (ui32 index = 0; index < Args.size(); ++index) {
  589. auto& arg = Args[index];
  590. if (arg.HasAt) {
  591. ctx.Error(Pos) << "Temporary tables are not supported here";
  592. return nullptr;
  593. }
  594. if (!arg.View.empty()) {
  595. ctx.Error(Pos) << Func << " doesn't supports views";
  596. return nullptr;
  597. }
  598. ExtractTableName(ctx, arg);
  599. }
  600. auto folder = Y("MrFolder");
  601. folder = L(folder, Args[0].Id.Build());
  602. folder = L(folder, Args.size() > 1 ? Args[1].Id.Build() : BuildQuotedAtom(Pos, ""));
  603. return folder;
  604. }
  605. else if (func == "walkfolders") {
  606. const size_t minPositionalArgs = 1;
  607. const size_t maxPositionalArgs = 2;
  608. size_t positionalArgsCnt = 0;
  609. for (const auto& arg : Args) {
  610. if (!arg.Expr->GetLabel()) {
  611. positionalArgsCnt++;
  612. } else {
  613. break;
  614. }
  615. }
  616. if (positionalArgsCnt < minPositionalArgs || positionalArgsCnt > maxPositionalArgs) {
  617. ctx.Error(Pos) << Func << " requires from " << minPositionalArgs
  618. << " to " << maxPositionalArgs
  619. << " positional arguments, but got: " << positionalArgsCnt;
  620. return nullptr;
  621. }
  622. constexpr auto walkFoldersModuleName = "walk_folders_module";
  623. ctx.RequiredModules.emplace(walkFoldersModuleName, "/lib/yql/walk_folders.yql");
  624. auto& rootFolderArg = Args[0];
  625. if (rootFolderArg.HasAt) {
  626. ctx.Error(Pos) << "Temporary tables are not supported here";
  627. return nullptr;
  628. }
  629. if (!rootFolderArg.View.empty()) {
  630. ctx.Error(Pos) << Func << " doesn't supports views";
  631. return nullptr;
  632. }
  633. ExtractTableName(ctx, rootFolderArg);
  634. const auto initState =
  635. positionalArgsCnt > 1
  636. ? Args[1].Expr
  637. : Y("List", Y("ListType", Y("DataType", Q("String"))));
  638. TNodePtr rootAttributes;
  639. TNodePtr preHandler;
  640. TNodePtr resolveHandler;
  641. TNodePtr diveHandler;
  642. TNodePtr postHandler;
  643. for (auto it = Args.begin() + positionalArgsCnt; it != Args.end(); ++it) {
  644. auto& arg = *it;
  645. const auto label = arg.Expr->GetLabel();
  646. if (label == "RootAttributes") {
  647. ExtractTableName(ctx, arg);
  648. rootAttributes = arg.Id.Build();
  649. }
  650. else if (label == "PreHandler") {
  651. preHandler = arg.Expr;
  652. }
  653. else if (label == "ResolveHandler") {
  654. resolveHandler = arg.Expr;
  655. }
  656. else if (label == "DiveHandler") {
  657. diveHandler = arg.Expr;
  658. }
  659. else if (label == "PostHandler") {
  660. postHandler = arg.Expr;
  661. }
  662. else {
  663. ctx.Warning(Pos, DEFAULT_ERROR) << "Unsupported named argument: "
  664. << label << " in " << Func;
  665. }
  666. }
  667. if (rootAttributes == nullptr) {
  668. rootAttributes = BuildQuotedAtom(Pos, "");
  669. }
  670. if (preHandler != nullptr || postHandler != nullptr) {
  671. const auto makePrePostHandlerType = BuildBind(Pos, walkFoldersModuleName, "MakePrePostHandlersType");
  672. const auto prePostHandlerType = Y("EvaluateType", Y("TypeHandle", Y("Apply", makePrePostHandlerType, Y("TypeOf", initState))));
  673. if (preHandler != nullptr) {
  674. preHandler = Y("Callable", prePostHandlerType, preHandler);
  675. }
  676. if (postHandler != nullptr) {
  677. postHandler = Y("Callable", prePostHandlerType, postHandler);
  678. }
  679. }
  680. if (preHandler == nullptr) {
  681. preHandler = Y("Void");
  682. }
  683. if (postHandler == nullptr) {
  684. postHandler = Y("Void");
  685. }
  686. const auto makeResolveDiveHandlerType = BuildBind(Pos, walkFoldersModuleName, "MakeResolveDiveHandlersType");
  687. const auto resolveDiveHandlerType = Y("EvaluateType", Y("TypeHandle", Y("Apply", makeResolveDiveHandlerType, Y("TypeOf", initState))));
  688. if (resolveHandler == nullptr) {
  689. resolveHandler = BuildBind(Pos, walkFoldersModuleName, "AnyNodeDiveHandler");
  690. }
  691. if (diveHandler == nullptr) {
  692. diveHandler = BuildBind(Pos, walkFoldersModuleName, "AnyNodeDiveHandler");
  693. }
  694. resolveHandler = Y("Callable", resolveDiveHandlerType, resolveHandler);
  695. diveHandler = Y("Callable", resolveDiveHandlerType, diveHandler);
  696. const auto initStateType = Y("EvaluateType", Y("TypeHandle", Y("TypeOf", initState)));
  697. const auto pickledInitState = Y("Pickle", initState);
  698. const auto initPath = rootFolderArg.Id.Build();
  699. return Y("MrWalkFolders", initPath, rootAttributes, pickledInitState, initStateType,
  700. preHandler, resolveHandler, diveHandler, postHandler);
  701. }
  702. else if (func == "tables") {
  703. if (!Args.empty()) {
  704. ctx.Error(Pos) << Func << " doesn't accept arguments";
  705. return nullptr;
  706. }
  707. return L(Y("DataTables"));
  708. }
  709. else if (func == "object") {
  710. const size_t positionalArgs = 2;
  711. auto result = Y("MrObject");
  712. auto settings = Y();
  713. //TVector<TNodePtr> settings;
  714. size_t argc = 0;
  715. for (ui32 index = 0; index < Args.size(); ++index) {
  716. auto& arg = Args[index];
  717. if (arg.HasAt) {
  718. ctx.Error(arg.Expr->GetPos()) << "Temporary tables are not supported here";
  719. return nullptr;
  720. }
  721. if (!arg.View.empty()) {
  722. ctx.Error(Pos) << to_upper(Func) << " doesn't supports views";
  723. return nullptr;
  724. }
  725. if (!arg.Expr->GetLabel()) {
  726. ExtractTableName(ctx, arg);
  727. result = L(result, arg.Id.Build());
  728. ++argc;
  729. } else {
  730. settings = L(settings, Q(Y(BuildQuotedAtom(arg.Expr->GetPos(), arg.Expr->GetLabel()), arg.Expr)));
  731. }
  732. }
  733. if (argc != positionalArgs) {
  734. ctx.Error(Pos) << to_upper(Func) << " requires exacty " << positionalArgs << " positional args, but got " << argc;
  735. return nullptr;
  736. }
  737. result = L(result, Q(settings));
  738. return result;
  739. }
  740. ctx.Error(Pos) << "Unknown table name preprocessor: " << Func;
  741. return nullptr;
  742. }
  743. private:
  744. TString Service;
  745. TDeferredAtom Cluster;
  746. TString Func;
  747. TVector<TTableArg> Args;
  748. };
  749. TNodePtr BuildTableKeys(TPosition pos, const TString& service, const TDeferredAtom& cluster,
  750. const TString& func, const TVector<TTableArg>& args) {
  751. return new TPrepTableKeys(pos, service, cluster, func, args);
  752. }
  753. class TInputOptions final: public TAstListNode {
  754. public:
  755. TInputOptions(TPosition pos, const TTableHints& hints)
  756. : TAstListNode(pos)
  757. , Hints(hints)
  758. {
  759. }
  760. bool DoInit(TContext& ctx, ISource* src) override {
  761. for (auto& hint: Hints) {
  762. TString hintName = hint.first;
  763. TMaybe<TIssue> normalizeError = NormalizeName(Pos, hintName);
  764. if (!normalizeError.Empty()) {
  765. ctx.Error() << normalizeError->GetMessage();
  766. ctx.IncrementMonCounter("sql_errors", "NormalizeHintError");
  767. return false;
  768. }
  769. TNodePtr option = Y(BuildQuotedAtom(Pos, hintName));
  770. for (auto& x : hint.second) {
  771. if (!x->Init(ctx, src)) {
  772. return false;
  773. }
  774. option = L(option, x);
  775. }
  776. Nodes.push_back(Q(option));
  777. }
  778. return true;
  779. }
  780. TPtr DoClone() const final {
  781. return {};
  782. }
  783. private:
  784. TTableHints Hints;
  785. };
  786. TNodePtr BuildInputOptions(TPosition pos, const TTableHints& hints) {
  787. if (hints.empty()) {
  788. return nullptr;
  789. }
  790. return new TInputOptions(pos, hints);
  791. }
  792. class TIntoTableOptions: public TAstListNode {
  793. public:
  794. TIntoTableOptions(TPosition pos, const TVector<TString>& columns, const TTableHints& hints)
  795. : TAstListNode(pos)
  796. , Columns(columns)
  797. , Hints(hints)
  798. {
  799. }
  800. bool DoInit(TContext& ctx, ISource* src) override {
  801. Y_UNUSED(ctx);
  802. Y_UNUSED(src);
  803. TNodePtr options = Y();
  804. for (const auto& column: Columns) {
  805. options->Add(Q(column));
  806. }
  807. if (Columns) {
  808. Add(Q(Y(Q("erase_columns"), Q(options))));
  809. }
  810. for (const auto& hint : Hints) {
  811. TString hintName = hint.first;
  812. TMaybe<TIssue> normalizeError = NormalizeName(Pos, hintName);
  813. if (!normalizeError.Empty()) {
  814. ctx.Error() << normalizeError->GetMessage();
  815. ctx.IncrementMonCounter("sql_errors", "NormalizeHintError");
  816. return false;
  817. }
  818. TNodePtr option = Y(BuildQuotedAtom(Pos, hintName));
  819. for (auto& x : hint.second) {
  820. if (!x->Init(ctx, src)) {
  821. return false;
  822. }
  823. option = L(option, x);
  824. }
  825. Add(Q(option));
  826. }
  827. return true;
  828. }
  829. TNodePtr DoClone() const final {
  830. return new TIntoTableOptions(GetPos(), Columns, CloneContainer(Hints));
  831. }
  832. private:
  833. TVector<TString> Columns;
  834. TTableHints Hints;
  835. };
  836. TNodePtr BuildIntoTableOptions(TPosition pos, const TVector<TString>& eraseColumns, const TTableHints& hints) {
  837. return new TIntoTableOptions(pos, eraseColumns, hints);
  838. }
  839. class TInputTablesNode final: public TAstListNode {
  840. public:
  841. TInputTablesNode(TPosition pos, const TTableList& tables, bool inSubquery, TScopedStatePtr scoped)
  842. : TAstListNode(pos)
  843. , Tables(tables)
  844. , InSubquery(inSubquery)
  845. , Scoped(scoped)
  846. {
  847. }
  848. bool DoInit(TContext& ctx, ISource* src) override {
  849. THashSet<TString> processedTables;
  850. for (auto& tr: Tables) {
  851. if (!processedTables.insert(tr.RefName).second) {
  852. continue;
  853. }
  854. Scoped->UseCluster(tr.Service, tr.Cluster);
  855. auto tableKeys = tr.Keys->GetTableKeys();
  856. auto keys = tableKeys->BuildKeys(ctx, ITableKeys::EBuildKeysMode::INPUT);
  857. if (!keys || !keys->Init(ctx, src)) {
  858. return false;
  859. }
  860. auto fields = Y("Void");
  861. auto source = Y("DataSource", BuildQuotedAtom(Pos, tr.Service), Scoped->WrapCluster(tr.Cluster, ctx));
  862. auto options = tr.Options ? Q(tr.Options) : Q(Y());
  863. Add(Y("let", "x", keys->Y(TString(ReadName), "world", source, keys, fields, options)));
  864. if (IsIn({KikimrProviderName, YdbProviderName}, tr.Service) && InSubquery) {
  865. ctx.Error() << "Using of system '" << tr.Service << "' is not allowed in SUBQUERY";
  866. return false;
  867. }
  868. if (tr.Service != YtProviderName || ctx.Settings.SaveWorldDependencies) {
  869. Add(Y("let", "world", Y(TString(LeftName), "x")));
  870. }
  871. Add(Y("let", tr.RefName, Y(TString(RightName), "x")));
  872. }
  873. return TAstListNode::DoInit(ctx, src);
  874. }
  875. TPtr DoClone() const final {
  876. return {};
  877. }
  878. private:
  879. TTableList Tables;
  880. const bool InSubquery;
  881. TScopedStatePtr Scoped;
  882. };
  883. TNodePtr BuildInputTables(TPosition pos, const TTableList& tables, bool inSubquery, TScopedStatePtr scoped) {
  884. return new TInputTablesNode(pos, tables, inSubquery, scoped);
  885. }
  886. class TCreateTableNode final: public TAstListNode {
  887. public:
  888. TCreateTableNode(TPosition pos, const TTableRef& tr, bool existingOk, bool replaceIfExists, const TCreateTableParameters& params, TSourcePtr values, TScopedStatePtr scoped)
  889. : TAstListNode(pos)
  890. , Table(tr)
  891. , Params(params)
  892. , ExistingOk(existingOk)
  893. , ReplaceIfExists(replaceIfExists)
  894. , Values(std::move(values))
  895. , Scoped(scoped)
  896. {
  897. scoped->UseCluster(Table.Service, Table.Cluster);
  898. }
  899. bool DoInit(TContext& ctx, ISource* src) override {
  900. auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
  901. if (!keys || !keys->Init(ctx, src)) {
  902. return false;
  903. }
  904. if (!Params.PkColumns.empty()
  905. || !Params.PartitionByColumns.empty()
  906. || !Params.OrderByColumns.empty()
  907. || !Params.Indexes.empty()
  908. || !Params.Changefeeds.empty())
  909. {
  910. THashSet<TString> columnsSet;
  911. for (auto& col : Params.Columns) {
  912. columnsSet.insert(col.Name);
  913. }
  914. const bool allowUndefinedColumns = (Values != nullptr) && columnsSet.empty();
  915. THashSet<TString> pkColumns;
  916. for (auto& keyColumn : Params.PkColumns) {
  917. if (!allowUndefinedColumns && !columnsSet.contains(keyColumn.Name)) {
  918. ctx.Error(keyColumn.Pos) << "Undefined column: " << keyColumn.Name;
  919. return false;
  920. }
  921. if (!pkColumns.insert(keyColumn.Name).second) {
  922. ctx.Error(keyColumn.Pos) << "Duplicated column in PK: " << keyColumn.Name;
  923. return false;
  924. }
  925. }
  926. for (auto& keyColumn : Params.PartitionByColumns) {
  927. if (!allowUndefinedColumns && !columnsSet.contains(keyColumn.Name)) {
  928. ctx.Error(keyColumn.Pos) << "Undefined column: " << keyColumn.Name;
  929. return false;
  930. }
  931. }
  932. for (auto& keyColumn : Params.OrderByColumns) {
  933. if (!allowUndefinedColumns && !columnsSet.contains(keyColumn.first.Name)) {
  934. ctx.Error(keyColumn.first.Pos) << "Undefined column: " << keyColumn.first.Name;
  935. return false;
  936. }
  937. }
  938. THashSet<TString> indexNames;
  939. for (const auto& index : Params.Indexes) {
  940. if (!indexNames.insert(index.Name.Name).second) {
  941. ctx.Error(index.Name.Pos) << "Index " << index.Name.Name << " must be defined once";
  942. return false;
  943. }
  944. for (const auto& indexColumn : index.IndexColumns) {
  945. if (!allowUndefinedColumns && !columnsSet.contains(indexColumn.Name)) {
  946. ctx.Error(indexColumn.Pos) << "Undefined column: " << indexColumn.Name;
  947. return false;
  948. }
  949. }
  950. for (const auto& dataColumn : index.DataColumns) {
  951. if (!allowUndefinedColumns && !columnsSet.contains(dataColumn.Name)) {
  952. ctx.Error(dataColumn.Pos) << "Undefined column: " << dataColumn.Name;
  953. return false;
  954. }
  955. }
  956. }
  957. THashSet<TString> cfNames;
  958. for (const auto& cf : Params.Changefeeds) {
  959. if (!cfNames.insert(cf.Name.Name).second) {
  960. ctx.Error(cf.Name.Pos) << "Changefeed " << cf.Name.Name << " must be defined once";
  961. return false;
  962. }
  963. }
  964. }
  965. auto opts = Y();
  966. if (Table.Options) {
  967. if (!Table.Options->Init(ctx, src)) {
  968. return false;
  969. }
  970. opts = Table.Options;
  971. }
  972. if (ExistingOk) {
  973. opts = L(opts, Q(Y(Q("mode"), Q("create_if_not_exists"))));
  974. } else if (ReplaceIfExists) {
  975. opts = L(opts, Q(Y(Q("mode"), Q("create_or_replace"))));
  976. } else {
  977. opts = L(opts, Q(Y(Q("mode"), Q("create"))));
  978. }
  979. THashSet<TString> columnFamilyNames;
  980. if (Params.ColumnFamilies) {
  981. auto columnFamilies = Y();
  982. for (const auto& family : Params.ColumnFamilies) {
  983. if (!columnFamilyNames.insert(family.Name.Name).second) {
  984. ctx.Error(family.Name.Pos) << "Family " << family.Name.Name << " specified more than once";
  985. return false;
  986. }
  987. auto familyDesc = Y();
  988. familyDesc = L(familyDesc, Q(Y(Q("name"), BuildQuotedAtom(family.Name.Pos, family.Name.Name))));
  989. if (family.Data) {
  990. familyDesc = L(familyDesc, Q(Y(Q("data"), family.Data)));
  991. }
  992. if (family.Compression) {
  993. familyDesc = L(familyDesc, Q(Y(Q("compression"), family.Compression)));
  994. }
  995. if (family.CompressionLevel) {
  996. familyDesc = L(familyDesc, Q(Y(Q("compression_level"), family.CompressionLevel)));
  997. }
  998. columnFamilies = L(columnFamilies, Q(familyDesc));
  999. }
  1000. opts = L(opts, Q(Y(Q("columnFamilies"), Q(columnFamilies))));
  1001. }
  1002. auto columns = Y();
  1003. THashSet<TString> columnsWithDefaultValue;
  1004. auto columnsDefaultValueSettings = Y();
  1005. for (auto& col : Params.Columns) {
  1006. auto columnDesc = Y();
  1007. columnDesc = L(columnDesc, BuildQuotedAtom(Pos, col.Name));
  1008. auto type = col.Type;
  1009. if (type) {
  1010. if (col.Nullable) {
  1011. type = Y("AsOptionalType", type);
  1012. }
  1013. columnDesc = L(columnDesc, type);
  1014. auto columnConstraints = Y();
  1015. if (!col.Nullable) {
  1016. columnConstraints = L(columnConstraints, Q(Y(Q("not_null"))));
  1017. }
  1018. if (col.Serial) {
  1019. columnConstraints = L(columnConstraints, Q(Y(Q("serial"))));
  1020. }
  1021. if (col.DefaultExpr) {
  1022. if (!col.DefaultExpr->Init(ctx, src)) {
  1023. return false;
  1024. }
  1025. columnConstraints = L(columnConstraints, Q(Y(Q("default"), col.DefaultExpr)));
  1026. }
  1027. columnDesc = L(columnDesc, Q(Y(Q("columnConstrains"), Q(columnConstraints))));
  1028. auto familiesDesc = Y();
  1029. if (col.Families) {
  1030. for (const auto& family : col.Families) {
  1031. if (columnFamilyNames.find(family.Name) == columnFamilyNames.end()) {
  1032. ctx.Error(family.Pos) << "Unknown family " << family.Name;
  1033. return false;
  1034. }
  1035. familiesDesc = L(familiesDesc, BuildQuotedAtom(family.Pos, family.Name));
  1036. }
  1037. }
  1038. columnDesc = L(columnDesc, Q(familiesDesc));
  1039. }
  1040. columns = L(columns, Q(columnDesc));
  1041. }
  1042. opts = L(opts, Q(Y(Q("columns"), Q(columns))));
  1043. if (!columnsWithDefaultValue.empty()) {
  1044. opts = L(opts, Q(Y(Q("columnsDefaultValues"), Q(columnsDefaultValueSettings))));
  1045. }
  1046. if (Table.Service == RtmrProviderName) {
  1047. if (!Params.PkColumns.empty() && !Params.PartitionByColumns.empty()) {
  1048. ctx.Error() << "Only one of PRIMARY KEY or PARTITION BY constraints may be specified";
  1049. return false;
  1050. }
  1051. } else {
  1052. if (!Params.OrderByColumns.empty()) {
  1053. ctx.Error() << "ORDER BY is supported only for " << RtmrProviderName << " provider";
  1054. return false;
  1055. }
  1056. }
  1057. if (!Params.PkColumns.empty()) {
  1058. auto primaryKey = Y();
  1059. for (auto& col : Params.PkColumns) {
  1060. primaryKey = L(primaryKey, BuildQuotedAtom(col.Pos, col.Name));
  1061. }
  1062. opts = L(opts, Q(Y(Q("primarykey"), Q(primaryKey))));
  1063. if (!Params.OrderByColumns.empty()) {
  1064. ctx.Error() << "PRIMARY KEY cannot be used with ORDER BY, use PARTITION BY instead";
  1065. return false;
  1066. }
  1067. }
  1068. if (!Params.PartitionByColumns.empty()) {
  1069. auto partitionBy = Y();
  1070. for (auto& col : Params.PartitionByColumns) {
  1071. partitionBy = L(partitionBy, BuildQuotedAtom(col.Pos, col.Name));
  1072. }
  1073. opts = L(opts, Q(Y(Q("partitionby"), Q(partitionBy))));
  1074. }
  1075. if (!Params.OrderByColumns.empty()) {
  1076. auto orderBy = Y();
  1077. for (auto& col : Params.OrderByColumns) {
  1078. orderBy = L(orderBy, Q(Y(BuildQuotedAtom(col.first.Pos, col.first.Name), col.second ? Q("1") : Q("0"))));
  1079. }
  1080. opts = L(opts, Q(Y(Q("orderby"), Q(orderBy))));
  1081. }
  1082. for (const auto& index : Params.Indexes) {
  1083. const auto& desc = CreateIndexDesc(index, ETableSettingsParsingMode::Create, *this);
  1084. opts = L(opts, Q(Y(Q("index"), Q(desc))));
  1085. }
  1086. for (const auto& cf : Params.Changefeeds) {
  1087. const auto& desc = CreateChangefeedDesc(cf, *this);
  1088. opts = L(opts, Q(Y(Q("changefeed"), Q(desc))));
  1089. }
  1090. if (Params.TableSettings.IsSet()) {
  1091. opts = L(opts, Q(Y(Q("tableSettings"), Q(
  1092. CreateTableSettings(Params.TableSettings, ETableSettingsParsingMode::Create, *this)
  1093. ))));
  1094. }
  1095. switch (Params.TableType) {
  1096. case ETableType::TableStore:
  1097. opts = L(opts, Q(Y(Q("tableType"), Q("tableStore"))));
  1098. break;
  1099. case ETableType::ExternalTable:
  1100. opts = L(opts, Q(Y(Q("tableType"), Q("externalTable"))));
  1101. break;
  1102. case ETableType::Table:
  1103. break;
  1104. }
  1105. if (Params.Temporary) {
  1106. opts = L(opts, Q(Y(Q("temporary"))));
  1107. }
  1108. TNodePtr node = nullptr;
  1109. if (Values) {
  1110. if (!Values->Init(ctx, nullptr)) {
  1111. return false;
  1112. }
  1113. TTableList tableList;
  1114. Values->GetInputTables(tableList);
  1115. auto valuesSource = Values.Get();
  1116. auto values = Values->Build(ctx);
  1117. if (!Values) {
  1118. return false;
  1119. }
  1120. TNodePtr inputTables(BuildInputTables(Pos, tableList, false, Scoped));
  1121. if (!inputTables->Init(ctx, valuesSource)) {
  1122. return false;
  1123. }
  1124. node = inputTables;
  1125. node = L(node, Y("let", "values", values));
  1126. } else {
  1127. node = Y(Y("let", "values", Y("Void")));
  1128. }
  1129. auto write = Y(
  1130. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.Service), Scoped->WrapCluster(Table.Cluster, ctx))),
  1131. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, "values", Q(opts))),
  1132. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1133. );
  1134. node = L(node, Y("let", "world", Y("block", Q(write))));
  1135. node = L(node, Y("return", "world"));
  1136. Add("block", Q(node));
  1137. return TAstListNode::DoInit(ctx, src);
  1138. }
  1139. TPtr DoClone() const final {
  1140. return {};
  1141. }
  1142. private:
  1143. const TTableRef Table;
  1144. const TCreateTableParameters Params;
  1145. const bool ExistingOk;
  1146. const bool ReplaceIfExists;
  1147. const TSourcePtr Values;
  1148. TScopedStatePtr Scoped;
  1149. };
  1150. TNodePtr BuildCreateTable(TPosition pos, const TTableRef& tr, bool existingOk, bool replaceIfExists, const TCreateTableParameters& params, TSourcePtr values, TScopedStatePtr scoped)
  1151. {
  1152. return new TCreateTableNode(pos, tr, existingOk, replaceIfExists, params, std::move(values), scoped);
  1153. }
  1154. class TAlterTableNode final: public TAstListNode {
  1155. public:
  1156. TAlterTableNode(TPosition pos, const TTableRef& tr, const TAlterTableParameters& params, TScopedStatePtr scoped)
  1157. : TAstListNode(pos)
  1158. , Table(tr)
  1159. , Params(params)
  1160. , Scoped(scoped)
  1161. {
  1162. scoped->UseCluster(Table.Service, Table.Cluster);
  1163. }
  1164. bool DoInit(TContext& ctx, ISource* src) override {
  1165. auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
  1166. if (!keys || !keys->Init(ctx, src)) {
  1167. return false;
  1168. }
  1169. auto actions = Y();
  1170. if (Params.AddColumns) {
  1171. auto columns = Y();
  1172. for (auto& col : Params.AddColumns) {
  1173. auto columnDesc = Y();
  1174. columnDesc = L(columnDesc, BuildQuotedAtom(Pos, col.Name));
  1175. auto type = col.Type;
  1176. if (col.Nullable) {
  1177. type = Y("AsOptionalType", type);
  1178. }
  1179. columnDesc = L(columnDesc, type);
  1180. auto columnConstraints = Y();
  1181. if (!col.Nullable) {
  1182. columnConstraints = L(columnConstraints, Q(Y(Q("not_null"))));
  1183. }
  1184. if (col.Serial) {
  1185. columnConstraints = L(columnConstraints, Q(Y(Q("serial"))));
  1186. }
  1187. if (col.DefaultExpr) {
  1188. if (!col.DefaultExpr->Init(ctx, src)) {
  1189. return false;
  1190. }
  1191. columnConstraints = L(columnConstraints, Q(Y(Q("default"), col.DefaultExpr)));
  1192. }
  1193. columnDesc = L(columnDesc, Q(Y(Q("columnConstrains"), Q(columnConstraints))));
  1194. auto familiesDesc = Y();
  1195. for (const auto& family : col.Families) {
  1196. familiesDesc = L(familiesDesc, BuildQuotedAtom(family.Pos, family.Name));
  1197. }
  1198. columnDesc = L(columnDesc, Q(familiesDesc));
  1199. columns = L(columns, Q(columnDesc));
  1200. }
  1201. actions = L(actions, Q(Y(Q("addColumns"), Q(columns))));
  1202. }
  1203. if (Params.DropColumns) {
  1204. auto columns = Y();
  1205. for (auto& colName : Params.DropColumns) {
  1206. columns = L(columns, BuildQuotedAtom(Pos, colName));
  1207. }
  1208. actions = L(actions, Q(Y(Q("dropColumns"), Q(columns))));
  1209. }
  1210. if (Params.AlterColumns) {
  1211. auto columns = Y();
  1212. for (auto& col : Params.AlterColumns) {
  1213. if (col.TypeOfChange == TColumnSchema::ETypeOfChange::DropNotNullConstraint) {
  1214. auto columnDesc = Y();
  1215. columnDesc = L(columnDesc, BuildQuotedAtom(Pos, col.Name));
  1216. auto columnConstraints = Y();
  1217. columnConstraints = L(columnConstraints, Q(Y(Q("drop_not_null"))));
  1218. columnDesc = L(columnDesc, Q(Y(Q("changeColumnConstraints"), Q(columnConstraints))));
  1219. columns = L(columns, Q(columnDesc));
  1220. } else if (col.TypeOfChange == TColumnSchema::ETypeOfChange::SetNotNullConstraint) {
  1221. // todo flown4qqqq
  1222. } else if (col.TypeOfChange == TColumnSchema::ETypeOfChange::SetFamily) {
  1223. auto columnDesc = Y();
  1224. columnDesc = L(columnDesc, BuildQuotedAtom(Pos, col.Name));
  1225. auto familiesDesc = Y();
  1226. for (const auto& family : col.Families) {
  1227. familiesDesc = L(familiesDesc, BuildQuotedAtom(family.Pos, family.Name));
  1228. }
  1229. columnDesc = L(columnDesc, Q(Y(Q("setFamily"), Q(familiesDesc))));
  1230. columns = L(columns, Q(columnDesc));
  1231. } else if (col.TypeOfChange == TColumnSchema::ETypeOfChange::Nothing) {
  1232. // do nothing
  1233. } else {
  1234. ctx.Error(Pos) << " action is not supported";
  1235. }
  1236. }
  1237. actions = L(actions, Q(Y(Q("alterColumns"), Q(columns))));
  1238. }
  1239. if (Params.AddColumnFamilies) {
  1240. auto columnFamilies = Y();
  1241. for (const auto& family : Params.AddColumnFamilies) {
  1242. auto familyDesc = Y();
  1243. familyDesc = L(familyDesc, Q(Y(Q("name"), BuildQuotedAtom(family.Name.Pos, family.Name.Name))));
  1244. if (family.Data) {
  1245. familyDesc = L(familyDesc, Q(Y(Q("data"), family.Data)));
  1246. }
  1247. if (family.Compression) {
  1248. familyDesc = L(familyDesc, Q(Y(Q("compression"), family.Compression)));
  1249. }
  1250. if (family.CompressionLevel) {
  1251. familyDesc = L(familyDesc, Q(Y(Q("compression_level"), family.CompressionLevel)));
  1252. }
  1253. columnFamilies = L(columnFamilies, Q(familyDesc));
  1254. }
  1255. actions = L(actions, Q(Y(Q("addColumnFamilies"), Q(columnFamilies))));
  1256. }
  1257. if (Params.AlterColumnFamilies) {
  1258. auto columnFamilies = Y();
  1259. for (const auto& family : Params.AlterColumnFamilies) {
  1260. auto familyDesc = Y();
  1261. familyDesc = L(familyDesc, Q(Y(Q("name"), BuildQuotedAtom(family.Name.Pos, family.Name.Name))));
  1262. if (family.Data) {
  1263. familyDesc = L(familyDesc, Q(Y(Q("data"), family.Data)));
  1264. }
  1265. if (family.Compression) {
  1266. familyDesc = L(familyDesc, Q(Y(Q("compression"), family.Compression)));
  1267. }
  1268. if (family.CompressionLevel) {
  1269. familyDesc = L(familyDesc, Q(Y(Q("compression_level"), family.CompressionLevel)));
  1270. }
  1271. columnFamilies = L(columnFamilies, Q(familyDesc));
  1272. }
  1273. actions = L(actions, Q(Y(Q("alterColumnFamilies"), Q(columnFamilies))));
  1274. }
  1275. if (Params.TableSettings.IsSet()) {
  1276. actions = L(actions, Q(Y(Q("setTableSettings"), Q(
  1277. CreateTableSettings(Params.TableSettings, ETableSettingsParsingMode::Alter, *this)
  1278. ))));
  1279. }
  1280. for (const auto& index : Params.AddIndexes) {
  1281. const auto& desc = CreateIndexDesc(index, ETableSettingsParsingMode::Alter, *this);
  1282. actions = L(actions, Q(Y(Q("addIndex"), Q(desc))));
  1283. }
  1284. for (const auto& index : Params.AlterIndexes) {
  1285. const auto& desc = CreateAlterIndex(index, *this);
  1286. actions = L(actions, Q(Y(Q("alterIndex"), Q(desc))));
  1287. }
  1288. for (const auto& id : Params.DropIndexes) {
  1289. auto indexName = BuildQuotedAtom(id.Pos, id.Name);
  1290. actions = L(actions, Q(Y(Q("dropIndex"), indexName)));
  1291. }
  1292. if (Params.RenameIndexTo) {
  1293. auto src = BuildQuotedAtom(Params.RenameIndexTo->first.Pos, Params.RenameIndexTo->first.Name);
  1294. auto dst = BuildQuotedAtom(Params.RenameIndexTo->second.Pos, Params.RenameIndexTo->second.Name);
  1295. auto desc = Y();
  1296. desc = L(desc, Q(Y(Q("src"), src)));
  1297. desc = L(desc, Q(Y(Q("dst"), dst)));
  1298. actions = L(actions, Q(Y(Q("renameIndexTo"), Q(desc))));
  1299. }
  1300. if (Params.RenameTo) {
  1301. auto destination = ctx.GetPrefixedPath(Scoped->CurrService, Scoped->CurrCluster,
  1302. TDeferredAtom(Params.RenameTo->Pos, Params.RenameTo->Name));
  1303. actions = L(actions, Q(Y(Q("renameTo"), destination)));
  1304. }
  1305. for (const auto& cf : Params.AddChangefeeds) {
  1306. const auto& desc = CreateChangefeedDesc(cf, *this);
  1307. actions = L(actions, Q(Y(Q("addChangefeed"), Q(desc))));
  1308. }
  1309. for (const auto& cf : Params.AlterChangefeeds) {
  1310. const auto& desc = CreateChangefeedDesc(cf, *this);
  1311. actions = L(actions, Q(Y(Q("alterChangefeed"), Q(desc))));
  1312. }
  1313. for (const auto& id : Params.DropChangefeeds) {
  1314. const auto name = BuildQuotedAtom(id.Pos, id.Name);
  1315. actions = L(actions, Q(Y(Q("dropChangefeed"), name)));
  1316. }
  1317. auto opts = Y();
  1318. opts = L(opts, Q(Y(Q("mode"), Q("alter"))));
  1319. opts = L(opts, Q(Y(Q("actions"), Q(actions))));
  1320. switch (Params.TableType) {
  1321. case ETableType::TableStore:
  1322. opts = L(opts, Q(Y(Q("tableType"), Q("tableStore"))));
  1323. break;
  1324. case ETableType::ExternalTable:
  1325. opts = L(opts, Q(Y(Q("tableType"), Q("externalTable"))));
  1326. break;
  1327. case ETableType::Table:
  1328. break;
  1329. }
  1330. Add("block", Q(Y(
  1331. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.Service), Scoped->WrapCluster(Table.Cluster, ctx))),
  1332. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  1333. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1334. )));
  1335. return TAstListNode::DoInit(ctx, src);
  1336. }
  1337. TPtr DoClone() const final {
  1338. return {};
  1339. }
  1340. private:
  1341. TTableRef Table;
  1342. const TAlterTableParameters Params;
  1343. TScopedStatePtr Scoped;
  1344. };
  1345. TNodePtr BuildAlterTable(TPosition pos, const TTableRef& tr, const TAlterTableParameters& params, TScopedStatePtr scoped)
  1346. {
  1347. return new TAlterTableNode(pos, tr, params, scoped);
  1348. }
  1349. class TDropTableNode final: public TAstListNode {
  1350. public:
  1351. TDropTableNode(TPosition pos, const TTableRef& tr, bool missingOk, ETableType tableType, TScopedStatePtr scoped)
  1352. : TAstListNode(pos)
  1353. , Table(tr)
  1354. , TableType(tableType)
  1355. , Scoped(scoped)
  1356. , MissingOk(missingOk)
  1357. {
  1358. FakeSource = BuildFakeSource(pos);
  1359. scoped->UseCluster(Table.Service, Table.Cluster);
  1360. }
  1361. bool DoInit(TContext& ctx, ISource* src) override {
  1362. Y_UNUSED(src);
  1363. auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::DROP);
  1364. if (!keys || !keys->Init(ctx, FakeSource.Get())) {
  1365. return false;
  1366. }
  1367. auto opts = Y();
  1368. opts = L(opts, Q(Y(Q("mode"), Q(MissingOk ? "drop_if_exists" : "drop"))));
  1369. switch (TableType) {
  1370. case ETableType::TableStore:
  1371. opts = L(opts, Q(Y(Q("tableType"), Q("tableStore"))));
  1372. break;
  1373. case ETableType::ExternalTable:
  1374. opts = L(opts, Q(Y(Q("tableType"), Q("externalTable"))));
  1375. break;
  1376. case ETableType::Table:
  1377. break;
  1378. }
  1379. Add("block", Q(Y(
  1380. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.Service), Scoped->WrapCluster(Table.Cluster, ctx))),
  1381. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  1382. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1383. )));
  1384. return TAstListNode::DoInit(ctx, FakeSource.Get());
  1385. }
  1386. TPtr DoClone() const final {
  1387. return {};
  1388. }
  1389. private:
  1390. TTableRef Table;
  1391. ETableType TableType;
  1392. TScopedStatePtr Scoped;
  1393. TSourcePtr FakeSource;
  1394. const bool MissingOk;
  1395. };
  1396. TNodePtr BuildDropTable(TPosition pos, const TTableRef& tr, bool missingOk, ETableType tableType, TScopedStatePtr scoped) {
  1397. return new TDropTableNode(pos, tr, missingOk, tableType, scoped);
  1398. }
  1399. static INode::TPtr CreateConsumerDesc(const TTopicConsumerDescription& desc, const INode& node, bool alter) {
  1400. auto settings = node.Y();
  1401. if (desc.Settings.Important) {
  1402. settings = node.L(settings, node.Q(node.Y(node.Q("important"), desc.Settings.Important)));
  1403. }
  1404. if (const auto& readFromTs = desc.Settings.ReadFromTs) {
  1405. if (readFromTs.IsSet()) {
  1406. settings = node.L(settings, node.Q(node.Y(node.Q("setReadFromTs"), readFromTs.GetValueSet())));
  1407. } else if (alter) {
  1408. settings = node.L(settings, node.Q(node.Y(node.Q("resetReadFromTs"), node.Q(node.Y()))));
  1409. } else {
  1410. YQL_ENSURE(false, "Cannot reset on create");
  1411. }
  1412. }
  1413. if (const auto& readFromTs = desc.Settings.SupportedCodecs) {
  1414. if (readFromTs.IsSet()) {
  1415. settings = node.L(settings, node.Q(node.Y(node.Q("setSupportedCodecs"), readFromTs.GetValueSet())));
  1416. } else if (alter) {
  1417. settings = node.L(settings, node.Q(node.Y(node.Q("resetSupportedCodecs"), node.Q(node.Y()))));
  1418. } else {
  1419. YQL_ENSURE(false, "Cannot reset on create");
  1420. }
  1421. }
  1422. return node.Y(
  1423. node.Q(node.Y(node.Q("name"), BuildQuotedAtom(desc.Name.Pos, desc.Name.Name))),
  1424. node.Q(node.Y(node.Q("settings"), node.Q(settings)))
  1425. );
  1426. }
  1427. class TCreateTopicNode final: public TAstListNode {
  1428. public:
  1429. TCreateTopicNode(TPosition pos, const TTopicRef& tr, const TCreateTopicParameters& params, TScopedStatePtr scoped)
  1430. : TAstListNode(pos)
  1431. , Topic(tr)
  1432. , Params(params)
  1433. , Scoped(scoped)
  1434. {
  1435. scoped->UseCluster(TString(KikimrProviderName), Topic.Cluster);
  1436. }
  1437. bool DoInit(TContext& ctx, ISource* src) override {
  1438. auto keys = Topic.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
  1439. if (!keys || !keys->Init(ctx, src)) {
  1440. return false;
  1441. }
  1442. if (!Params.Consumers.empty())
  1443. {
  1444. THashSet<TString> consumerNames;
  1445. for (const auto& consumer : Params.Consumers) {
  1446. if (!consumerNames.insert(consumer.Name.Name).second) {
  1447. ctx.Error(consumer.Name.Pos) << "Consumer " << consumer.Name.Name << " defined more than once";
  1448. return false;
  1449. }
  1450. }
  1451. }
  1452. auto opts = Y();
  1453. TString mode = Params.ExistingOk ? "create_if_not_exists" : "create";
  1454. opts = L(opts, Q(Y(Q("mode"), Q(mode))));
  1455. for (const auto& consumer : Params.Consumers) {
  1456. const auto& desc = CreateConsumerDesc(consumer, *this, false);
  1457. opts = L(opts, Q(Y(Q("consumer"), Q(desc))));
  1458. }
  1459. if (Params.TopicSettings.IsSet()) {
  1460. auto settings = Y();
  1461. #define INSERT_TOPIC_SETTING(NAME) \
  1462. if (const auto& NAME##Val = Params.TopicSettings.NAME) { \
  1463. if (NAME##Val.IsSet()) { \
  1464. settings = L(settings, Q(Y(Q(Y_STRINGIZE(set##NAME)), NAME##Val.GetValueSet()))); \
  1465. } else { \
  1466. YQL_ENSURE(false, "Can't reset on create"); \
  1467. } \
  1468. }
  1469. INSERT_TOPIC_SETTING(MaxPartitions)
  1470. INSERT_TOPIC_SETTING(MinPartitions)
  1471. INSERT_TOPIC_SETTING(RetentionPeriod)
  1472. INSERT_TOPIC_SETTING(SupportedCodecs)
  1473. INSERT_TOPIC_SETTING(PartitionWriteSpeed)
  1474. INSERT_TOPIC_SETTING(PartitionWriteBurstSpeed)
  1475. INSERT_TOPIC_SETTING(MeteringMode)
  1476. INSERT_TOPIC_SETTING(AutoPartitioningStabilizationWindow)
  1477. INSERT_TOPIC_SETTING(AutoPartitioningUpUtilizationPercent)
  1478. INSERT_TOPIC_SETTING(AutoPartitioningDownUtilizationPercent)
  1479. INSERT_TOPIC_SETTING(AutoPartitioningStrategy)
  1480. #undef INSERT_TOPIC_SETTING
  1481. opts = L(opts, Q(Y(Q("topicSettings"), Q(settings))));
  1482. }
  1483. Add("block", Q(Y(
  1484. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, TString(KikimrProviderName)),
  1485. Scoped->WrapCluster(Topic.Cluster, ctx))),
  1486. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  1487. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1488. )));
  1489. return TAstListNode::DoInit(ctx, src);
  1490. }
  1491. TPtr DoClone() const final {
  1492. return {};
  1493. }
  1494. private:
  1495. const TTopicRef Topic;
  1496. const TCreateTopicParameters Params;
  1497. TScopedStatePtr Scoped;
  1498. };
  1499. TNodePtr BuildCreateTopic(
  1500. TPosition pos, const TTopicRef& tr, const TCreateTopicParameters& params, TScopedStatePtr scoped
  1501. ){
  1502. return new TCreateTopicNode(pos, tr, params, scoped);
  1503. }
  1504. class TAlterTopicNode final: public TAstListNode {
  1505. public:
  1506. TAlterTopicNode(TPosition pos, const TTopicRef& tr, const TAlterTopicParameters& params, TScopedStatePtr scoped)
  1507. : TAstListNode(pos)
  1508. , Topic(tr)
  1509. , Params(params)
  1510. , Scoped(scoped)
  1511. {
  1512. scoped->UseCluster(TString(KikimrProviderName), Topic.Cluster);
  1513. }
  1514. bool DoInit(TContext& ctx, ISource* src) override {
  1515. auto keys = Topic.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
  1516. if (!keys || !keys->Init(ctx, src)) {
  1517. return false;
  1518. }
  1519. if (!Params.AddConsumers.empty())
  1520. {
  1521. THashSet<TString> consumerNames;
  1522. for (const auto& consumer : Params.AddConsumers) {
  1523. if (!consumerNames.insert(consumer.Name.Name).second) {
  1524. ctx.Error(consumer.Name.Pos) << "Consumer " << consumer.Name.Name << " defined more than once";
  1525. return false;
  1526. }
  1527. }
  1528. }
  1529. if (!Params.AlterConsumers.empty())
  1530. {
  1531. THashSet<TString> consumerNames;
  1532. for (const auto& [_, consumer] : Params.AlterConsumers) {
  1533. if (!consumerNames.insert(consumer.Name.Name).second) {
  1534. ctx.Error(consumer.Name.Pos) << "Consumer " << consumer.Name.Name << " altered more than once";
  1535. return false;
  1536. }
  1537. }
  1538. }
  1539. if (!Params.DropConsumers.empty())
  1540. {
  1541. THashSet<TString> consumerNames;
  1542. for (const auto& consumer : Params.DropConsumers) {
  1543. if (!consumerNames.insert(consumer.Name).second) {
  1544. ctx.Error(consumer.Pos) << "Consumer " << consumer.Name << " dropped more than once";
  1545. return false;
  1546. }
  1547. }
  1548. }
  1549. auto opts = Y();
  1550. TString mode = Params.MissingOk ? "alter_if_exists" : "alter";
  1551. opts = L(opts, Q(Y(Q("mode"), Q(mode))));
  1552. for (const auto& consumer : Params.AddConsumers) {
  1553. const auto& desc = CreateConsumerDesc(consumer, *this, false);
  1554. opts = L(opts, Q(Y(Q("addConsumer"), Q(desc))));
  1555. }
  1556. for (const auto& [_, consumer] : Params.AlterConsumers) {
  1557. const auto& desc = CreateConsumerDesc(consumer, *this, true);
  1558. opts = L(opts, Q(Y(Q("alterConsumer"), Q(desc))));
  1559. }
  1560. for (const auto& consumer : Params.DropConsumers) {
  1561. const auto name = BuildQuotedAtom(consumer.Pos, consumer.Name);
  1562. opts = L(opts, Q(Y(Q("dropConsumer"), name)));
  1563. }
  1564. if (Params.TopicSettings.IsSet()) {
  1565. auto settings = Y();
  1566. #define INSERT_TOPIC_SETTING(NAME) \
  1567. if (const auto& NAME##Val = Params.TopicSettings.NAME) { \
  1568. if (NAME##Val.IsSet()) { \
  1569. settings = L(settings, Q(Y(Q(Y_STRINGIZE(set##NAME)), NAME##Val.GetValueSet()))); \
  1570. } else { \
  1571. settings = L(settings, Q(Y(Q(Y_STRINGIZE(reset##NAME)), Y()))); \
  1572. } \
  1573. }
  1574. INSERT_TOPIC_SETTING(MaxPartitions)
  1575. INSERT_TOPIC_SETTING(MinPartitions)
  1576. INSERT_TOPIC_SETTING(RetentionPeriod)
  1577. INSERT_TOPIC_SETTING(SupportedCodecs)
  1578. INSERT_TOPIC_SETTING(PartitionWriteSpeed)
  1579. INSERT_TOPIC_SETTING(PartitionWriteBurstSpeed)
  1580. INSERT_TOPIC_SETTING(MeteringMode)
  1581. INSERT_TOPIC_SETTING(AutoPartitioningStabilizationWindow)
  1582. INSERT_TOPIC_SETTING(AutoPartitioningUpUtilizationPercent)
  1583. INSERT_TOPIC_SETTING(AutoPartitioningDownUtilizationPercent)
  1584. INSERT_TOPIC_SETTING(AutoPartitioningStrategy)
  1585. #undef INSERT_TOPIC_SETTING
  1586. opts = L(opts, Q(Y(Q("topicSettings"), Q(settings))));
  1587. }
  1588. Add("block", Q(Y(
  1589. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, TString(KikimrProviderName)),
  1590. Scoped->WrapCluster(Topic.Cluster, ctx))),
  1591. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  1592. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1593. )));
  1594. return TAstListNode::DoInit(ctx, src);
  1595. }
  1596. TPtr DoClone() const final {
  1597. return {};
  1598. }
  1599. private:
  1600. const TTopicRef Topic;
  1601. const TAlterTopicParameters Params;
  1602. TScopedStatePtr Scoped;
  1603. };
  1604. TNodePtr BuildAlterTopic(
  1605. TPosition pos, const TTopicRef& tr, const TAlterTopicParameters& params, TScopedStatePtr scoped
  1606. ){
  1607. return new TAlterTopicNode(pos, tr, params, scoped);
  1608. }
  1609. class TDropTopicNode final: public TAstListNode {
  1610. public:
  1611. TDropTopicNode(TPosition pos, const TTopicRef& tr, const TDropTopicParameters& params, TScopedStatePtr scoped)
  1612. : TAstListNode(pos)
  1613. , Topic(tr)
  1614. , Params(params)
  1615. , Scoped(scoped)
  1616. {
  1617. scoped->UseCluster(TString(KikimrProviderName), Topic.Cluster);
  1618. }
  1619. bool DoInit(TContext& ctx, ISource* src) override {
  1620. Y_UNUSED(src);
  1621. auto keys = Topic.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::DROP);
  1622. if (!keys || !keys->Init(ctx, FakeSource.Get())) {
  1623. return false;
  1624. }
  1625. auto opts = Y();
  1626. TString mode = Params.MissingOk ? "drop_if_exists" : "drop";
  1627. opts = L(opts, Q(Y(Q("mode"), Q(mode))));
  1628. Add("block", Q(Y(
  1629. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, TString(KikimrProviderName)),
  1630. Scoped->WrapCluster(Topic.Cluster, ctx))),
  1631. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  1632. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1633. )));
  1634. return TAstListNode::DoInit(ctx, FakeSource.Get());
  1635. }
  1636. TPtr DoClone() const final {
  1637. return {};
  1638. }
  1639. private:
  1640. TTopicRef Topic;
  1641. TDropTopicParameters Params;
  1642. TScopedStatePtr Scoped;
  1643. TSourcePtr FakeSource;
  1644. };
  1645. TNodePtr BuildDropTopic(TPosition pos, const TTopicRef& tr, const TDropTopicParameters& params, TScopedStatePtr scoped) {
  1646. return new TDropTopicNode(pos, tr, params, scoped);
  1647. }
  1648. class TCreateRole final: public TAstListNode {
  1649. public:
  1650. TCreateRole(TPosition pos, bool isUser, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TMaybe<TRoleParameters>& params, TScopedStatePtr scoped)
  1651. : TAstListNode(pos)
  1652. , IsUser(isUser)
  1653. , Service(service)
  1654. , Cluster(cluster)
  1655. , Name(name)
  1656. , Params(params)
  1657. , Scoped(scoped)
  1658. {
  1659. FakeSource = BuildFakeSource(pos);
  1660. scoped->UseCluster(service, cluster);
  1661. }
  1662. bool DoInit(TContext& ctx, ISource* src) override {
  1663. Y_UNUSED(src);
  1664. auto name = Name.Build();
  1665. TNodePtr password;
  1666. if (Params && Params->Password) {
  1667. password = Params->Password->Build();
  1668. }
  1669. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  1670. if (!name->Init(ctx, FakeSource.Get()) || !cluster->Init(ctx, FakeSource.Get())) {
  1671. return false;
  1672. }
  1673. if (password && !password->Init(ctx, FakeSource.Get())) {
  1674. return false;
  1675. }
  1676. TVector<TNodePtr> roles;
  1677. if (Params && !Params->Roles.empty()) {
  1678. for (auto& item : Params->Roles) {
  1679. roles.push_back(item.Build());
  1680. if (!roles.back()->Init(ctx, FakeSource.Get())) {
  1681. return false;
  1682. }
  1683. }
  1684. }
  1685. auto options = Y(Q(Y(Q("mode"), Q(IsUser ? "createUser" : "createGroup"))));
  1686. if (Params) {
  1687. if (Params->IsPasswordEncrypted) {
  1688. options = L(options, Q(Y(Q("passwordEncrypted"))));
  1689. }
  1690. if (Params->Password) {
  1691. options = L(options, Q(Y(Q("password"), password)));
  1692. } else {
  1693. options = L(options, Q(Y(Q("nullPassword"))));
  1694. }
  1695. if (!Params->Roles.empty()) {
  1696. options = L(options, Q(Y(Q("roles"), Q(new TAstListNodeImpl(Pos, std::move(roles))))));
  1697. }
  1698. }
  1699. Add("block", Q(Y(
  1700. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)),
  1701. Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))),
  1702. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1703. )));
  1704. return TAstListNode::DoInit(ctx, FakeSource.Get());
  1705. }
  1706. TPtr DoClone() const final {
  1707. return {};
  1708. }
  1709. private:
  1710. const bool IsUser;
  1711. const TString Service;
  1712. TDeferredAtom Cluster;
  1713. TDeferredAtom Name;
  1714. const TMaybe<TRoleParameters> Params;
  1715. TScopedStatePtr Scoped;
  1716. TSourcePtr FakeSource;
  1717. };
  1718. TNodePtr BuildCreateUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TMaybe<TRoleParameters>& params, TScopedStatePtr scoped) {
  1719. bool isUser = true;
  1720. return new TCreateRole(pos, isUser, service, cluster, name, params, scoped);
  1721. }
  1722. TNodePtr BuildCreateGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TMaybe<TRoleParameters>& params, TScopedStatePtr scoped) {
  1723. bool isUser = false;
  1724. return new TCreateRole(pos, isUser, service, cluster, name, params, scoped);
  1725. }
  1726. class TAlterUser final: public TAstListNode {
  1727. public:
  1728. TAlterUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TRoleParameters& params, TScopedStatePtr scoped)
  1729. : TAstListNode(pos)
  1730. , Service(service)
  1731. , Cluster(cluster)
  1732. , Name(name)
  1733. , Params(params)
  1734. , Scoped(scoped)
  1735. {
  1736. FakeSource = BuildFakeSource(pos);
  1737. scoped->UseCluster(service, cluster);
  1738. }
  1739. bool DoInit(TContext& ctx, ISource* src) override {
  1740. Y_UNUSED(src);
  1741. auto name = Name.Build();
  1742. TNodePtr password;
  1743. if (Params.Password) {
  1744. password = Params.Password->Build();
  1745. }
  1746. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  1747. if (!name->Init(ctx, FakeSource.Get()) || !cluster->Init(ctx, FakeSource.Get())) {
  1748. return false;
  1749. }
  1750. if (password && !password->Init(ctx, FakeSource.Get())) {
  1751. return false;
  1752. }
  1753. auto options = Y(Q(Y(Q("mode"), Q("alterUser"))));
  1754. if (Params.IsPasswordEncrypted) {
  1755. options = L(options, Q(Y(Q("passwordEncrypted"))));
  1756. }
  1757. if (Params.Password) {
  1758. options = L(options, Q(Y(Q("password"), password)));
  1759. } else {
  1760. options = L(options, Q(Y(Q("nullPassword"))));
  1761. }
  1762. Add("block", Q(Y(
  1763. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)),
  1764. Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))),
  1765. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1766. )));
  1767. return TAstListNode::DoInit(ctx, FakeSource.Get());
  1768. }
  1769. TPtr DoClone() const final {
  1770. return {};
  1771. }
  1772. private:
  1773. const TString Service;
  1774. TDeferredAtom Cluster;
  1775. TDeferredAtom Name;
  1776. const TRoleParameters Params;
  1777. TScopedStatePtr Scoped;
  1778. TSourcePtr FakeSource;
  1779. };
  1780. TNodePtr BuildAlterUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TRoleParameters& params, TScopedStatePtr scoped) {
  1781. return new TAlterUser(pos, service, cluster, name, params, scoped);
  1782. }
  1783. class TAlterSequence final: public TAstListNode {
  1784. public:
  1785. TAlterSequence(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TString& id, const TSequenceParameters& params, TScopedStatePtr scoped)
  1786. : TAstListNode(pos)
  1787. , Service(service)
  1788. , Cluster(cluster)
  1789. , Id(id)
  1790. , Params(params)
  1791. , Scoped(scoped)
  1792. {
  1793. FakeSource = BuildFakeSource(pos);
  1794. scoped->UseCluster(service, cluster);
  1795. }
  1796. bool DoInit(TContext& ctx, ISource* src) override {
  1797. Y_UNUSED(src);
  1798. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  1799. if (!cluster->Init(ctx, FakeSource.Get())) {
  1800. return false;
  1801. }
  1802. auto options = Y();
  1803. TString mode = Params.MissingOk ? "alter_if_exists" : "alter";
  1804. options = L(options, Q(Y(Q("mode"), Q(mode))));
  1805. if (Params.IsRestart) {
  1806. if (Params.RestartValue) {
  1807. TString strValue = Params.RestartValue->Build()->GetLiteralValue();
  1808. ui64 value = FromString<ui64>(strValue);
  1809. ui64 maxValue = ui64(std::numeric_limits<i64>::max());
  1810. ui64 minValue = 1;
  1811. if (value > maxValue) {
  1812. ctx.Error(Pos) << "Restart value: " << value << " cannot be greater than max value: " << maxValue;
  1813. return false;
  1814. }
  1815. if (value < minValue) {
  1816. ctx.Error(Pos) << "Restart value: " << value << " cannot be less than min value: " << minValue;
  1817. return false;
  1818. }
  1819. options = L(options, Q(Y(Q("restart"), Q(ToString(value)))));
  1820. } else {
  1821. options = L(options, Q(Y(Q("restart"), Q(TString()))));
  1822. }
  1823. }
  1824. if (Params.StartValue) {
  1825. TString strValue = Params.StartValue->Build()->GetLiteralValue();
  1826. ui64 value = FromString<ui64>(strValue);
  1827. ui64 maxValue = ui64(std::numeric_limits<i64>::max());
  1828. ui64 minValue = 1;
  1829. if (value > maxValue) {
  1830. ctx.Error(Pos) << "Start value: " << value << " cannot be greater than max value: " << maxValue;
  1831. return false;
  1832. }
  1833. if (value < minValue) {
  1834. ctx.Error(Pos) << "Start value: " << value << " cannot be less than min value: " << minValue;
  1835. return false;
  1836. }
  1837. options = L(options, Q(Y(Q("start"), Q(ToString(value)))));
  1838. }
  1839. if (Params.Increment) {
  1840. TString strValue = Params.Increment->Build()->GetLiteralValue();
  1841. ui64 value = FromString<ui64>(strValue);
  1842. ui64 maxValue = ui64(std::numeric_limits<i64>::max());
  1843. if (value > maxValue) {
  1844. ctx.Error(Pos) << "Increment: " << value << " cannot be greater than max value: " << maxValue;
  1845. return false;
  1846. }
  1847. if (value == 0) {
  1848. ctx.Error(Pos) << "Increment must not be zero";
  1849. return false;
  1850. }
  1851. options = L(options, Q(Y(Q("increment"), Q(ToString(value)))));
  1852. }
  1853. Add("block", Q(Y(
  1854. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, TString(KikimrProviderName)),
  1855. Scoped->WrapCluster(Cluster, ctx))),
  1856. Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("sequence"), Y("String", BuildQuotedAtom(Pos, Id))))), Y("Void"), Q(options))),
  1857. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1858. )));
  1859. return TAstListNode::DoInit(ctx, src);
  1860. }
  1861. TPtr DoClone() const final {
  1862. return {};
  1863. }
  1864. private:
  1865. const TString Service;
  1866. TDeferredAtom Cluster;
  1867. TString Id;
  1868. const TSequenceParameters Params;
  1869. TScopedStatePtr Scoped;
  1870. TSourcePtr FakeSource;
  1871. };
  1872. TNodePtr BuildAlterSequence(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TString& id, const TSequenceParameters& params, TScopedStatePtr scoped) {
  1873. return new TAlterSequence(pos, service, cluster, id, params, scoped);
  1874. }
  1875. class TRenameRole final: public TAstListNode {
  1876. public:
  1877. TRenameRole(TPosition pos, bool isUser, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TDeferredAtom& newName, TScopedStatePtr scoped)
  1878. : TAstListNode(pos)
  1879. , IsUser(isUser)
  1880. , Service(service)
  1881. , Cluster(cluster)
  1882. , Name(name)
  1883. , NewName(newName)
  1884. , Scoped(scoped)
  1885. {
  1886. FakeSource = BuildFakeSource(pos);
  1887. scoped->UseCluster(service, cluster);
  1888. }
  1889. bool DoInit(TContext& ctx, ISource* src) override {
  1890. Y_UNUSED(src);
  1891. auto name = Name.Build();
  1892. auto newName = NewName.Build();
  1893. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  1894. if (!name->Init(ctx, FakeSource.Get()) ||
  1895. !newName->Init(ctx, FakeSource.Get()) ||
  1896. !cluster->Init(ctx, FakeSource.Get()))
  1897. {
  1898. return false;
  1899. }
  1900. auto options = Y(Q(Y(Q("mode"), Q(IsUser ? "renameUser" : "renameGroup"))));
  1901. options = L(options, Q(Y(Q("newName"), newName)));
  1902. Add("block", Q(Y(
  1903. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)),
  1904. Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))),
  1905. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1906. )));
  1907. return TAstListNode::DoInit(ctx, FakeSource.Get());
  1908. }
  1909. TPtr DoClone() const final {
  1910. return {};
  1911. }
  1912. private:
  1913. const bool IsUser;
  1914. const TString Service;
  1915. TDeferredAtom Cluster;
  1916. TDeferredAtom Name;
  1917. TDeferredAtom NewName;
  1918. TScopedStatePtr Scoped;
  1919. TSourcePtr FakeSource;
  1920. };
  1921. TNodePtr BuildRenameUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TDeferredAtom& newName, TScopedStatePtr scoped) {
  1922. const bool isUser = true;
  1923. return new TRenameRole(pos, isUser, service, cluster, name, newName, scoped);
  1924. }
  1925. TNodePtr BuildRenameGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TDeferredAtom& newName, TScopedStatePtr scoped) {
  1926. const bool isUser = false;
  1927. return new TRenameRole(pos, isUser, service, cluster, name, newName, scoped);
  1928. }
  1929. class TAlterGroup final: public TAstListNode {
  1930. public:
  1931. TAlterGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TVector<TDeferredAtom>& toChange, bool isDrop, TScopedStatePtr scoped)
  1932. : TAstListNode(pos)
  1933. , Service(service)
  1934. , Cluster(cluster)
  1935. , Name(name)
  1936. , ToChange(toChange)
  1937. , IsDrop(isDrop)
  1938. , Scoped(scoped)
  1939. {
  1940. FakeSource = BuildFakeSource(pos);
  1941. scoped->UseCluster(service, cluster);
  1942. }
  1943. bool DoInit(TContext& ctx, ISource* src) override {
  1944. Y_UNUSED(src);
  1945. auto name = Name.Build();
  1946. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  1947. if (!name->Init(ctx, FakeSource.Get()) || !cluster->Init(ctx, FakeSource.Get())) {
  1948. return false;
  1949. }
  1950. TVector<TNodePtr> toChange;
  1951. for (auto& item : ToChange) {
  1952. toChange.push_back(item.Build());
  1953. if (!toChange.back()->Init(ctx, FakeSource.Get())) {
  1954. return false;
  1955. }
  1956. }
  1957. auto options = Y(Q(Y(Q("mode"), Q(IsDrop ? "dropUsersFromGroup" : "addUsersToGroup"))));
  1958. options = L(options, Q(Y(Q("roles"), Q(new TAstListNodeImpl(Pos, std::move(toChange))))));
  1959. Add("block", Q(Y(
  1960. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)),
  1961. Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))),
  1962. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1963. )));
  1964. return TAstListNode::DoInit(ctx, FakeSource.Get());
  1965. }
  1966. TPtr DoClone() const final {
  1967. return {};
  1968. }
  1969. private:
  1970. const TString Service;
  1971. TDeferredAtom Cluster;
  1972. TDeferredAtom Name;
  1973. TVector<TDeferredAtom> ToChange;
  1974. const bool IsDrop;
  1975. TScopedStatePtr Scoped;
  1976. TSourcePtr FakeSource;
  1977. };
  1978. TNodePtr BuildAlterGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TVector<TDeferredAtom>& toChange, bool isDrop,
  1979. TScopedStatePtr scoped)
  1980. {
  1981. return new TAlterGroup(pos, service, cluster, name, toChange, isDrop, scoped);
  1982. }
  1983. class TDropRoles final: public TAstListNode {
  1984. public:
  1985. TDropRoles(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& toDrop, bool isUser, bool missingOk, TScopedStatePtr scoped)
  1986. : TAstListNode(pos)
  1987. , Service(service)
  1988. , Cluster(cluster)
  1989. , ToDrop(toDrop)
  1990. , IsUser(isUser)
  1991. , MissingOk(missingOk)
  1992. , Scoped(scoped)
  1993. {
  1994. FakeSource = BuildFakeSource(pos);
  1995. scoped->UseCluster(service, cluster);
  1996. }
  1997. bool DoInit(TContext& ctx, ISource* src) override {
  1998. Y_UNUSED(src);
  1999. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  2000. if (!cluster->Init(ctx, FakeSource.Get())) {
  2001. return false;
  2002. }
  2003. const char* mode = IsUser ?
  2004. (MissingOk ? "dropUserIfExists" : "dropUser") :
  2005. (MissingOk ? "dropGroupIfExists" : "dropGroup");
  2006. auto options = Y(Q(Y(Q("mode"), Q(mode))));
  2007. auto block = Y(Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)));
  2008. for (auto& item : ToDrop) {
  2009. auto name = item.Build();
  2010. if (!name->Init(ctx, FakeSource.Get())) {
  2011. return false;
  2012. }
  2013. block = L(block, Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))));
  2014. }
  2015. block = L(block, Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world")));
  2016. Add("block", Q(block));
  2017. return TAstListNode::DoInit(ctx, FakeSource.Get());
  2018. }
  2019. TPtr DoClone() const final {
  2020. return {};
  2021. }
  2022. private:
  2023. const TString Service;
  2024. TDeferredAtom Cluster;
  2025. TVector<TDeferredAtom> ToDrop;
  2026. const bool IsUser;
  2027. const bool MissingOk;
  2028. TScopedStatePtr Scoped;
  2029. TSourcePtr FakeSource;
  2030. };
  2031. TNodePtr BuildUpsertObjectOperation(TPosition pos, const TString& objectId, const TString& typeId,
  2032. std::map<TString, TDeferredAtom>&& features, const TObjectOperatorContext& context) {
  2033. return new TUpsertObject(pos, objectId, typeId, false, false, std::move(features), std::set<TString>(), context);
  2034. }
  2035. TNodePtr BuildCreateObjectOperation(TPosition pos, const TString& objectId, const TString& typeId,
  2036. bool existingOk, bool replaceIfExists, std::map<TString, TDeferredAtom>&& features, const TObjectOperatorContext& context) {
  2037. return new TCreateObject(pos, objectId, typeId, existingOk, replaceIfExists, std::move(features), std::set<TString>(), context);
  2038. }
  2039. TNodePtr BuildAlterObjectOperation(TPosition pos, const TString& secretId, const TString& typeId,
  2040. std::map<TString, TDeferredAtom>&& features, std::set<TString>&& featuresToReset, const TObjectOperatorContext& context)
  2041. {
  2042. return new TAlterObject(pos, secretId, typeId, false, false, std::move(features), std::move(featuresToReset), context);
  2043. }
  2044. TNodePtr BuildDropObjectOperation(TPosition pos, const TString& secretId, const TString& typeId,
  2045. bool missingOk, std::map<TString, TDeferredAtom>&& options, const TObjectOperatorContext& context)
  2046. {
  2047. return new TDropObject(pos, secretId, typeId, missingOk, false, std::move(options), std::set<TString>(), context);
  2048. }
  2049. TNodePtr BuildDropRoles(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& toDrop, bool isUser, bool missingOk, TScopedStatePtr scoped) {
  2050. return new TDropRoles(pos, service, cluster, toDrop, isUser, missingOk, scoped);
  2051. }
  2052. class TPermissionsAction final : public TAstListNode {
  2053. public:
  2054. struct TPermissionParameters {
  2055. TString PermissionAction;
  2056. TVector<TDeferredAtom> Permissions;
  2057. TVector<TDeferredAtom> SchemaPaths;
  2058. TVector<TDeferredAtom> RoleNames;
  2059. };
  2060. TPermissionsAction(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TPermissionParameters& parameters, TScopedStatePtr scoped)
  2061. : TAstListNode(pos)
  2062. , Service(service)
  2063. , Cluster(cluster)
  2064. , Parameters(parameters)
  2065. , Scoped(scoped)
  2066. {
  2067. FakeSource = BuildFakeSource(pos);
  2068. scoped->UseCluster(service, cluster);
  2069. }
  2070. bool DoInit(TContext& ctx, ISource* src) override {
  2071. Y_UNUSED(src);
  2072. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  2073. TNodePtr permissionAction = TDeferredAtom(Pos, Parameters.PermissionAction).Build();
  2074. if (!permissionAction->Init(ctx, FakeSource.Get()) ||
  2075. !cluster->Init(ctx, FakeSource.Get())) {
  2076. return false;
  2077. }
  2078. TVector<TNodePtr> paths;
  2079. paths.reserve(Parameters.SchemaPaths.size());
  2080. for (auto& item : Parameters.SchemaPaths) {
  2081. paths.push_back(item.Build());
  2082. if (!paths.back()->Init(ctx, FakeSource.Get())) {
  2083. return false;
  2084. }
  2085. }
  2086. auto options = Y(Q(Y(Q("paths"), Q(new TAstListNodeImpl(Pos, std::move(paths))))));
  2087. TVector<TNodePtr> permissions;
  2088. permissions.reserve(Parameters.Permissions.size());
  2089. for (auto& item : Parameters.Permissions) {
  2090. permissions.push_back(item.Build());
  2091. if (!permissions.back()->Init(ctx, FakeSource.Get())) {
  2092. return false;
  2093. }
  2094. }
  2095. options = L(options, Q(Y(Q("permissions"), Q(new TAstListNodeImpl(Pos, std::move(permissions))))));
  2096. TVector<TNodePtr> roles;
  2097. roles.reserve(Parameters.RoleNames.size());
  2098. for (auto& item : Parameters.RoleNames) {
  2099. roles.push_back(item.Build());
  2100. if (!roles.back()->Init(ctx, FakeSource.Get())) {
  2101. return false;
  2102. }
  2103. }
  2104. options = L(options, Q(Y(Q("roles"), Q(new TAstListNodeImpl(Pos, std::move(roles))))));
  2105. auto block = Y(Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)));
  2106. block = L(block, Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("permission"), Y("String", permissionAction)))), Y("Void"), Q(options))));
  2107. block = L(block, Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world")));
  2108. Add("block", Q(block));
  2109. return TAstListNode::DoInit(ctx, FakeSource.Get());
  2110. }
  2111. TPtr DoClone() const final {
  2112. return {};
  2113. }
  2114. private:
  2115. const TString Service;
  2116. TDeferredAtom Cluster;
  2117. TPermissionParameters Parameters;
  2118. TScopedStatePtr Scoped;
  2119. TSourcePtr FakeSource;
  2120. };
  2121. TNodePtr BuildGrantPermissions(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& permissions, const TVector<TDeferredAtom>& schemaPaths, const TVector<TDeferredAtom>& roleNames, TScopedStatePtr scoped) {
  2122. return new TPermissionsAction(pos,
  2123. service,
  2124. cluster,
  2125. {.PermissionAction = "grant",
  2126. .Permissions = permissions,
  2127. .SchemaPaths = schemaPaths,
  2128. .RoleNames = roleNames},
  2129. scoped);
  2130. }
  2131. TNodePtr BuildRevokePermissions(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& permissions, const TVector<TDeferredAtom>& schemaPaths, const TVector<TDeferredAtom>& roleNames, TScopedStatePtr scoped) {
  2132. return new TPermissionsAction(pos,
  2133. service,
  2134. cluster,
  2135. {.PermissionAction = "revoke",
  2136. .Permissions = permissions,
  2137. .SchemaPaths = schemaPaths,
  2138. .RoleNames = roleNames},
  2139. scoped);
  2140. }
  2141. class TAsyncReplication
  2142. : public TAstListNode
  2143. , protected TObjectOperatorContext
  2144. {
  2145. protected:
  2146. virtual INode::TPtr FillOptions(INode::TPtr options) const = 0;
  2147. public:
  2148. explicit TAsyncReplication(TPosition pos, const TString& id, const TString& mode, const TObjectOperatorContext& context)
  2149. : TAstListNode(pos)
  2150. , TObjectOperatorContext(context)
  2151. , Id(id)
  2152. , Mode(mode)
  2153. {
  2154. }
  2155. bool DoInit(TContext& ctx, ISource* src) override {
  2156. Scoped->UseCluster(ServiceId, Cluster);
  2157. auto keys = Y("Key", Q(Y(Q("replication"), Y("String", BuildQuotedAtom(Pos, Id)))));
  2158. auto options = FillOptions(Y(Q(Y(Q("mode"), Q(Mode)))));
  2159. Add("block", Q(Y(
  2160. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
  2161. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(options))),
  2162. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  2163. )));
  2164. return TAstListNode::DoInit(ctx, src);
  2165. }
  2166. TPtr DoClone() const final {
  2167. return {};
  2168. }
  2169. private:
  2170. const TString Id;
  2171. const TString Mode;
  2172. }; // TAsyncReplication
  2173. class TCreateAsyncReplication final: public TAsyncReplication {
  2174. public:
  2175. explicit TCreateAsyncReplication(TPosition pos, const TString& id,
  2176. std::vector<std::pair<TString, TString>>&& targets,
  2177. std::map<TString, TNodePtr>&& settings,
  2178. const TObjectOperatorContext& context)
  2179. : TAsyncReplication(pos, id, "create", context)
  2180. , Targets(std::move(targets))
  2181. , Settings(std::move(settings))
  2182. {
  2183. }
  2184. protected:
  2185. INode::TPtr FillOptions(INode::TPtr options) const override {
  2186. if (!Targets.empty()) {
  2187. auto targets = Y();
  2188. for (auto&& [remote, local] : Targets) {
  2189. auto target = Y();
  2190. target = L(target, Q(Y(Q("remote"), Q(remote))));
  2191. target = L(target, Q(Y(Q("local"), Q(local))));
  2192. targets = L(targets, Q(target));
  2193. }
  2194. options = L(options, Q(Y(Q("targets"), Q(targets))));
  2195. }
  2196. if (!Settings.empty()) {
  2197. auto settings = Y();
  2198. for (auto&& [k, v] : Settings) {
  2199. if (v) {
  2200. settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k), v)));
  2201. } else {
  2202. settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k))));
  2203. }
  2204. }
  2205. options = L(options, Q(Y(Q("settings"), Q(settings))));
  2206. }
  2207. return options;
  2208. }
  2209. private:
  2210. std::vector<std::pair<TString, TString>> Targets; // (remote, local)
  2211. std::map<TString, TNodePtr> Settings;
  2212. }; // TCreateAsyncReplication
  2213. TNodePtr BuildCreateAsyncReplication(TPosition pos, const TString& id,
  2214. std::vector<std::pair<TString, TString>>&& targets,
  2215. std::map<TString, TNodePtr>&& settings,
  2216. const TObjectOperatorContext& context)
  2217. {
  2218. return new TCreateAsyncReplication(pos, id, std::move(targets), std::move(settings), context);
  2219. }
  2220. class TDropAsyncReplication final: public TAsyncReplication {
  2221. public:
  2222. explicit TDropAsyncReplication(TPosition pos, const TString& id, bool cascade, const TObjectOperatorContext& context)
  2223. : TAsyncReplication(pos, id, cascade ? "dropCascade" : "drop", context)
  2224. {
  2225. }
  2226. protected:
  2227. INode::TPtr FillOptions(INode::TPtr options) const override {
  2228. return options;
  2229. }
  2230. }; // TDropAsyncReplication
  2231. TNodePtr BuildDropAsyncReplication(TPosition pos, const TString& id, bool cascade, const TObjectOperatorContext& context) {
  2232. return new TDropAsyncReplication(pos, id, cascade, context);
  2233. }
  2234. class TAlterAsyncReplication final: public TAsyncReplication {
  2235. public:
  2236. explicit TAlterAsyncReplication(TPosition pos, const TString& id,
  2237. std::map<TString, TNodePtr>&& settings,
  2238. const TObjectOperatorContext& context)
  2239. : TAsyncReplication(pos, id, "alter", context)
  2240. , Settings(std::move(settings))
  2241. {
  2242. }
  2243. protected:
  2244. INode::TPtr FillOptions(INode::TPtr options) const override {
  2245. if (!Settings.empty()) {
  2246. auto settings = Y();
  2247. for (auto&& [k, v] : Settings) {
  2248. if (v) {
  2249. settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k), v)));
  2250. } else {
  2251. settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k))));
  2252. }
  2253. }
  2254. options = L(options, Q(Y(Q("settings"), Q(settings))));
  2255. }
  2256. return options;
  2257. }
  2258. private:
  2259. std::map<TString, TNodePtr> Settings;
  2260. }; // TAlterAsyncReplication
  2261. TNodePtr BuildAlterAsyncReplication(TPosition pos, const TString& id,
  2262. std::map<TString, TNodePtr>&& settings,
  2263. const TObjectOperatorContext& context)
  2264. {
  2265. return new TAlterAsyncReplication(pos, id, std::move(settings), context);
  2266. }
  2267. static const TMap<EWriteColumnMode, TString> columnModeToStrMapMR {
  2268. {EWriteColumnMode::Default, ""},
  2269. {EWriteColumnMode::Insert, "append"},
  2270. {EWriteColumnMode::Renew, "renew"}
  2271. };
  2272. static const TMap<EWriteColumnMode, TString> columnModeToStrMapStat {
  2273. {EWriteColumnMode::Upsert, "upsert"}
  2274. };
  2275. static const TMap<EWriteColumnMode, TString> columnModeToStrMapKikimr {
  2276. {EWriteColumnMode::Default, ""},
  2277. {EWriteColumnMode::Insert, "insert_abort"},
  2278. {EWriteColumnMode::InsertOrAbort, "insert_abort"},
  2279. {EWriteColumnMode::InsertOrIgnore, "insert_ignore"},
  2280. {EWriteColumnMode::InsertOrRevert, "insert_revert"},
  2281. {EWriteColumnMode::Upsert, "upsert"},
  2282. {EWriteColumnMode::Replace, "replace"},
  2283. {EWriteColumnMode::Update, "update"},
  2284. {EWriteColumnMode::UpdateOn, "update_on"},
  2285. {EWriteColumnMode::Delete, "delete"},
  2286. {EWriteColumnMode::DeleteOn, "delete_on"},
  2287. };
  2288. class TWriteTableNode final: public TAstListNode {
  2289. public:
  2290. TWriteTableNode(TPosition pos, const TString& label, const TTableRef& table, EWriteColumnMode mode,
  2291. TNodePtr options, TScopedStatePtr scoped)
  2292. : TAstListNode(pos)
  2293. , Label(label)
  2294. , Table(table)
  2295. , Mode(mode)
  2296. , Options(options)
  2297. , Scoped(scoped)
  2298. {
  2299. scoped->UseCluster(Table.Service, Table.Cluster);
  2300. }
  2301. bool DoInit(TContext& ctx, ISource* src) override {
  2302. auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::WRITE);
  2303. if (!keys || !keys->Init(ctx, src)) {
  2304. return false;
  2305. }
  2306. auto getModesMap = [] (const TString& serviceName) -> const TMap<EWriteColumnMode, TString>& {
  2307. if (serviceName == KikimrProviderName || serviceName == YdbProviderName) {
  2308. return columnModeToStrMapKikimr;
  2309. } else if (serviceName == StatProviderName) {
  2310. return columnModeToStrMapStat;
  2311. } else {
  2312. return columnModeToStrMapMR;
  2313. }
  2314. };
  2315. auto options = Y();
  2316. if (Options) {
  2317. if (!Options->Init(ctx, src)) {
  2318. return false;
  2319. }
  2320. options = L(Options);
  2321. }
  2322. if (Mode != EWriteColumnMode::Default) {
  2323. auto modeStr = getModesMap(Table.Service).FindPtr(Mode);
  2324. options->Add(Q(Y(Q("mode"), Q(modeStr ? *modeStr : "unsupported"))));
  2325. }
  2326. Add("block", Q((Y(
  2327. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.Service), Scoped->WrapCluster(Table.Cluster, ctx))),
  2328. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Label, Q(options))),
  2329. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  2330. ))));
  2331. return TAstListNode::DoInit(ctx, src);
  2332. }
  2333. TPtr DoClone() const final {
  2334. return {};
  2335. }
  2336. private:
  2337. TString Label;
  2338. TTableRef Table;
  2339. EWriteColumnMode Mode;
  2340. TNodePtr Options;
  2341. TScopedStatePtr Scoped;
  2342. };
  2343. TNodePtr BuildWriteTable(TPosition pos, const TString& label, const TTableRef& table, EWriteColumnMode mode, TNodePtr options,
  2344. TScopedStatePtr scoped)
  2345. {
  2346. return new TWriteTableNode(pos, label, table, mode, std::move(options), scoped);
  2347. }
  2348. class TClustersSinkOperationBase: public TAstListNode {
  2349. protected:
  2350. TClustersSinkOperationBase(TPosition pos)
  2351. : TAstListNode(pos)
  2352. {}
  2353. virtual TPtr ProduceOperation() = 0;
  2354. bool DoInit(TContext& ctx, ISource* src) override {
  2355. auto block(Y());
  2356. auto op = ProduceOperation();
  2357. if (!op) {
  2358. return false;
  2359. }
  2360. block = L(block, op);
  2361. block = L(block, Y("return", "world"));
  2362. Add("block", Q(block));
  2363. return TAstListNode::DoInit(ctx, src);
  2364. }
  2365. TPtr DoClone() const final {
  2366. return {};
  2367. }
  2368. };
  2369. class TCommitClustersNode: public TClustersSinkOperationBase {
  2370. public:
  2371. TCommitClustersNode(TPosition pos)
  2372. : TClustersSinkOperationBase(pos)
  2373. {
  2374. }
  2375. TPtr ProduceOperation() override {
  2376. return Y("let", "world", Y("CommitAll!", "world"));
  2377. }
  2378. };
  2379. TNodePtr BuildCommitClusters(TPosition pos) {
  2380. return new TCommitClustersNode(pos);
  2381. }
  2382. class TRollbackClustersNode: public TClustersSinkOperationBase {
  2383. public:
  2384. TRollbackClustersNode(TPosition pos)
  2385. : TClustersSinkOperationBase(pos)
  2386. {
  2387. }
  2388. TPtr ProduceOperation() override {
  2389. return Y("let", "world", Y("CommitAll!", "world", Q(Y(Q(Y(Q("mode"), Q("rollback")))))));
  2390. }
  2391. };
  2392. TNodePtr BuildRollbackClusters(TPosition pos) {
  2393. return new TRollbackClustersNode(pos);
  2394. }
  2395. class TWriteResultNode final: public TAstListNode {
  2396. public:
  2397. TWriteResultNode(TPosition pos, const TString& label, TNodePtr settings)
  2398. : TAstListNode(pos)
  2399. , Label(label)
  2400. , Settings(settings)
  2401. , CommitClusters(BuildCommitClusters(Pos))
  2402. {}
  2403. bool DoInit(TContext& ctx, ISource* src) override {
  2404. auto block(Y(
  2405. Y("let", "result_sink", Y("DataSink", Q(TString(ResultProviderName)))),
  2406. Y("let", "world", Y(TString(WriteName), "world", "result_sink", Y("Key"), Label, Q(Settings)))
  2407. ));
  2408. if (ctx.PragmaAutoCommit) {
  2409. block = L(block, Y("let", "world", CommitClusters));
  2410. }
  2411. block = L(block, Y("return", Y(TString(CommitName), "world", "result_sink")));
  2412. Add("block", Q(block));
  2413. return TAstListNode::DoInit(ctx, src);
  2414. }
  2415. TPtr DoClone() const final {
  2416. return {};
  2417. }
  2418. private:
  2419. TString Label;
  2420. TNodePtr Settings;
  2421. TNodePtr CommitClusters;
  2422. };
  2423. TNodePtr BuildWriteResult(TPosition pos, const TString& label, TNodePtr settings) {
  2424. return new TWriteResultNode(pos, label, settings);
  2425. }
  2426. class TYqlProgramNode: public TAstListNode {
  2427. public:
  2428. TYqlProgramNode(TPosition pos, const TVector<TNodePtr>& blocks, bool topLevel, TScopedStatePtr scoped, bool useSeq)
  2429. : TAstListNode(pos)
  2430. , Blocks(blocks)
  2431. , TopLevel(topLevel)
  2432. , Scoped(scoped)
  2433. , UseSeq(useSeq)
  2434. {}
  2435. bool DoInit(TContext& ctx, ISource* src) override {
  2436. bool hasError = false;
  2437. INode::TPtr currentWorldsHolder;
  2438. INode::TPtr seqNode;
  2439. if (UseSeq) {
  2440. currentWorldsHolder = new TAstListNodeImpl(GetPos());
  2441. seqNode = new TAstListNodeImpl(GetPos());
  2442. seqNode->Add("Seq!","world");
  2443. }
  2444. INode* currentWorlds = UseSeq ? currentWorldsHolder.Get() : this;
  2445. auto flushCurrentWorlds = [&](bool changeSeq, bool finish) {
  2446. currentWorldsHolder->Add(Y("return","world"));
  2447. auto lambda = BuildLambda(GetPos(), Y("world"), Y("block", Q(currentWorldsHolder)));
  2448. seqNode->Add(lambda);
  2449. if (finish) {
  2450. Add(Y("let", "world", seqNode));
  2451. } else {
  2452. currentWorldsHolder = new TAstListNodeImpl(GetPos());
  2453. currentWorlds = currentWorldsHolder.Get();
  2454. }
  2455. if (changeSeq) {
  2456. Add(Y("let", "world", seqNode));
  2457. seqNode = new TAstListNodeImpl(GetPos());
  2458. seqNode->Add("Seq!","world");
  2459. }
  2460. };
  2461. if (TopLevel) {
  2462. for (auto& var: ctx.Variables) {
  2463. if (!var.second.second->Init(ctx, src)) {
  2464. hasError = true;
  2465. continue;
  2466. }
  2467. Add(Y(
  2468. "declare",
  2469. new TAstAtomNodeImpl(var.second.first, var.first, TNodeFlags::ArbitraryContent),
  2470. var.second.second));
  2471. }
  2472. for (const auto& overrideLibrary: ctx.OverrideLibraries) {
  2473. auto node = Y(
  2474. "override_library",
  2475. new TAstAtomNodeImpl(
  2476. std::get<TPosition>(overrideLibrary.second),
  2477. overrideLibrary.first, TNodeFlags::ArbitraryContent
  2478. ));
  2479. Add(node);
  2480. }
  2481. for (const auto& package: ctx.Packages) {
  2482. const auto& [url, urlPosition] = std::get<1U>(package.second);
  2483. auto node = Y(
  2484. "package",
  2485. new TAstAtomNodeImpl(
  2486. std::get<TPosition>(package.second), package.first,
  2487. TNodeFlags::ArbitraryContent
  2488. ),
  2489. new TAstAtomNodeImpl(urlPosition, url, TNodeFlags::ArbitraryContent));
  2490. if (const auto& tokenWithPosition = std::get<2U>(package.second)) {
  2491. const auto& [token, tokenPosition] = *tokenWithPosition;
  2492. node = L(node, new TAstAtomNodeImpl(tokenPosition, token, TNodeFlags::ArbitraryContent));
  2493. }
  2494. Add(node);
  2495. }
  2496. for (const auto& lib : ctx.Libraries) {
  2497. auto node = Y("library", new TAstAtomNodeImpl(std::get<TPosition>(lib.second), lib.first, TNodeFlags::ArbitraryContent));
  2498. if (const auto& first = std::get<1U>(lib.second)) {
  2499. node = L(node, new TAstAtomNodeImpl(first->second, first->first, TNodeFlags::ArbitraryContent));
  2500. if (const auto& second = std::get<2U>(lib.second)) {
  2501. node = L(node, new TAstAtomNodeImpl(second->second, second->first, TNodeFlags::ArbitraryContent));
  2502. }
  2503. }
  2504. Add(node);
  2505. }
  2506. for (const auto& p : ctx.PackageVersions) {
  2507. Add(Y("set_package_version", BuildQuotedAtom(Pos, p.first), BuildQuotedAtom(Pos, ToString(p.second))));
  2508. }
  2509. Add(Y("import", "aggregate_module", BuildQuotedAtom(Pos, "/lib/yql/aggregate.yql")));
  2510. Add(Y("import", "window_module", BuildQuotedAtom(Pos, "/lib/yql/window.yql")));
  2511. for (const auto& module : ctx.Settings.ModuleMapping) {
  2512. TString moduleName(module.first + "_module");
  2513. moduleName.to_lower();
  2514. Add(Y("import", moduleName, BuildQuotedAtom(Pos, module.second)));
  2515. }
  2516. for (const auto& moduleAlias : ctx.ImportModuleAliases) {
  2517. Add(Y("import", moduleAlias.second, BuildQuotedAtom(Pos, moduleAlias.first)));
  2518. }
  2519. for (const auto& x : ctx.SimpleUdfs) {
  2520. Add(Y("let", x.second, Y("Udf", BuildQuotedAtom(Pos, x.first))));
  2521. }
  2522. if (!ctx.CompactNamedExprs) {
  2523. for (auto& nodes: Scoped->NamedNodes) {
  2524. if (src || ctx.Exports.contains(nodes.first)) {
  2525. auto& item = nodes.second.front();
  2526. if (!item->Node->Init(ctx, src)) {
  2527. hasError = true;
  2528. continue;
  2529. }
  2530. // Some constants may be used directly by YQL code and need to be translated without reference from SQL AST
  2531. if (item->Node->IsConstant() || ctx.Exports.contains(nodes.first)) {
  2532. Add(Y("let", BuildAtom(item->Node->GetPos(), nodes.first), item->Node));
  2533. }
  2534. }
  2535. }
  2536. }
  2537. if (ctx.Settings.Mode != NSQLTranslation::ESqlMode::LIBRARY) {
  2538. auto configSource = Y("DataSource", BuildQuotedAtom(Pos, TString(ConfigProviderName)));
  2539. auto resultSink = Y("DataSink", BuildQuotedAtom(Pos, TString(ResultProviderName)));
  2540. for (const auto& warningPragma : ctx.WarningPolicy.GetRules()) {
  2541. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2542. BuildQuotedAtom(Pos, "Warning"), BuildQuotedAtom(Pos, warningPragma.GetPattern()),
  2543. BuildQuotedAtom(Pos, to_lower(ToString(warningPragma.GetAction()))))));
  2544. }
  2545. if (ctx.ResultSizeLimit > 0) {
  2546. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", resultSink,
  2547. BuildQuotedAtom(Pos, "SizeLimit"), BuildQuotedAtom(Pos, ToString(ctx.ResultSizeLimit)))));
  2548. }
  2549. if (!ctx.PragmaPullUpFlatMapOverJoin) {
  2550. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2551. BuildQuotedAtom(Pos, "DisablePullUpFlatMapOverJoin"))));
  2552. }
  2553. if (ctx.FilterPushdownOverJoinOptionalSide) {
  2554. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2555. BuildQuotedAtom(Pos, "FilterPushdownOverJoinOptionalSide"))));
  2556. }
  2557. if (!ctx.RotateJoinTree) {
  2558. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2559. BuildQuotedAtom(Pos, "RotateJoinTree"), BuildQuotedAtom(Pos, "false"))));
  2560. }
  2561. if (ctx.DiscoveryMode) {
  2562. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2563. BuildQuotedAtom(Pos, "DiscoveryMode"))));
  2564. }
  2565. if (ctx.DqEngineEnable) {
  2566. TString mode = "auto";
  2567. if (ctx.PqReadByRtmrCluster && ctx.PqReadByRtmrCluster != "dq") {
  2568. mode = "disable";
  2569. } else if (ctx.DqEngineForce) {
  2570. mode = "force";
  2571. }
  2572. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2573. BuildQuotedAtom(Pos, "DqEngine"), BuildQuotedAtom(Pos, mode))));
  2574. }
  2575. if (ctx.CostBasedOptimizer) {
  2576. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2577. BuildQuotedAtom(Pos, "CostBasedOptimizer"), BuildQuotedAtom(Pos, ctx.CostBasedOptimizer))));
  2578. }
  2579. if (ctx.JsonQueryReturnsJsonDocument.Defined()) {
  2580. TString pragmaName = "DisableJsonQueryReturnsJsonDocument";
  2581. if (*ctx.JsonQueryReturnsJsonDocument) {
  2582. pragmaName = "JsonQueryReturnsJsonDocument";
  2583. }
  2584. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource, BuildQuotedAtom(Pos, pragmaName))));
  2585. }
  2586. if (ctx.OrderedColumns) {
  2587. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2588. BuildQuotedAtom(Pos, "OrderedColumns"))));
  2589. }
  2590. if (ctx.PqReadByRtmrCluster) {
  2591. auto pqSourceAll = Y("DataSource", BuildQuotedAtom(Pos, TString(PqProviderName)), BuildQuotedAtom(Pos, "$all"));
  2592. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", pqSourceAll,
  2593. BuildQuotedAtom(Pos, "Attr"), BuildQuotedAtom(Pos, "PqReadByRtmrCluster_"), BuildQuotedAtom(Pos, ctx.PqReadByRtmrCluster))));
  2594. auto rtmrSourceAll = Y("DataSource", BuildQuotedAtom(Pos, TString(RtmrProviderName)), BuildQuotedAtom(Pos, "$all"));
  2595. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", rtmrSourceAll,
  2596. BuildQuotedAtom(Pos, "Attr"), BuildQuotedAtom(Pos, "PqReadByRtmrCluster_"), BuildQuotedAtom(Pos, ctx.PqReadByRtmrCluster))));
  2597. if (ctx.PqReadByRtmrCluster != "dq") {
  2598. // set any dynamic settings for particular RTMR cluster for CommitAll!
  2599. auto rtmrSource = Y("DataSource", BuildQuotedAtom(Pos, TString(RtmrProviderName)), BuildQuotedAtom(Pos, ctx.PqReadByRtmrCluster));
  2600. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", rtmrSource,
  2601. BuildQuotedAtom(Pos, "Attr"), BuildQuotedAtom(Pos, "Dummy_"), BuildQuotedAtom(Pos, "1"))));
  2602. }
  2603. }
  2604. if (ctx.YsonCastToString.Defined()) {
  2605. const TString pragmaName = *ctx.YsonCastToString ? "YsonCastToString" : "DisableYsonCastToString";
  2606. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource, BuildQuotedAtom(Pos, pragmaName))));
  2607. }
  2608. if (ctx.UseBlocks) {
  2609. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource, BuildQuotedAtom(Pos, "UseBlocks"))));
  2610. }
  2611. if (ctx.BlockEngineEnable) {
  2612. TString mode = ctx.BlockEngineForce ? "force" : "auto";
  2613. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2614. BuildQuotedAtom(Pos, "BlockEngine"), BuildQuotedAtom(Pos, mode))));
  2615. }
  2616. }
  2617. }
  2618. for (auto& block: Blocks) {
  2619. if (block->SubqueryAlias()) {
  2620. continue;
  2621. }
  2622. if (!block->Init(ctx, nullptr)) {
  2623. hasError = true;
  2624. continue;
  2625. }
  2626. }
  2627. for (const auto& x : Scoped->Local.ExprClusters) {
  2628. auto& data = Scoped->Local.ExprClustersMap[x.Get()];
  2629. auto& node = data.second;
  2630. if (!node->Init(ctx, nullptr)) {
  2631. hasError = true;
  2632. continue;
  2633. }
  2634. Add(Y("let", data.first, node));
  2635. }
  2636. if (UseSeq) {
  2637. flushCurrentWorlds(false, false);
  2638. }
  2639. for (auto& block: Blocks) {
  2640. const auto subqueryAliasPtr = block->SubqueryAlias();
  2641. if (subqueryAliasPtr) {
  2642. if (block->UsedSubquery()) {
  2643. if (UseSeq) {
  2644. flushCurrentWorlds(true, false);
  2645. }
  2646. const auto& ref = block->GetLabel();
  2647. YQL_ENSURE(!ref.empty());
  2648. Add(block);
  2649. currentWorlds->Add(Y("let", "world", Y("Nth", *subqueryAliasPtr, Q("0"))));
  2650. Add(Y("let", ref, Y("Nth", *subqueryAliasPtr, Q("1"))));
  2651. }
  2652. } else {
  2653. const auto& ref = block->GetLabel();
  2654. if (ref) {
  2655. Add(Y("let", ref, block));
  2656. } else {
  2657. currentWorlds->Add(Y("let", "world", block));
  2658. if (UseSeq) {
  2659. flushCurrentWorlds(false, false);
  2660. }
  2661. }
  2662. }
  2663. }
  2664. if (UseSeq) {
  2665. flushCurrentWorlds(false, true);
  2666. }
  2667. if (TopLevel) {
  2668. if (ctx.UniversalAliases) {
  2669. decltype(Nodes) preparedNodes;
  2670. preparedNodes.swap(Nodes);
  2671. for (const auto& [name, node] : ctx.UniversalAliases) {
  2672. Add(Y("let", name, node));
  2673. }
  2674. Nodes.insert(Nodes.end(), preparedNodes.begin(), preparedNodes.end());
  2675. }
  2676. decltype(Nodes) imports;
  2677. for (const auto& [alias, path]: ctx.RequiredModules) {
  2678. imports.push_back(Y("import", alias, BuildQuotedAtom(Pos, path)));
  2679. }
  2680. Nodes.insert(Nodes.begin(), std::make_move_iterator(imports.begin()), std::make_move_iterator(imports.end()));
  2681. for (const auto& symbol: ctx.Exports) {
  2682. if (ctx.CompactNamedExprs) {
  2683. auto node = Scoped->LookupNode(symbol);
  2684. YQL_ENSURE(node);
  2685. if (!node->Init(ctx, src)) {
  2686. hasError = true;
  2687. continue;
  2688. }
  2689. Add(Y("let", BuildAtom(node->GetPos(), symbol), node));
  2690. }
  2691. Add(Y("export", symbol));
  2692. }
  2693. }
  2694. if (!TopLevel || ctx.Settings.Mode != NSQLTranslation::ESqlMode::LIBRARY) {
  2695. Add(Y("return", "world"));
  2696. }
  2697. return !hasError;
  2698. }
  2699. TPtr DoClone() const final {
  2700. return {};
  2701. }
  2702. private:
  2703. TVector<TNodePtr> Blocks;
  2704. const bool TopLevel;
  2705. TScopedStatePtr Scoped;
  2706. const bool UseSeq;
  2707. };
  2708. TNodePtr BuildQuery(TPosition pos, const TVector<TNodePtr>& blocks, bool topLevel, TScopedStatePtr scoped, bool useSeq) {
  2709. return new TYqlProgramNode(pos, blocks, topLevel, scoped, useSeq);
  2710. }
  2711. class TPragmaNode final: public INode {
  2712. public:
  2713. TPragmaNode(TPosition pos, const TString& prefix, const TString& name, const TVector<TDeferredAtom>& values, bool valueDefault)
  2714. : INode(pos)
  2715. , Prefix(prefix)
  2716. , Name(name)
  2717. , Values(values)
  2718. , ValueDefault(valueDefault)
  2719. {
  2720. FakeSource = BuildFakeSource(pos);
  2721. }
  2722. bool DoInit(TContext& ctx, ISource* src) override {
  2723. Y_UNUSED(src);
  2724. TString serviceName;
  2725. TString cluster;
  2726. if (std::find(Providers.cbegin(), Providers.cend(), Prefix) != Providers.cend()) {
  2727. cluster = "$all";
  2728. serviceName = Prefix;
  2729. } else {
  2730. serviceName = *ctx.GetClusterProvider(Prefix, cluster);
  2731. }
  2732. auto datasource = Y("DataSource", BuildQuotedAtom(Pos, serviceName));
  2733. if (Prefix != ConfigProviderName) {
  2734. datasource = L(datasource, BuildQuotedAtom(Pos, cluster));
  2735. }
  2736. Node = Y();
  2737. Node = L(Node, AstNode(TString(ConfigureName)));
  2738. Node = L(Node, AstNode(TString(TStringBuf("world"))));
  2739. Node = L(Node, datasource);
  2740. if (Name == TStringBuf("flags")) {
  2741. for (ui32 i = 0; i < Values.size(); ++i) {
  2742. Node = L(Node, Values[i].Build());
  2743. }
  2744. }
  2745. else if (Name == TStringBuf("AddFileByUrl") || Name == TStringBuf("SetFileOption") || Name == TStringBuf("AddFolderByUrl") || Name == TStringBuf("ImportUdfs") || Name == TStringBuf("SetPackageVersion")) {
  2746. Node = L(Node, BuildQuotedAtom(Pos, Name));
  2747. for (ui32 i = 0; i < Values.size(); ++i) {
  2748. Node = L(Node, Values[i].Build());
  2749. }
  2750. }
  2751. else if (Name == TStringBuf("auth")) {
  2752. Node = L(Node, BuildQuotedAtom(Pos, "Auth"));
  2753. Node = L(Node, Values.empty() ? BuildQuotedAtom(Pos, TString()) : Values.front().Build());
  2754. }
  2755. else {
  2756. Node = L(Node, BuildQuotedAtom(Pos, "Attr"));
  2757. Node = L(Node, BuildQuotedAtom(Pos, Name));
  2758. if (!ValueDefault) {
  2759. Node = L(Node, Values.empty() ? BuildQuotedAtom(Pos, TString()) : Values.front().Build());
  2760. }
  2761. }
  2762. if (!Node->Init(ctx, FakeSource.Get())) {
  2763. return false;
  2764. }
  2765. return true;
  2766. }
  2767. TAstNode* Translate(TContext& ctx) const final {
  2768. return Node->Translate(ctx);
  2769. }
  2770. TPtr DoClone() const final {
  2771. return {};
  2772. }
  2773. private:
  2774. TString Prefix;
  2775. TString Name;
  2776. TVector<TDeferredAtom> Values;
  2777. bool ValueDefault;
  2778. TNodePtr Node;
  2779. TSourcePtr FakeSource;
  2780. };
  2781. TNodePtr BuildPragma(TPosition pos, const TString& prefix, const TString& name, const TVector<TDeferredAtom>& values, bool valueDefault) {
  2782. return new TPragmaNode(pos, prefix, name, values, valueDefault);
  2783. }
  2784. class TSqlLambda final: public TAstListNode {
  2785. public:
  2786. TSqlLambda(TPosition pos, TVector<TString>&& args, TVector<TNodePtr>&& exprSeq)
  2787. : TAstListNode(pos)
  2788. , Args(args)
  2789. , ExprSeq(exprSeq)
  2790. {
  2791. FakeSource = BuildFakeSource(pos);
  2792. }
  2793. bool DoInit(TContext& ctx, ISource* src) override {
  2794. Y_UNUSED(src);
  2795. for (auto& exprPtr: ExprSeq) {
  2796. if (!exprPtr->Init(ctx, FakeSource.Get())) {
  2797. return {};
  2798. }
  2799. }
  2800. YQL_ENSURE(!ExprSeq.empty());
  2801. auto body = Y();
  2802. auto end = ExprSeq.end() - 1;
  2803. for (auto iter = ExprSeq.begin(); iter != end; ++iter) {
  2804. auto exprPtr = *iter;
  2805. const auto& label = exprPtr->GetLabel();
  2806. YQL_ENSURE(label);
  2807. body = L(body, Y("let", label, exprPtr));
  2808. }
  2809. body = Y("block", Q(L(body, Y("return", *end))));
  2810. auto args = Y();
  2811. for (const auto& arg: Args) {
  2812. args = L(args, BuildAtom(GetPos(), arg));
  2813. }
  2814. Add("lambda", Q(args), body);
  2815. return TAstListNode::DoInit(ctx, src);
  2816. }
  2817. TPtr DoClone() const final {
  2818. return new TSqlLambda(Pos, TVector<TString>(Args), CloneContainer(ExprSeq));
  2819. }
  2820. void DoUpdateState() const override {
  2821. State.Set(ENodeState::Const);
  2822. }
  2823. private:
  2824. TVector<TString> Args;
  2825. TVector<TNodePtr> ExprSeq;
  2826. TSourcePtr FakeSource;
  2827. };
  2828. TNodePtr BuildSqlLambda(TPosition pos, TVector<TString>&& args, TVector<TNodePtr>&& exprSeq) {
  2829. return new TSqlLambda(pos, std::move(args), std::move(exprSeq));
  2830. }
  2831. class TWorldIf final : public TAstListNode {
  2832. public:
  2833. TWorldIf(TPosition pos, TNodePtr predicate, TNodePtr thenNode, TNodePtr elseNode, bool isEvaluate)
  2834. : TAstListNode(pos)
  2835. , Predicate(predicate)
  2836. , ThenNode(thenNode)
  2837. , ElseNode(elseNode)
  2838. , IsEvaluate(isEvaluate)
  2839. {
  2840. FakeSource = BuildFakeSource(pos);
  2841. }
  2842. bool DoInit(TContext& ctx, ISource* src) override {
  2843. if (!Predicate->Init(ctx, FakeSource.Get())) {
  2844. return{};
  2845. }
  2846. Add(IsEvaluate ? "EvaluateIf!" : "If!");
  2847. Add("world");
  2848. auto coalesced = Y("Coalesce", Predicate, Y("Bool", Q("false")));
  2849. Add(IsEvaluate ? Y("EvaluateExpr", Y("EnsureType", coalesced, Y("DataType", Q("Bool")))) : coalesced);
  2850. if (!ThenNode->Init(ctx, FakeSource.Get())) {
  2851. return{};
  2852. }
  2853. Add(ThenNode);
  2854. if (ElseNode) {
  2855. if (!ElseNode->Init(ctx, FakeSource.Get())) {
  2856. return{};
  2857. }
  2858. Add(ElseNode);
  2859. }
  2860. return TAstListNode::DoInit(ctx, src);
  2861. }
  2862. TPtr DoClone() const final {
  2863. return new TWorldIf(GetPos(), SafeClone(Predicate), SafeClone(ThenNode), SafeClone(ElseNode), IsEvaluate);
  2864. }
  2865. private:
  2866. TNodePtr Predicate;
  2867. TNodePtr ThenNode;
  2868. TNodePtr ElseNode;
  2869. bool IsEvaluate;
  2870. TSourcePtr FakeSource;
  2871. };
  2872. TNodePtr BuildWorldIfNode(TPosition pos, TNodePtr predicate, TNodePtr thenNode, TNodePtr elseNode, bool isEvaluate) {
  2873. return new TWorldIf(pos, predicate, thenNode, elseNode, isEvaluate);
  2874. }
  2875. class TWorldFor final : public TAstListNode {
  2876. public:
  2877. TWorldFor(TPosition pos, TNodePtr list, TNodePtr bodyNode, TNodePtr elseNode, bool isEvaluate, bool isParallel)
  2878. : TAstListNode(pos)
  2879. , List(list)
  2880. , BodyNode(bodyNode)
  2881. , ElseNode(elseNode)
  2882. , IsEvaluate(isEvaluate)
  2883. , IsParallel(isParallel)
  2884. {
  2885. FakeSource = BuildFakeSource(pos);
  2886. }
  2887. bool DoInit(TContext& ctx, ISource* src) override {
  2888. if (!List->Init(ctx, FakeSource.Get())) {
  2889. return{};
  2890. }
  2891. Add(TStringBuilder() << (IsEvaluate ? "Evaluate": "") << (IsParallel ? "Parallel" : "") << "For!");
  2892. Add("world");
  2893. Add(IsEvaluate ? Y("EvaluateExpr", List) : List);
  2894. if (!BodyNode->Init(ctx, FakeSource.Get())) {
  2895. return{};
  2896. }
  2897. Add(BodyNode);
  2898. if (ElseNode) {
  2899. if (!ElseNode->Init(ctx, FakeSource.Get())) {
  2900. return{};
  2901. }
  2902. Add(ElseNode);
  2903. }
  2904. return TAstListNode::DoInit(ctx, src);
  2905. }
  2906. TPtr DoClone() const final {
  2907. return new TWorldFor(GetPos(), SafeClone(List), SafeClone(BodyNode), SafeClone(ElseNode), IsEvaluate, IsParallel);
  2908. }
  2909. private:
  2910. TNodePtr List;
  2911. TNodePtr BodyNode;
  2912. TNodePtr ElseNode;
  2913. bool IsEvaluate;
  2914. bool IsParallel;
  2915. TSourcePtr FakeSource;
  2916. };
  2917. TNodePtr BuildWorldForNode(TPosition pos, TNodePtr list, TNodePtr bodyNode, TNodePtr elseNode, bool isEvaluate, bool isParallel) {
  2918. return new TWorldFor(pos, list, bodyNode, elseNode, isEvaluate, isParallel);
  2919. }
  2920. class TAnalyzeNode final: public TAstListNode {
  2921. public:
  2922. TAnalyzeNode(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TAnalyzeParams& params, TScopedStatePtr scoped)
  2923. : TAstListNode(pos)
  2924. , Service(service)
  2925. , Cluster(cluster)
  2926. , Params(params)
  2927. , Scoped(scoped)
  2928. {
  2929. FakeSource = BuildFakeSource(pos);
  2930. scoped->UseCluster(Service, Cluster);
  2931. }
  2932. bool DoInit(TContext& ctx, ISource* src) override {
  2933. Y_UNUSED(src);
  2934. auto keys = Params.Table->Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::DROP);
  2935. if (!keys || !keys->Init(ctx, FakeSource.Get())) {
  2936. return false;
  2937. }
  2938. auto opts = Y();
  2939. auto columns = Y();
  2940. for (const auto& column: Params.Columns) {
  2941. columns->Add(Q(column));
  2942. }
  2943. opts->Add(Q(Y(Q("columns"), Q(columns))));
  2944. opts->Add(Q(Y(Q("mode"), Q("analyze"))));
  2945. Add("block", Q(Y(
  2946. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), Scoped->WrapCluster(Cluster, ctx))),
  2947. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  2948. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  2949. )));
  2950. return TAstListNode::DoInit(ctx, FakeSource.Get());
  2951. }
  2952. TPtr DoClone() const final {
  2953. return {};
  2954. }
  2955. private:
  2956. TString Service;
  2957. TDeferredAtom Cluster;
  2958. TAnalyzeParams Params;
  2959. TScopedStatePtr Scoped;
  2960. TSourcePtr FakeSource;
  2961. };
  2962. TNodePtr BuildAnalyze(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TAnalyzeParams& params, TScopedStatePtr scoped) {
  2963. return new TAnalyzeNode(pos, service, cluster, params, scoped);
  2964. }
  2965. class TBaseBackupCollectionNode
  2966. : public TAstListNode
  2967. , public TObjectOperatorContext
  2968. {
  2969. using TBase = TAstListNode;
  2970. public:
  2971. TBaseBackupCollectionNode(
  2972. TPosition pos,
  2973. const TString& prefix,
  2974. const TString& objectId,
  2975. const TObjectOperatorContext& context)
  2976. : TBase(pos)
  2977. , TObjectOperatorContext(context)
  2978. , Prefix(prefix)
  2979. , Id(objectId)
  2980. {}
  2981. bool DoInit(TContext& ctx, ISource* src) final {
  2982. auto keys = Y("Key");
  2983. keys = L(keys, Q(Y(Q("backupCollection"), Y("String", BuildQuotedAtom(Pos, Id)), Y("String", BuildQuotedAtom(Pos, Prefix)))));
  2984. auto options = this->FillOptions(ctx, Y());
  2985. Add("block", Q(Y(
  2986. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
  2987. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(options))),
  2988. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  2989. )));
  2990. return TAstListNode::DoInit(ctx, src);
  2991. }
  2992. virtual INode::TPtr FillOptions(TContext& ctx, INode::TPtr options) const = 0;
  2993. protected:
  2994. TString Prefix;
  2995. TString Id;
  2996. };
  2997. class TCreateBackupCollectionNode
  2998. : public TBaseBackupCollectionNode
  2999. {
  3000. using TBase = TBaseBackupCollectionNode;
  3001. public:
  3002. TCreateBackupCollectionNode(
  3003. TPosition pos,
  3004. const TString& prefix,
  3005. const TString& objectId,
  3006. const TCreateBackupCollectionParameters& params,
  3007. const TObjectOperatorContext& context)
  3008. : TBase(pos, prefix, objectId, context)
  3009. , Params(params)
  3010. {}
  3011. virtual INode::TPtr FillOptions(TContext& ctx, INode::TPtr options) const final {
  3012. options->Add(Q(Y(Q("mode"), Q("create"))));
  3013. auto settings = Y();
  3014. for (auto& [key, value] : Params.Settings) {
  3015. settings->Add(Q(Y(BuildQuotedAtom(Pos, key), Y("String", value.Build()))));
  3016. }
  3017. options->Add(Q(Y(Q("settings"), Q(settings))));
  3018. auto entries = Y();
  3019. if (Params.Database) {
  3020. entries->Add(Q(Y(Q(Y(Q("type"), Q("database"))))));
  3021. }
  3022. for (auto& table : Params.Tables) {
  3023. auto path = ctx.GetPrefixedPath(ServiceId, Cluster, table);
  3024. entries->Add(Q(Y(Q(Y(Q("type"), Q("table"))), Q(Y(Q("path"), path)))));
  3025. }
  3026. options->Add(Q(Y(Q("entries"), Q(entries))));
  3027. return options;
  3028. }
  3029. TPtr DoClone() const final {
  3030. return new TCreateBackupCollectionNode(GetPos(), Prefix, Id, Params, *this);
  3031. }
  3032. private:
  3033. TCreateBackupCollectionParameters Params;
  3034. };
  3035. class TAlterBackupCollectionNode
  3036. : public TBaseBackupCollectionNode
  3037. {
  3038. using TBase = TBaseBackupCollectionNode;
  3039. public:
  3040. TAlterBackupCollectionNode(
  3041. TPosition pos,
  3042. const TString& prefix,
  3043. const TString& objectId,
  3044. const TAlterBackupCollectionParameters& params,
  3045. const TObjectOperatorContext& context)
  3046. : TBase(pos, prefix, objectId, context)
  3047. , Params(params)
  3048. {}
  3049. virtual INode::TPtr FillOptions(TContext& ctx, INode::TPtr options) const final {
  3050. options->Add(Q(Y(Q("mode"), Q("alter"))));
  3051. auto settings = Y();
  3052. for (auto& [key, value] : Params.Settings) {
  3053. settings->Add(Q(Y(BuildQuotedAtom(Pos, key), Y("String", value.Build()))));
  3054. }
  3055. options->Add(Q(Y(Q("settings"), Q(settings))));
  3056. auto resetSettings = Y();
  3057. for (auto& key : Params.SettingsToReset) {
  3058. resetSettings->Add(BuildQuotedAtom(Pos, key));
  3059. }
  3060. options->Add(Q(Y(Q("resetSettings"), Q(resetSettings))));
  3061. auto entries = Y();
  3062. if (Params.Database != TAlterBackupCollectionParameters::EDatabase::Unchanged) {
  3063. entries->Add(Q(Y(Q(Y(Q("type"), Q("database"))), Q(Y(Q("action"), Q(Params.Database == TAlterBackupCollectionParameters::EDatabase::Add ? "add" : "drop"))))));
  3064. }
  3065. for (auto& table : Params.TablesToAdd) {
  3066. auto path = ctx.GetPrefixedPath(ServiceId, Cluster, table);
  3067. entries->Add(Q(Y(Q(Y(Q("type"), Q("table"))), Q(Y(Q("path"), path)), Q(Y(Q("action"), Q("add"))))));
  3068. }
  3069. for (auto& table : Params.TablesToDrop) {
  3070. auto path = ctx.GetPrefixedPath(ServiceId, Cluster, table);
  3071. entries->Add(Q(Y(Q(Y(Q("type"), Q("table"))), Q(Y(Q("path"), path)), Q(Y(Q("action"), Q("drop"))))));
  3072. }
  3073. options->Add(Q(Y(Q("alterEntries"), Q(entries))));
  3074. return options;
  3075. }
  3076. TPtr DoClone() const final {
  3077. return new TAlterBackupCollectionNode(GetPos(), Prefix, Id, Params, *this);
  3078. }
  3079. private:
  3080. TAlterBackupCollectionParameters Params;
  3081. };
  3082. class TDropBackupCollectionNode
  3083. : public TBaseBackupCollectionNode
  3084. {
  3085. using TBase = TBaseBackupCollectionNode;
  3086. public:
  3087. TDropBackupCollectionNode(
  3088. TPosition pos,
  3089. const TString& prefix,
  3090. const TString& objectId,
  3091. const TDropBackupCollectionParameters&,
  3092. const TObjectOperatorContext& context)
  3093. : TBase(pos, prefix, objectId, context)
  3094. {}
  3095. virtual INode::TPtr FillOptions(TContext&, INode::TPtr options) const final {
  3096. options->Add(Q(Y(Q("mode"), Q("drop"))));
  3097. return options;
  3098. }
  3099. TPtr DoClone() const final {
  3100. TDropBackupCollectionParameters params;
  3101. return new TDropBackupCollectionNode(GetPos(), Prefix, Id, params, *this);
  3102. }
  3103. };
  3104. TNodePtr BuildCreateBackupCollection(
  3105. TPosition pos,
  3106. const TString& prefix,
  3107. const TString& id,
  3108. const TCreateBackupCollectionParameters& params,
  3109. const TObjectOperatorContext& context)
  3110. {
  3111. return new TCreateBackupCollectionNode(pos, prefix, id, params, context);
  3112. }
  3113. TNodePtr BuildAlterBackupCollection(
  3114. TPosition pos,
  3115. const TString& prefix,
  3116. const TString& id,
  3117. const TAlterBackupCollectionParameters& params,
  3118. const TObjectOperatorContext& context)
  3119. {
  3120. return new TAlterBackupCollectionNode(pos, prefix, id, params, context);
  3121. }
  3122. TNodePtr BuildDropBackupCollection(
  3123. TPosition pos,
  3124. const TString& prefix,
  3125. const TString& id,
  3126. const TDropBackupCollectionParameters& params,
  3127. const TObjectOperatorContext& context)
  3128. {
  3129. return new TDropBackupCollectionNode(pos, prefix, id, params, context);
  3130. }
  3131. class TBackupNode final
  3132. : public TAstListNode
  3133. , public TObjectOperatorContext
  3134. {
  3135. using TBase = TAstListNode;
  3136. public:
  3137. TBackupNode(
  3138. TPosition pos,
  3139. const TString& prefix,
  3140. const TString& id,
  3141. const TBackupParameters& params,
  3142. const TObjectOperatorContext& context)
  3143. : TBase(pos)
  3144. , TObjectOperatorContext(context)
  3145. , Prefix(prefix)
  3146. , Id(id)
  3147. , Params(params)
  3148. {
  3149. Y_UNUSED(Params);
  3150. }
  3151. bool DoInit(TContext& ctx, ISource* src) override {
  3152. auto keys = Y("Key");
  3153. keys = L(keys, Q(Y(Q("backup"), Y("String", BuildQuotedAtom(Pos, Id)), Y("String", BuildQuotedAtom(Pos, Prefix)))));
  3154. auto opts = Y();
  3155. if (Params.Incremental) {
  3156. opts->Add(Q(Y(Q("mode"), Q("backupIncremental"))));
  3157. } else {
  3158. opts->Add(Q(Y(Q("mode"), Q("backup"))));
  3159. }
  3160. Add("block", Q(Y(
  3161. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
  3162. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  3163. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  3164. )));
  3165. return TAstListNode::DoInit(ctx, src);
  3166. }
  3167. TPtr DoClone() const final {
  3168. return new TBackupNode(GetPos(), Prefix, Id, Params, *this);
  3169. }
  3170. private:
  3171. TString Prefix;
  3172. TString Id;
  3173. TBackupParameters Params;
  3174. };
  3175. TNodePtr BuildBackup(
  3176. TPosition pos,
  3177. const TString& prefix,
  3178. const TString& id,
  3179. const TBackupParameters& params,
  3180. const TObjectOperatorContext& context)
  3181. {
  3182. return new TBackupNode(pos, prefix, id, params, context);
  3183. }
  3184. class TRestoreNode final
  3185. : public TAstListNode
  3186. , public TObjectOperatorContext
  3187. {
  3188. using TBase = TAstListNode;
  3189. public:
  3190. TRestoreNode(
  3191. TPosition pos,
  3192. const TString& prefix,
  3193. const TString& id,
  3194. const TRestoreParameters& params,
  3195. const TObjectOperatorContext& context)
  3196. : TBase(pos)
  3197. , TObjectOperatorContext(context)
  3198. , Prefix(prefix)
  3199. , Id(id)
  3200. , Params(params)
  3201. {
  3202. Y_UNUSED(Params);
  3203. }
  3204. bool DoInit(TContext& ctx, ISource* src) override {
  3205. auto keys = Y("Key");
  3206. keys = L(keys, Q(Y(Q("restore"), Y("String", BuildQuotedAtom(Pos, Id)), Y("String", BuildQuotedAtom(Pos, Prefix)))));
  3207. auto opts = Y();
  3208. opts->Add(Q(Y(Q("mode"), Q("restore"))));
  3209. if (Params.At) {
  3210. opts->Add(Q(Y(Q("at"), BuildQuotedAtom(Pos, Params.At))));
  3211. }
  3212. Add("block", Q(Y(
  3213. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
  3214. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  3215. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  3216. )));
  3217. return TAstListNode::DoInit(ctx, src);
  3218. }
  3219. TPtr DoClone() const final {
  3220. return new TRestoreNode(GetPos(), Prefix, Id, Params, *this);
  3221. }
  3222. private:
  3223. TString Prefix;
  3224. TString Id;
  3225. TRestoreParameters Params;
  3226. };
  3227. TNodePtr BuildRestore(
  3228. TPosition pos,
  3229. const TString& prefix,
  3230. const TString& id,
  3231. const TRestoreParameters& params,
  3232. const TObjectOperatorContext& context)
  3233. {
  3234. return new TRestoreNode(pos, prefix, id, params, context);
  3235. }
  3236. } // namespace NSQLTranslationV1