query.cpp 147 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062
  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.BarriersInterval) {
  335. settings = node.L(settings, node.Q(node.Y(node.Q("barriers_interval"), desc.Settings.BarriersInterval)));
  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 TAlterDatabaseNode final : public TAstListNode {
  1155. public:
  1156. TAlterDatabaseNode(
  1157. TPosition pos,
  1158. const TString& service,
  1159. const TDeferredAtom& cluster,
  1160. const TAlterDatabaseParameters& params,
  1161. TScopedStatePtr scoped
  1162. )
  1163. : TAstListNode(pos)
  1164. , Params(params)
  1165. , Scoped(scoped)
  1166. , Cluster(cluster)
  1167. , Service(service)
  1168. {
  1169. scoped->UseCluster(service, cluster);
  1170. }
  1171. bool DoInit(TContext& ctx, ISource* src) override {
  1172. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  1173. auto options = Y(Q(Y(Q("mode"), Q("alterDatabase"))));
  1174. if (Params.Owner.has_value()) {
  1175. options = L(options, Q(Y(Q("owner"), Params.Owner.value().Build())));
  1176. }
  1177. Add("block", Q(Y(
  1178. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)),
  1179. Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("databasePath"), Y("String", Params.DbPath.Build())))), Y("Void"), Q(options))),
  1180. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1181. )));
  1182. return TAstListNode::DoInit(ctx, src);
  1183. }
  1184. TPtr DoClone() const final {
  1185. return {};
  1186. }
  1187. private:
  1188. const TAlterDatabaseParameters Params;
  1189. TScopedStatePtr Scoped;
  1190. TDeferredAtom Cluster;
  1191. TString Service;
  1192. };
  1193. TNodePtr BuildAlterDatabase(
  1194. TPosition pos,
  1195. const TString& service,
  1196. const TDeferredAtom& cluster,
  1197. const TAlterDatabaseParameters& params,
  1198. TScopedStatePtr scoped
  1199. ) {
  1200. return new TAlterDatabaseNode(
  1201. pos,
  1202. service,
  1203. cluster,
  1204. params,
  1205. scoped
  1206. );
  1207. }
  1208. class TAlterTableNode final : public TAstListNode {
  1209. public:
  1210. TAlterTableNode(TPosition pos, const TTableRef& tr, const TAlterTableParameters& params, TScopedStatePtr scoped)
  1211. : TAstListNode(pos)
  1212. , Table(tr)
  1213. , Params(params)
  1214. , Scoped(scoped)
  1215. {
  1216. scoped->UseCluster(Table.Service, Table.Cluster);
  1217. }
  1218. bool DoInit(TContext& ctx, ISource* src) override {
  1219. auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
  1220. if (!keys || !keys->Init(ctx, src)) {
  1221. return false;
  1222. }
  1223. auto actions = Y();
  1224. if (Params.AddColumns) {
  1225. auto columns = Y();
  1226. for (auto& col : Params.AddColumns) {
  1227. auto columnDesc = Y();
  1228. columnDesc = L(columnDesc, BuildQuotedAtom(Pos, col.Name));
  1229. auto type = col.Type;
  1230. if (col.Nullable) {
  1231. type = Y("AsOptionalType", type);
  1232. }
  1233. columnDesc = L(columnDesc, type);
  1234. auto columnConstraints = Y();
  1235. if (!col.Nullable) {
  1236. columnConstraints = L(columnConstraints, Q(Y(Q("not_null"))));
  1237. }
  1238. if (col.Serial) {
  1239. columnConstraints = L(columnConstraints, Q(Y(Q("serial"))));
  1240. }
  1241. if (col.DefaultExpr) {
  1242. if (!col.DefaultExpr->Init(ctx, src)) {
  1243. return false;
  1244. }
  1245. columnConstraints = L(columnConstraints, Q(Y(Q("default"), col.DefaultExpr)));
  1246. }
  1247. columnDesc = L(columnDesc, Q(Y(Q("columnConstrains"), Q(columnConstraints))));
  1248. auto familiesDesc = Y();
  1249. for (const auto& family : col.Families) {
  1250. familiesDesc = L(familiesDesc, BuildQuotedAtom(family.Pos, family.Name));
  1251. }
  1252. columnDesc = L(columnDesc, Q(familiesDesc));
  1253. columns = L(columns, Q(columnDesc));
  1254. }
  1255. actions = L(actions, Q(Y(Q("addColumns"), Q(columns))));
  1256. }
  1257. if (Params.DropColumns) {
  1258. auto columns = Y();
  1259. for (auto& colName : Params.DropColumns) {
  1260. columns = L(columns, BuildQuotedAtom(Pos, colName));
  1261. }
  1262. actions = L(actions, Q(Y(Q("dropColumns"), Q(columns))));
  1263. }
  1264. if (Params.AlterColumns) {
  1265. auto columns = Y();
  1266. for (auto& col : Params.AlterColumns) {
  1267. if (col.TypeOfChange == TColumnSchema::ETypeOfChange::DropNotNullConstraint) {
  1268. auto columnDesc = Y();
  1269. columnDesc = L(columnDesc, BuildQuotedAtom(Pos, col.Name));
  1270. auto columnConstraints = Y();
  1271. columnConstraints = L(columnConstraints, Q(Y(Q("drop_not_null"))));
  1272. columnDesc = L(columnDesc, Q(Y(Q("changeColumnConstraints"), Q(columnConstraints))));
  1273. columns = L(columns, Q(columnDesc));
  1274. } else if (col.TypeOfChange == TColumnSchema::ETypeOfChange::SetNotNullConstraint) {
  1275. // todo flown4qqqq
  1276. } else if (col.TypeOfChange == TColumnSchema::ETypeOfChange::SetFamily) {
  1277. auto columnDesc = Y();
  1278. columnDesc = L(columnDesc, BuildQuotedAtom(Pos, col.Name));
  1279. auto familiesDesc = Y();
  1280. for (const auto& family : col.Families) {
  1281. familiesDesc = L(familiesDesc, BuildQuotedAtom(family.Pos, family.Name));
  1282. }
  1283. columnDesc = L(columnDesc, Q(Y(Q("setFamily"), Q(familiesDesc))));
  1284. columns = L(columns, Q(columnDesc));
  1285. } else if (col.TypeOfChange == TColumnSchema::ETypeOfChange::Nothing) {
  1286. // do nothing
  1287. } else {
  1288. ctx.Error(Pos) << " action is not supported";
  1289. }
  1290. }
  1291. actions = L(actions, Q(Y(Q("alterColumns"), Q(columns))));
  1292. }
  1293. if (Params.AddColumnFamilies) {
  1294. auto columnFamilies = Y();
  1295. for (const auto& family : Params.AddColumnFamilies) {
  1296. auto familyDesc = Y();
  1297. familyDesc = L(familyDesc, Q(Y(Q("name"), BuildQuotedAtom(family.Name.Pos, family.Name.Name))));
  1298. if (family.Data) {
  1299. familyDesc = L(familyDesc, Q(Y(Q("data"), family.Data)));
  1300. }
  1301. if (family.Compression) {
  1302. familyDesc = L(familyDesc, Q(Y(Q("compression"), family.Compression)));
  1303. }
  1304. if (family.CompressionLevel) {
  1305. familyDesc = L(familyDesc, Q(Y(Q("compression_level"), family.CompressionLevel)));
  1306. }
  1307. columnFamilies = L(columnFamilies, Q(familyDesc));
  1308. }
  1309. actions = L(actions, Q(Y(Q("addColumnFamilies"), Q(columnFamilies))));
  1310. }
  1311. if (Params.AlterColumnFamilies) {
  1312. auto columnFamilies = Y();
  1313. for (const auto& family : Params.AlterColumnFamilies) {
  1314. auto familyDesc = Y();
  1315. familyDesc = L(familyDesc, Q(Y(Q("name"), BuildQuotedAtom(family.Name.Pos, family.Name.Name))));
  1316. if (family.Data) {
  1317. familyDesc = L(familyDesc, Q(Y(Q("data"), family.Data)));
  1318. }
  1319. if (family.Compression) {
  1320. familyDesc = L(familyDesc, Q(Y(Q("compression"), family.Compression)));
  1321. }
  1322. if (family.CompressionLevel) {
  1323. familyDesc = L(familyDesc, Q(Y(Q("compression_level"), family.CompressionLevel)));
  1324. }
  1325. columnFamilies = L(columnFamilies, Q(familyDesc));
  1326. }
  1327. actions = L(actions, Q(Y(Q("alterColumnFamilies"), Q(columnFamilies))));
  1328. }
  1329. if (Params.TableSettings.IsSet()) {
  1330. actions = L(actions, Q(Y(Q("setTableSettings"), Q(
  1331. CreateTableSettings(Params.TableSettings, ETableSettingsParsingMode::Alter, *this)
  1332. ))));
  1333. }
  1334. for (const auto& index : Params.AddIndexes) {
  1335. const auto& desc = CreateIndexDesc(index, ETableSettingsParsingMode::Alter, *this);
  1336. actions = L(actions, Q(Y(Q("addIndex"), Q(desc))));
  1337. }
  1338. for (const auto& index : Params.AlterIndexes) {
  1339. const auto& desc = CreateAlterIndex(index, *this);
  1340. actions = L(actions, Q(Y(Q("alterIndex"), Q(desc))));
  1341. }
  1342. for (const auto& id : Params.DropIndexes) {
  1343. auto indexName = BuildQuotedAtom(id.Pos, id.Name);
  1344. actions = L(actions, Q(Y(Q("dropIndex"), indexName)));
  1345. }
  1346. if (Params.RenameIndexTo) {
  1347. auto src = BuildQuotedAtom(Params.RenameIndexTo->first.Pos, Params.RenameIndexTo->first.Name);
  1348. auto dst = BuildQuotedAtom(Params.RenameIndexTo->second.Pos, Params.RenameIndexTo->second.Name);
  1349. auto desc = Y();
  1350. desc = L(desc, Q(Y(Q("src"), src)));
  1351. desc = L(desc, Q(Y(Q("dst"), dst)));
  1352. actions = L(actions, Q(Y(Q("renameIndexTo"), Q(desc))));
  1353. }
  1354. if (Params.RenameTo) {
  1355. auto destination = ctx.GetPrefixedPath(Scoped->CurrService, Scoped->CurrCluster,
  1356. TDeferredAtom(Params.RenameTo->Pos, Params.RenameTo->Name));
  1357. actions = L(actions, Q(Y(Q("renameTo"), destination)));
  1358. }
  1359. for (const auto& cf : Params.AddChangefeeds) {
  1360. const auto& desc = CreateChangefeedDesc(cf, *this);
  1361. actions = L(actions, Q(Y(Q("addChangefeed"), Q(desc))));
  1362. }
  1363. for (const auto& cf : Params.AlterChangefeeds) {
  1364. const auto& desc = CreateChangefeedDesc(cf, *this);
  1365. actions = L(actions, Q(Y(Q("alterChangefeed"), Q(desc))));
  1366. }
  1367. for (const auto& id : Params.DropChangefeeds) {
  1368. const auto name = BuildQuotedAtom(id.Pos, id.Name);
  1369. actions = L(actions, Q(Y(Q("dropChangefeed"), name)));
  1370. }
  1371. auto opts = Y();
  1372. opts = L(opts, Q(Y(Q("mode"), Q("alter"))));
  1373. opts = L(opts, Q(Y(Q("actions"), Q(actions))));
  1374. switch (Params.TableType) {
  1375. case ETableType::TableStore:
  1376. opts = L(opts, Q(Y(Q("tableType"), Q("tableStore"))));
  1377. break;
  1378. case ETableType::ExternalTable:
  1379. opts = L(opts, Q(Y(Q("tableType"), Q("externalTable"))));
  1380. break;
  1381. case ETableType::Table:
  1382. break;
  1383. }
  1384. Add("block", Q(Y(
  1385. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.Service), Scoped->WrapCluster(Table.Cluster, ctx))),
  1386. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  1387. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1388. )));
  1389. return TAstListNode::DoInit(ctx, src);
  1390. }
  1391. TPtr DoClone() const final {
  1392. return {};
  1393. }
  1394. private:
  1395. TTableRef Table;
  1396. const TAlterTableParameters Params;
  1397. TScopedStatePtr Scoped;
  1398. };
  1399. TNodePtr BuildAlterTable(TPosition pos, const TTableRef& tr, const TAlterTableParameters& params, TScopedStatePtr scoped)
  1400. {
  1401. return new TAlterTableNode(pos, tr, params, scoped);
  1402. }
  1403. class TDropTableNode final : public TAstListNode {
  1404. public:
  1405. TDropTableNode(TPosition pos, const TTableRef& tr, bool missingOk, ETableType tableType, TScopedStatePtr scoped)
  1406. : TAstListNode(pos)
  1407. , Table(tr)
  1408. , TableType(tableType)
  1409. , Scoped(scoped)
  1410. , MissingOk(missingOk)
  1411. {
  1412. FakeSource = BuildFakeSource(pos);
  1413. scoped->UseCluster(Table.Service, Table.Cluster);
  1414. }
  1415. bool DoInit(TContext& ctx, ISource* src) override {
  1416. Y_UNUSED(src);
  1417. auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::DROP);
  1418. if (!keys || !keys->Init(ctx, FakeSource.Get())) {
  1419. return false;
  1420. }
  1421. auto opts = Y();
  1422. opts = L(opts, Q(Y(Q("mode"), Q(MissingOk ? "drop_if_exists" : "drop"))));
  1423. switch (TableType) {
  1424. case ETableType::TableStore:
  1425. opts = L(opts, Q(Y(Q("tableType"), Q("tableStore"))));
  1426. break;
  1427. case ETableType::ExternalTable:
  1428. opts = L(opts, Q(Y(Q("tableType"), Q("externalTable"))));
  1429. break;
  1430. case ETableType::Table:
  1431. break;
  1432. }
  1433. Add("block", Q(Y(
  1434. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.Service), Scoped->WrapCluster(Table.Cluster, ctx))),
  1435. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  1436. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1437. )));
  1438. return TAstListNode::DoInit(ctx, FakeSource.Get());
  1439. }
  1440. TPtr DoClone() const final {
  1441. return {};
  1442. }
  1443. private:
  1444. TTableRef Table;
  1445. ETableType TableType;
  1446. TScopedStatePtr Scoped;
  1447. TSourcePtr FakeSource;
  1448. const bool MissingOk;
  1449. };
  1450. TNodePtr BuildDropTable(TPosition pos, const TTableRef& tr, bool missingOk, ETableType tableType, TScopedStatePtr scoped) {
  1451. return new TDropTableNode(pos, tr, missingOk, tableType, scoped);
  1452. }
  1453. static INode::TPtr CreateConsumerDesc(const TTopicConsumerDescription& desc, const INode& node, bool alter) {
  1454. auto settings = node.Y();
  1455. if (desc.Settings.Important) {
  1456. settings = node.L(settings, node.Q(node.Y(node.Q("important"), desc.Settings.Important)));
  1457. }
  1458. if (const auto& readFromTs = desc.Settings.ReadFromTs) {
  1459. if (readFromTs.IsSet()) {
  1460. settings = node.L(settings, node.Q(node.Y(node.Q("setReadFromTs"), readFromTs.GetValueSet())));
  1461. } else if (alter) {
  1462. settings = node.L(settings, node.Q(node.Y(node.Q("resetReadFromTs"), node.Q(node.Y()))));
  1463. } else {
  1464. YQL_ENSURE(false, "Cannot reset on create");
  1465. }
  1466. }
  1467. if (const auto& readFromTs = desc.Settings.SupportedCodecs) {
  1468. if (readFromTs.IsSet()) {
  1469. settings = node.L(settings, node.Q(node.Y(node.Q("setSupportedCodecs"), readFromTs.GetValueSet())));
  1470. } else if (alter) {
  1471. settings = node.L(settings, node.Q(node.Y(node.Q("resetSupportedCodecs"), node.Q(node.Y()))));
  1472. } else {
  1473. YQL_ENSURE(false, "Cannot reset on create");
  1474. }
  1475. }
  1476. return node.Y(
  1477. node.Q(node.Y(node.Q("name"), BuildQuotedAtom(desc.Name.Pos, desc.Name.Name))),
  1478. node.Q(node.Y(node.Q("settings"), node.Q(settings)))
  1479. );
  1480. }
  1481. class TCreateTopicNode final : public TAstListNode {
  1482. public:
  1483. TCreateTopicNode(TPosition pos, const TTopicRef& tr, const TCreateTopicParameters& params, TScopedStatePtr scoped)
  1484. : TAstListNode(pos)
  1485. , Topic(tr)
  1486. , Params(params)
  1487. , Scoped(scoped)
  1488. {
  1489. scoped->UseCluster(TString(KikimrProviderName), Topic.Cluster);
  1490. }
  1491. bool DoInit(TContext& ctx, ISource* src) override {
  1492. auto keys = Topic.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
  1493. if (!keys || !keys->Init(ctx, src)) {
  1494. return false;
  1495. }
  1496. if (!Params.Consumers.empty())
  1497. {
  1498. THashSet<TString> consumerNames;
  1499. for (const auto& consumer : Params.Consumers) {
  1500. if (!consumerNames.insert(consumer.Name.Name).second) {
  1501. ctx.Error(consumer.Name.Pos) << "Consumer " << consumer.Name.Name << " defined more than once";
  1502. return false;
  1503. }
  1504. }
  1505. }
  1506. auto opts = Y();
  1507. TString mode = Params.ExistingOk ? "create_if_not_exists" : "create";
  1508. opts = L(opts, Q(Y(Q("mode"), Q(mode))));
  1509. for (const auto& consumer : Params.Consumers) {
  1510. const auto& desc = CreateConsumerDesc(consumer, *this, false);
  1511. opts = L(opts, Q(Y(Q("consumer"), Q(desc))));
  1512. }
  1513. if (Params.TopicSettings.IsSet()) {
  1514. auto settings = Y();
  1515. #define INSERT_TOPIC_SETTING(NAME) \
  1516. if (const auto& NAME##Val = Params.TopicSettings.NAME) { \
  1517. if (NAME##Val.IsSet()) { \
  1518. settings = L(settings, Q(Y(Q(Y_STRINGIZE(set##NAME)), NAME##Val.GetValueSet()))); \
  1519. } else { \
  1520. YQL_ENSURE(false, "Can't reset on create"); \
  1521. } \
  1522. }
  1523. INSERT_TOPIC_SETTING(MaxPartitions)
  1524. INSERT_TOPIC_SETTING(MinPartitions)
  1525. INSERT_TOPIC_SETTING(RetentionPeriod)
  1526. INSERT_TOPIC_SETTING(SupportedCodecs)
  1527. INSERT_TOPIC_SETTING(PartitionWriteSpeed)
  1528. INSERT_TOPIC_SETTING(PartitionWriteBurstSpeed)
  1529. INSERT_TOPIC_SETTING(MeteringMode)
  1530. INSERT_TOPIC_SETTING(AutoPartitioningStabilizationWindow)
  1531. INSERT_TOPIC_SETTING(AutoPartitioningUpUtilizationPercent)
  1532. INSERT_TOPIC_SETTING(AutoPartitioningDownUtilizationPercent)
  1533. INSERT_TOPIC_SETTING(AutoPartitioningStrategy)
  1534. #undef INSERT_TOPIC_SETTING
  1535. opts = L(opts, Q(Y(Q("topicSettings"), Q(settings))));
  1536. }
  1537. Add("block", Q(Y(
  1538. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, TString(KikimrProviderName)),
  1539. Scoped->WrapCluster(Topic.Cluster, ctx))),
  1540. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  1541. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1542. )));
  1543. return TAstListNode::DoInit(ctx, src);
  1544. }
  1545. TPtr DoClone() const final {
  1546. return {};
  1547. }
  1548. private:
  1549. const TTopicRef Topic;
  1550. const TCreateTopicParameters Params;
  1551. TScopedStatePtr Scoped;
  1552. };
  1553. TNodePtr BuildCreateTopic(
  1554. TPosition pos, const TTopicRef& tr, const TCreateTopicParameters& params, TScopedStatePtr scoped
  1555. ){
  1556. return new TCreateTopicNode(pos, tr, params, scoped);
  1557. }
  1558. class TAlterTopicNode final : public TAstListNode {
  1559. public:
  1560. TAlterTopicNode(TPosition pos, const TTopicRef& tr, const TAlterTopicParameters& params, TScopedStatePtr scoped)
  1561. : TAstListNode(pos)
  1562. , Topic(tr)
  1563. , Params(params)
  1564. , Scoped(scoped)
  1565. {
  1566. scoped->UseCluster(TString(KikimrProviderName), Topic.Cluster);
  1567. }
  1568. bool DoInit(TContext& ctx, ISource* src) override {
  1569. auto keys = Topic.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
  1570. if (!keys || !keys->Init(ctx, src)) {
  1571. return false;
  1572. }
  1573. if (!Params.AddConsumers.empty())
  1574. {
  1575. THashSet<TString> consumerNames;
  1576. for (const auto& consumer : Params.AddConsumers) {
  1577. if (!consumerNames.insert(consumer.Name.Name).second) {
  1578. ctx.Error(consumer.Name.Pos) << "Consumer " << consumer.Name.Name << " defined more than once";
  1579. return false;
  1580. }
  1581. }
  1582. }
  1583. if (!Params.AlterConsumers.empty())
  1584. {
  1585. THashSet<TString> consumerNames;
  1586. for (const auto& [_, consumer] : Params.AlterConsumers) {
  1587. if (!consumerNames.insert(consumer.Name.Name).second) {
  1588. ctx.Error(consumer.Name.Pos) << "Consumer " << consumer.Name.Name << " altered more than once";
  1589. return false;
  1590. }
  1591. }
  1592. }
  1593. if (!Params.DropConsumers.empty())
  1594. {
  1595. THashSet<TString> consumerNames;
  1596. for (const auto& consumer : Params.DropConsumers) {
  1597. if (!consumerNames.insert(consumer.Name).second) {
  1598. ctx.Error(consumer.Pos) << "Consumer " << consumer.Name << " dropped more than once";
  1599. return false;
  1600. }
  1601. }
  1602. }
  1603. auto opts = Y();
  1604. TString mode = Params.MissingOk ? "alter_if_exists" : "alter";
  1605. opts = L(opts, Q(Y(Q("mode"), Q(mode))));
  1606. for (const auto& consumer : Params.AddConsumers) {
  1607. const auto& desc = CreateConsumerDesc(consumer, *this, false);
  1608. opts = L(opts, Q(Y(Q("addConsumer"), Q(desc))));
  1609. }
  1610. for (const auto& [_, consumer] : Params.AlterConsumers) {
  1611. const auto& desc = CreateConsumerDesc(consumer, *this, true);
  1612. opts = L(opts, Q(Y(Q("alterConsumer"), Q(desc))));
  1613. }
  1614. for (const auto& consumer : Params.DropConsumers) {
  1615. const auto name = BuildQuotedAtom(consumer.Pos, consumer.Name);
  1616. opts = L(opts, Q(Y(Q("dropConsumer"), name)));
  1617. }
  1618. if (Params.TopicSettings.IsSet()) {
  1619. auto settings = Y();
  1620. #define INSERT_TOPIC_SETTING(NAME) \
  1621. if (const auto& NAME##Val = Params.TopicSettings.NAME) { \
  1622. if (NAME##Val.IsSet()) { \
  1623. settings = L(settings, Q(Y(Q(Y_STRINGIZE(set##NAME)), NAME##Val.GetValueSet()))); \
  1624. } else { \
  1625. settings = L(settings, Q(Y(Q(Y_STRINGIZE(reset##NAME)), Y()))); \
  1626. } \
  1627. }
  1628. INSERT_TOPIC_SETTING(MaxPartitions)
  1629. INSERT_TOPIC_SETTING(MinPartitions)
  1630. INSERT_TOPIC_SETTING(RetentionPeriod)
  1631. INSERT_TOPIC_SETTING(SupportedCodecs)
  1632. INSERT_TOPIC_SETTING(PartitionWriteSpeed)
  1633. INSERT_TOPIC_SETTING(PartitionWriteBurstSpeed)
  1634. INSERT_TOPIC_SETTING(MeteringMode)
  1635. INSERT_TOPIC_SETTING(AutoPartitioningStabilizationWindow)
  1636. INSERT_TOPIC_SETTING(AutoPartitioningUpUtilizationPercent)
  1637. INSERT_TOPIC_SETTING(AutoPartitioningDownUtilizationPercent)
  1638. INSERT_TOPIC_SETTING(AutoPartitioningStrategy)
  1639. #undef INSERT_TOPIC_SETTING
  1640. opts = L(opts, Q(Y(Q("topicSettings"), Q(settings))));
  1641. }
  1642. Add("block", Q(Y(
  1643. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, TString(KikimrProviderName)),
  1644. Scoped->WrapCluster(Topic.Cluster, ctx))),
  1645. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  1646. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1647. )));
  1648. return TAstListNode::DoInit(ctx, src);
  1649. }
  1650. TPtr DoClone() const final {
  1651. return {};
  1652. }
  1653. private:
  1654. const TTopicRef Topic;
  1655. const TAlterTopicParameters Params;
  1656. TScopedStatePtr Scoped;
  1657. };
  1658. TNodePtr BuildAlterTopic(
  1659. TPosition pos, const TTopicRef& tr, const TAlterTopicParameters& params, TScopedStatePtr scoped
  1660. ){
  1661. return new TAlterTopicNode(pos, tr, params, scoped);
  1662. }
  1663. class TDropTopicNode final : public TAstListNode {
  1664. public:
  1665. TDropTopicNode(TPosition pos, const TTopicRef& tr, const TDropTopicParameters& params, TScopedStatePtr scoped)
  1666. : TAstListNode(pos)
  1667. , Topic(tr)
  1668. , Params(params)
  1669. , Scoped(scoped)
  1670. {
  1671. scoped->UseCluster(TString(KikimrProviderName), Topic.Cluster);
  1672. }
  1673. bool DoInit(TContext& ctx, ISource* src) override {
  1674. Y_UNUSED(src);
  1675. auto keys = Topic.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::DROP);
  1676. if (!keys || !keys->Init(ctx, FakeSource.Get())) {
  1677. return false;
  1678. }
  1679. auto opts = Y();
  1680. TString mode = Params.MissingOk ? "drop_if_exists" : "drop";
  1681. opts = L(opts, Q(Y(Q("mode"), Q(mode))));
  1682. Add("block", Q(Y(
  1683. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, TString(KikimrProviderName)),
  1684. Scoped->WrapCluster(Topic.Cluster, ctx))),
  1685. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  1686. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1687. )));
  1688. return TAstListNode::DoInit(ctx, FakeSource.Get());
  1689. }
  1690. TPtr DoClone() const final {
  1691. return {};
  1692. }
  1693. private:
  1694. TTopicRef Topic;
  1695. TDropTopicParameters Params;
  1696. TScopedStatePtr Scoped;
  1697. TSourcePtr FakeSource;
  1698. };
  1699. TNodePtr BuildDropTopic(TPosition pos, const TTopicRef& tr, const TDropTopicParameters& params, TScopedStatePtr scoped) {
  1700. return new TDropTopicNode(pos, tr, params, scoped);
  1701. }
  1702. class TControlUser final : public TAstListNode {
  1703. public:
  1704. TControlUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TMaybe<TUserParameters>& params, TScopedStatePtr scoped, bool IsCreateUser)
  1705. : TAstListNode(pos)
  1706. , Service(service)
  1707. , Cluster(cluster)
  1708. , Name(name)
  1709. , Params(params)
  1710. , Scoped(scoped)
  1711. , IsCreateUser(IsCreateUser)
  1712. {
  1713. FakeSource = BuildFakeSource(pos);
  1714. scoped->UseCluster(service, cluster);
  1715. }
  1716. bool DoInit(TContext& ctx, ISource*) override {
  1717. auto name = Name.Build();
  1718. TNodePtr password;
  1719. TNodePtr hash;
  1720. if (Params) {
  1721. if (Params->Password) {
  1722. password = Params->Password->Build();
  1723. } else if (Params->Hash) {
  1724. hash = Params->Hash->Build();
  1725. }
  1726. }
  1727. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  1728. if (!name->Init(ctx, FakeSource.Get())
  1729. || !cluster->Init(ctx, FakeSource.Get())
  1730. || password && !password->Init(ctx, FakeSource.Get())
  1731. || hash && !hash->Init(ctx, FakeSource.Get())
  1732. )
  1733. {
  1734. return false;
  1735. }
  1736. auto options = Y(Q(Y(Q("mode"), Q(IsCreateUser ? "createUser" : "alterUser")))) ;
  1737. TVector<TNodePtr> roles;
  1738. if (Params && !Params->Roles.empty()) {
  1739. for (auto& item : Params->Roles) {
  1740. roles.push_back(item.Build());
  1741. if (!roles.back()->Init(ctx, FakeSource.Get())) {
  1742. return false;
  1743. }
  1744. }
  1745. options = L(options, Q(Y(Q("roles"), Q(new TAstListNodeImpl(Pos, std::move(roles))))));
  1746. }
  1747. if (Params) {
  1748. if (Params->IsPasswordEncrypted) {
  1749. options = L(options, Q(Y(Q("passwordEncrypted"))));
  1750. }
  1751. if (Params->Password) {
  1752. options = L(options, Q(Y(Q("password"), password)));
  1753. } else if (Params->Hash) {
  1754. options = L(options, Q(Y(Q("hash"), hash)));
  1755. } else {
  1756. options = L(options, Q(Y(Q("nullPassword"))));
  1757. }
  1758. if (Params->CanLogin.has_value()) {
  1759. options = L(options, Q(Y(Q(Params->CanLogin.value() ? "login" : "noLogin"))));
  1760. }
  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 TMaybe<TUserParameters> Params;
  1777. TScopedStatePtr Scoped;
  1778. TSourcePtr FakeSource;
  1779. bool IsCreateUser;
  1780. };
  1781. TNodePtr BuildControlUser( TPosition pos,
  1782. const TString& service,
  1783. const TDeferredAtom& cluster,
  1784. const TDeferredAtom& name,
  1785. const TMaybe<TUserParameters>& params,
  1786. TScopedStatePtr scoped,
  1787. bool isCreateUser)
  1788. {
  1789. return new TControlUser(pos, service, cluster, name, params, scoped, isCreateUser);
  1790. }
  1791. class TCreateGroup final : public TAstListNode {
  1792. public:
  1793. TCreateGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TMaybe<TCreateGroupParameters>& params, TScopedStatePtr scoped)
  1794. : TAstListNode(pos)
  1795. , Service(service)
  1796. , Cluster(cluster)
  1797. , Name(name)
  1798. , Params(params)
  1799. , Scoped(scoped)
  1800. {
  1801. FakeSource = BuildFakeSource(pos);
  1802. scoped->UseCluster(service, cluster);
  1803. }
  1804. bool DoInit(TContext& ctx, ISource*) override {
  1805. auto options = Y(Q(Y(Q("mode"), Q("createGroup"))));
  1806. TVector<TNodePtr> roles;
  1807. if (Params && !Params->Roles.empty()) {
  1808. for (auto& item : Params->Roles) {
  1809. roles.push_back(item.Build());
  1810. if (!roles.back()->Init(ctx, FakeSource.Get())) {
  1811. return false;
  1812. }
  1813. }
  1814. options = L(options, Q(Y(Q("roles"), Q(new TAstListNodeImpl(Pos, std::move(roles))))));
  1815. }
  1816. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  1817. Add("block", Q(Y(
  1818. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)),
  1819. Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", Name.Build())))), Y("Void"), Q(options))),
  1820. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1821. )));
  1822. return TAstListNode::DoInit(ctx, FakeSource.Get());
  1823. }
  1824. TPtr DoClone() const final {
  1825. return {};
  1826. }
  1827. private:
  1828. const TString Service;
  1829. TDeferredAtom Cluster;
  1830. TDeferredAtom Name;
  1831. const TMaybe<TCreateGroupParameters> Params;
  1832. TScopedStatePtr Scoped;
  1833. TSourcePtr FakeSource;
  1834. };
  1835. TNodePtr BuildCreateGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TMaybe<TCreateGroupParameters>& params, TScopedStatePtr scoped) {
  1836. return new TCreateGroup(pos, service, cluster, name, params, scoped);
  1837. }
  1838. class TAlterSequence final : public TAstListNode {
  1839. public:
  1840. TAlterSequence(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TString& id, const TSequenceParameters& params, TScopedStatePtr scoped)
  1841. : TAstListNode(pos)
  1842. , Service(service)
  1843. , Cluster(cluster)
  1844. , Id(id)
  1845. , Params(params)
  1846. , Scoped(scoped)
  1847. {
  1848. FakeSource = BuildFakeSource(pos);
  1849. scoped->UseCluster(service, cluster);
  1850. }
  1851. bool DoInit(TContext& ctx, ISource* src) override {
  1852. Y_UNUSED(src);
  1853. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  1854. if (!cluster->Init(ctx, FakeSource.Get())) {
  1855. return false;
  1856. }
  1857. auto options = Y();
  1858. TString mode = Params.MissingOk ? "alter_if_exists" : "alter";
  1859. options = L(options, Q(Y(Q("mode"), Q(mode))));
  1860. if (Params.IsRestart) {
  1861. if (Params.RestartValue) {
  1862. TString strValue = Params.RestartValue->Build()->GetLiteralValue();
  1863. ui64 value = FromString<ui64>(strValue);
  1864. ui64 maxValue = ui64(std::numeric_limits<i64>::max());
  1865. ui64 minValue = 1;
  1866. if (value > maxValue) {
  1867. ctx.Error(Pos) << "Restart value: " << value << " cannot be greater than max value: " << maxValue;
  1868. return false;
  1869. }
  1870. if (value < minValue) {
  1871. ctx.Error(Pos) << "Restart value: " << value << " cannot be less than min value: " << minValue;
  1872. return false;
  1873. }
  1874. options = L(options, Q(Y(Q("restart"), Q(ToString(value)))));
  1875. } else {
  1876. options = L(options, Q(Y(Q("restart"), Q(TString()))));
  1877. }
  1878. }
  1879. if (Params.StartValue) {
  1880. TString strValue = Params.StartValue->Build()->GetLiteralValue();
  1881. ui64 value = FromString<ui64>(strValue);
  1882. ui64 maxValue = ui64(std::numeric_limits<i64>::max());
  1883. ui64 minValue = 1;
  1884. if (value > maxValue) {
  1885. ctx.Error(Pos) << "Start value: " << value << " cannot be greater than max value: " << maxValue;
  1886. return false;
  1887. }
  1888. if (value < minValue) {
  1889. ctx.Error(Pos) << "Start value: " << value << " cannot be less than min value: " << minValue;
  1890. return false;
  1891. }
  1892. options = L(options, Q(Y(Q("start"), Q(ToString(value)))));
  1893. }
  1894. if (Params.Increment) {
  1895. TString strValue = Params.Increment->Build()->GetLiteralValue();
  1896. ui64 value = FromString<ui64>(strValue);
  1897. ui64 maxValue = ui64(std::numeric_limits<i64>::max());
  1898. if (value > maxValue) {
  1899. ctx.Error(Pos) << "Increment: " << value << " cannot be greater than max value: " << maxValue;
  1900. return false;
  1901. }
  1902. if (value == 0) {
  1903. ctx.Error(Pos) << "Increment must not be zero";
  1904. return false;
  1905. }
  1906. options = L(options, Q(Y(Q("increment"), Q(ToString(value)))));
  1907. }
  1908. Add("block", Q(Y(
  1909. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, TString(KikimrProviderName)),
  1910. Scoped->WrapCluster(Cluster, ctx))),
  1911. Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("sequence"), Y("String", BuildQuotedAtom(Pos, Id))))), Y("Void"), Q(options))),
  1912. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1913. )));
  1914. return TAstListNode::DoInit(ctx, src);
  1915. }
  1916. TPtr DoClone() const final {
  1917. return {};
  1918. }
  1919. private:
  1920. const TString Service;
  1921. TDeferredAtom Cluster;
  1922. TString Id;
  1923. const TSequenceParameters Params;
  1924. TScopedStatePtr Scoped;
  1925. TSourcePtr FakeSource;
  1926. };
  1927. TNodePtr BuildAlterSequence(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TString& id, const TSequenceParameters& params, TScopedStatePtr scoped) {
  1928. return new TAlterSequence(pos, service, cluster, id, params, scoped);
  1929. }
  1930. class TRenameRole final : public TAstListNode {
  1931. public:
  1932. TRenameRole(TPosition pos, bool isUser, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TDeferredAtom& newName, TScopedStatePtr scoped)
  1933. : TAstListNode(pos)
  1934. , IsUser(isUser)
  1935. , Service(service)
  1936. , Cluster(cluster)
  1937. , Name(name)
  1938. , NewName(newName)
  1939. , Scoped(scoped)
  1940. {
  1941. FakeSource = BuildFakeSource(pos);
  1942. scoped->UseCluster(service, cluster);
  1943. }
  1944. bool DoInit(TContext& ctx, ISource* src) override {
  1945. Y_UNUSED(src);
  1946. auto name = Name.Build();
  1947. auto newName = NewName.Build();
  1948. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  1949. if (!name->Init(ctx, FakeSource.Get()) ||
  1950. !newName->Init(ctx, FakeSource.Get()) ||
  1951. !cluster->Init(ctx, FakeSource.Get()))
  1952. {
  1953. return false;
  1954. }
  1955. auto options = Y(Q(Y(Q("mode"), Q(IsUser ? "renameUser" : "renameGroup"))));
  1956. options = L(options, Q(Y(Q("newName"), newName)));
  1957. Add("block", Q(Y(
  1958. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)),
  1959. Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))),
  1960. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  1961. )));
  1962. return TAstListNode::DoInit(ctx, FakeSource.Get());
  1963. }
  1964. TPtr DoClone() const final {
  1965. return {};
  1966. }
  1967. private:
  1968. const bool IsUser;
  1969. const TString Service;
  1970. TDeferredAtom Cluster;
  1971. TDeferredAtom Name;
  1972. TDeferredAtom NewName;
  1973. TScopedStatePtr Scoped;
  1974. TSourcePtr FakeSource;
  1975. };
  1976. TNodePtr BuildRenameUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TDeferredAtom& newName, TScopedStatePtr scoped) {
  1977. const bool isUser = true;
  1978. return new TRenameRole(pos, isUser, service, cluster, name, newName, scoped);
  1979. }
  1980. TNodePtr BuildRenameGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TDeferredAtom& newName, TScopedStatePtr scoped) {
  1981. const bool isUser = false;
  1982. return new TRenameRole(pos, isUser, service, cluster, name, newName, scoped);
  1983. }
  1984. class TAlterGroup final : public TAstListNode {
  1985. public:
  1986. TAlterGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TVector<TDeferredAtom>& toChange, bool isDrop, TScopedStatePtr scoped)
  1987. : TAstListNode(pos)
  1988. , Service(service)
  1989. , Cluster(cluster)
  1990. , Name(name)
  1991. , ToChange(toChange)
  1992. , IsDrop(isDrop)
  1993. , Scoped(scoped)
  1994. {
  1995. FakeSource = BuildFakeSource(pos);
  1996. scoped->UseCluster(service, cluster);
  1997. }
  1998. bool DoInit(TContext& ctx, ISource* src) override {
  1999. Y_UNUSED(src);
  2000. auto name = Name.Build();
  2001. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  2002. if (!name->Init(ctx, FakeSource.Get()) || !cluster->Init(ctx, FakeSource.Get())) {
  2003. return false;
  2004. }
  2005. TVector<TNodePtr> toChange;
  2006. for (auto& item : ToChange) {
  2007. toChange.push_back(item.Build());
  2008. if (!toChange.back()->Init(ctx, FakeSource.Get())) {
  2009. return false;
  2010. }
  2011. }
  2012. auto options = Y(Q(Y(Q("mode"), Q(IsDrop ? "dropUsersFromGroup" : "addUsersToGroup"))));
  2013. options = L(options, Q(Y(Q("roles"), Q(new TAstListNodeImpl(Pos, std::move(toChange))))));
  2014. Add("block", Q(Y(
  2015. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)),
  2016. Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))),
  2017. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  2018. )));
  2019. return TAstListNode::DoInit(ctx, FakeSource.Get());
  2020. }
  2021. TPtr DoClone() const final {
  2022. return {};
  2023. }
  2024. private:
  2025. const TString Service;
  2026. TDeferredAtom Cluster;
  2027. TDeferredAtom Name;
  2028. TVector<TDeferredAtom> ToChange;
  2029. const bool IsDrop;
  2030. TScopedStatePtr Scoped;
  2031. TSourcePtr FakeSource;
  2032. };
  2033. TNodePtr BuildAlterGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TVector<TDeferredAtom>& toChange, bool isDrop,
  2034. TScopedStatePtr scoped)
  2035. {
  2036. return new TAlterGroup(pos, service, cluster, name, toChange, isDrop, scoped);
  2037. }
  2038. class TDropRoles final : public TAstListNode {
  2039. public:
  2040. TDropRoles(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& toDrop, bool isUser, bool missingOk, TScopedStatePtr scoped)
  2041. : TAstListNode(pos)
  2042. , Service(service)
  2043. , Cluster(cluster)
  2044. , ToDrop(toDrop)
  2045. , IsUser(isUser)
  2046. , MissingOk(missingOk)
  2047. , Scoped(scoped)
  2048. {
  2049. FakeSource = BuildFakeSource(pos);
  2050. scoped->UseCluster(service, cluster);
  2051. }
  2052. bool DoInit(TContext& ctx, ISource* src) override {
  2053. Y_UNUSED(src);
  2054. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  2055. if (!cluster->Init(ctx, FakeSource.Get())) {
  2056. return false;
  2057. }
  2058. const char* mode = IsUser ?
  2059. (MissingOk ? "dropUserIfExists" : "dropUser") :
  2060. (MissingOk ? "dropGroupIfExists" : "dropGroup");
  2061. auto options = Y(Q(Y(Q("mode"), Q(mode))));
  2062. auto block = Y(Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)));
  2063. for (auto& item : ToDrop) {
  2064. auto name = item.Build();
  2065. if (!name->Init(ctx, FakeSource.Get())) {
  2066. return false;
  2067. }
  2068. block = L(block, Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))));
  2069. }
  2070. block = L(block, Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world")));
  2071. Add("block", Q(block));
  2072. return TAstListNode::DoInit(ctx, FakeSource.Get());
  2073. }
  2074. TPtr DoClone() const final {
  2075. return {};
  2076. }
  2077. private:
  2078. const TString Service;
  2079. TDeferredAtom Cluster;
  2080. TVector<TDeferredAtom> ToDrop;
  2081. const bool IsUser;
  2082. const bool MissingOk;
  2083. TScopedStatePtr Scoped;
  2084. TSourcePtr FakeSource;
  2085. };
  2086. TNodePtr BuildUpsertObjectOperation(TPosition pos, const TString& objectId, const TString& typeId,
  2087. std::map<TString, TDeferredAtom>&& features, const TObjectOperatorContext& context) {
  2088. return new TUpsertObject(pos, objectId, typeId, false, false, std::move(features), std::set<TString>(), context);
  2089. }
  2090. TNodePtr BuildCreateObjectOperation(TPosition pos, const TString& objectId, const TString& typeId,
  2091. bool existingOk, bool replaceIfExists, std::map<TString, TDeferredAtom>&& features, const TObjectOperatorContext& context) {
  2092. return new TCreateObject(pos, objectId, typeId, existingOk, replaceIfExists, std::move(features), std::set<TString>(), context);
  2093. }
  2094. TNodePtr BuildAlterObjectOperation(TPosition pos, const TString& secretId, const TString& typeId,
  2095. std::map<TString, TDeferredAtom>&& features, std::set<TString>&& featuresToReset, const TObjectOperatorContext& context)
  2096. {
  2097. return new TAlterObject(pos, secretId, typeId, false, false, std::move(features), std::move(featuresToReset), context);
  2098. }
  2099. TNodePtr BuildDropObjectOperation(TPosition pos, const TString& secretId, const TString& typeId,
  2100. bool missingOk, std::map<TString, TDeferredAtom>&& options, const TObjectOperatorContext& context)
  2101. {
  2102. return new TDropObject(pos, secretId, typeId, missingOk, false, std::move(options), std::set<TString>(), context);
  2103. }
  2104. TNodePtr BuildDropRoles(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& toDrop, bool isUser, bool missingOk, TScopedStatePtr scoped) {
  2105. return new TDropRoles(pos, service, cluster, toDrop, isUser, missingOk, scoped);
  2106. }
  2107. class TPermissionsAction final : public TAstListNode {
  2108. public:
  2109. struct TPermissionParameters {
  2110. TString PermissionAction;
  2111. TVector<TDeferredAtom> Permissions;
  2112. TVector<TDeferredAtom> SchemaPaths;
  2113. TVector<TDeferredAtom> RoleNames;
  2114. };
  2115. TPermissionsAction(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TPermissionParameters& parameters, TScopedStatePtr scoped)
  2116. : TAstListNode(pos)
  2117. , Service(service)
  2118. , Cluster(cluster)
  2119. , Parameters(parameters)
  2120. , Scoped(scoped)
  2121. {
  2122. FakeSource = BuildFakeSource(pos);
  2123. scoped->UseCluster(service, cluster);
  2124. }
  2125. bool DoInit(TContext& ctx, ISource* src) override {
  2126. Y_UNUSED(src);
  2127. TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
  2128. TNodePtr permissionAction = TDeferredAtom(Pos, Parameters.PermissionAction).Build();
  2129. if (!permissionAction->Init(ctx, FakeSource.Get()) ||
  2130. !cluster->Init(ctx, FakeSource.Get())) {
  2131. return false;
  2132. }
  2133. TVector<TNodePtr> paths;
  2134. paths.reserve(Parameters.SchemaPaths.size());
  2135. for (auto& item : Parameters.SchemaPaths) {
  2136. paths.push_back(item.Build());
  2137. if (!paths.back()->Init(ctx, FakeSource.Get())) {
  2138. return false;
  2139. }
  2140. }
  2141. auto options = Y(Q(Y(Q("paths"), Q(new TAstListNodeImpl(Pos, std::move(paths))))));
  2142. TVector<TNodePtr> permissions;
  2143. permissions.reserve(Parameters.Permissions.size());
  2144. for (auto& item : Parameters.Permissions) {
  2145. permissions.push_back(item.Build());
  2146. if (!permissions.back()->Init(ctx, FakeSource.Get())) {
  2147. return false;
  2148. }
  2149. }
  2150. options = L(options, Q(Y(Q("permissions"), Q(new TAstListNodeImpl(Pos, std::move(permissions))))));
  2151. TVector<TNodePtr> roles;
  2152. roles.reserve(Parameters.RoleNames.size());
  2153. for (auto& item : Parameters.RoleNames) {
  2154. roles.push_back(item.Build());
  2155. if (!roles.back()->Init(ctx, FakeSource.Get())) {
  2156. return false;
  2157. }
  2158. }
  2159. options = L(options, Q(Y(Q("roles"), Q(new TAstListNodeImpl(Pos, std::move(roles))))));
  2160. auto block = Y(Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)));
  2161. block = L(block, Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("permission"), Y("String", permissionAction)))), Y("Void"), Q(options))));
  2162. block = L(block, Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world")));
  2163. Add("block", Q(block));
  2164. return TAstListNode::DoInit(ctx, FakeSource.Get());
  2165. }
  2166. TPtr DoClone() const final {
  2167. return {};
  2168. }
  2169. private:
  2170. const TString Service;
  2171. TDeferredAtom Cluster;
  2172. TPermissionParameters Parameters;
  2173. TScopedStatePtr Scoped;
  2174. TSourcePtr FakeSource;
  2175. };
  2176. TNodePtr BuildGrantPermissions(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& permissions, const TVector<TDeferredAtom>& schemaPaths, const TVector<TDeferredAtom>& roleNames, TScopedStatePtr scoped) {
  2177. return new TPermissionsAction(pos,
  2178. service,
  2179. cluster,
  2180. {.PermissionAction = "grant",
  2181. .Permissions = permissions,
  2182. .SchemaPaths = schemaPaths,
  2183. .RoleNames = roleNames},
  2184. scoped);
  2185. }
  2186. TNodePtr BuildRevokePermissions(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& permissions, const TVector<TDeferredAtom>& schemaPaths, const TVector<TDeferredAtom>& roleNames, TScopedStatePtr scoped) {
  2187. return new TPermissionsAction(pos,
  2188. service,
  2189. cluster,
  2190. {.PermissionAction = "revoke",
  2191. .Permissions = permissions,
  2192. .SchemaPaths = schemaPaths,
  2193. .RoleNames = roleNames},
  2194. scoped);
  2195. }
  2196. class TAsyncReplication
  2197. : public TAstListNode
  2198. , protected TObjectOperatorContext
  2199. {
  2200. protected:
  2201. virtual INode::TPtr FillOptions(INode::TPtr options) const = 0;
  2202. public:
  2203. explicit TAsyncReplication(TPosition pos, const TString& id, const TString& mode, const TObjectOperatorContext& context)
  2204. : TAstListNode(pos)
  2205. , TObjectOperatorContext(context)
  2206. , Id(id)
  2207. , Mode(mode)
  2208. {
  2209. }
  2210. bool DoInit(TContext& ctx, ISource* src) override {
  2211. Scoped->UseCluster(ServiceId, Cluster);
  2212. auto keys = Y("Key", Q(Y(Q("replication"), Y("String", BuildQuotedAtom(Pos, Id)))));
  2213. auto options = FillOptions(Y(Q(Y(Q("mode"), Q(Mode)))));
  2214. Add("block", Q(Y(
  2215. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
  2216. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(options))),
  2217. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  2218. )));
  2219. return TAstListNode::DoInit(ctx, src);
  2220. }
  2221. TPtr DoClone() const final {
  2222. return {};
  2223. }
  2224. private:
  2225. const TString Id;
  2226. const TString Mode;
  2227. }; // TAsyncReplication
  2228. class TCreateAsyncReplication final : public TAsyncReplication {
  2229. public:
  2230. explicit TCreateAsyncReplication(TPosition pos, const TString& id,
  2231. std::vector<std::pair<TString, TString>>&& targets,
  2232. std::map<TString, TNodePtr>&& settings,
  2233. const TObjectOperatorContext& context)
  2234. : TAsyncReplication(pos, id, "create", context)
  2235. , Targets(std::move(targets))
  2236. , Settings(std::move(settings))
  2237. {
  2238. }
  2239. protected:
  2240. INode::TPtr FillOptions(INode::TPtr options) const override {
  2241. if (!Targets.empty()) {
  2242. auto targets = Y();
  2243. for (auto&& [remote, local] : Targets) {
  2244. auto target = Y();
  2245. target = L(target, Q(Y(Q("remote"), Q(remote))));
  2246. target = L(target, Q(Y(Q("local"), Q(local))));
  2247. targets = L(targets, Q(target));
  2248. }
  2249. options = L(options, Q(Y(Q("targets"), Q(targets))));
  2250. }
  2251. if (!Settings.empty()) {
  2252. auto settings = Y();
  2253. for (auto&& [k, v] : Settings) {
  2254. if (v) {
  2255. settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k), v)));
  2256. } else {
  2257. settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k))));
  2258. }
  2259. }
  2260. options = L(options, Q(Y(Q("settings"), Q(settings))));
  2261. }
  2262. return options;
  2263. }
  2264. private:
  2265. std::vector<std::pair<TString, TString>> Targets; // (remote, local)
  2266. std::map<TString, TNodePtr> Settings;
  2267. }; // TCreateAsyncReplication
  2268. TNodePtr BuildCreateAsyncReplication(TPosition pos, const TString& id,
  2269. std::vector<std::pair<TString, TString>>&& targets,
  2270. std::map<TString, TNodePtr>&& settings,
  2271. const TObjectOperatorContext& context)
  2272. {
  2273. return new TCreateAsyncReplication(pos, id, std::move(targets), std::move(settings), context);
  2274. }
  2275. class TDropAsyncReplication final : public TAsyncReplication {
  2276. public:
  2277. explicit TDropAsyncReplication(TPosition pos, const TString& id, bool cascade, const TObjectOperatorContext& context)
  2278. : TAsyncReplication(pos, id, cascade ? "dropCascade" : "drop", context)
  2279. {
  2280. }
  2281. protected:
  2282. INode::TPtr FillOptions(INode::TPtr options) const override {
  2283. return options;
  2284. }
  2285. }; // TDropAsyncReplication
  2286. TNodePtr BuildDropAsyncReplication(TPosition pos, const TString& id, bool cascade, const TObjectOperatorContext& context) {
  2287. return new TDropAsyncReplication(pos, id, cascade, context);
  2288. }
  2289. class TAlterAsyncReplication final : public TAsyncReplication {
  2290. public:
  2291. explicit TAlterAsyncReplication(TPosition pos, const TString& id,
  2292. std::map<TString, TNodePtr>&& settings,
  2293. const TObjectOperatorContext& context)
  2294. : TAsyncReplication(pos, id, "alter", context)
  2295. , Settings(std::move(settings))
  2296. {
  2297. }
  2298. protected:
  2299. INode::TPtr FillOptions(INode::TPtr options) const override {
  2300. if (!Settings.empty()) {
  2301. auto settings = Y();
  2302. for (auto&& [k, v] : Settings) {
  2303. if (v) {
  2304. settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k), v)));
  2305. } else {
  2306. settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k))));
  2307. }
  2308. }
  2309. options = L(options, Q(Y(Q("settings"), Q(settings))));
  2310. }
  2311. return options;
  2312. }
  2313. private:
  2314. std::map<TString, TNodePtr> Settings;
  2315. }; // TAlterAsyncReplication
  2316. TNodePtr BuildAlterAsyncReplication(TPosition pos, const TString& id,
  2317. std::map<TString, TNodePtr>&& settings,
  2318. const TObjectOperatorContext& context)
  2319. {
  2320. return new TAlterAsyncReplication(pos, id, std::move(settings), context);
  2321. }
  2322. class TTransfer
  2323. : public TAstListNode
  2324. , protected TObjectOperatorContext
  2325. {
  2326. protected:
  2327. virtual INode::TPtr FillOptions(INode::TPtr options) const = 0;
  2328. public:
  2329. explicit TTransfer(TPosition pos, const TString& id, const TString& mode, const TObjectOperatorContext& context)
  2330. : TAstListNode(pos)
  2331. , TObjectOperatorContext(context)
  2332. , Id(id)
  2333. , Mode(mode)
  2334. {
  2335. }
  2336. bool DoInit(TContext& ctx, ISource* src) override {
  2337. Scoped->UseCluster(ServiceId, Cluster);
  2338. auto keys = Y("Key", Q(Y(Q("transfer"), Y("String", BuildQuotedAtom(Pos, Id)))));
  2339. auto options = FillOptions(Y(Q(Y(Q("mode"), Q(Mode)))));
  2340. Add("block", Q(Y(
  2341. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
  2342. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(options))),
  2343. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  2344. )));
  2345. return TAstListNode::DoInit(ctx, src);
  2346. }
  2347. TPtr DoClone() const final {
  2348. return {};
  2349. }
  2350. private:
  2351. const TString Id;
  2352. const TString Mode;
  2353. }; // TTransfer
  2354. class TCreateTransfer final: public TTransfer {
  2355. public:
  2356. explicit TCreateTransfer(TPosition pos, const TString& id, const TString&& source, const TString&& target,
  2357. const TString&& transformLambda,
  2358. std::map<TString, TNodePtr>&& settings,
  2359. const TObjectOperatorContext& context)
  2360. : TTransfer(pos, id, "create", context)
  2361. , Source(std::move(source))
  2362. , Target(std::move(target))
  2363. , TransformLambda(std::move(transformLambda))
  2364. , Settings(std::move(settings))
  2365. {
  2366. }
  2367. protected:
  2368. INode::TPtr FillOptions(INode::TPtr options) const override {
  2369. options = L(options, Q(Y(Q("source"), Q(Source))));
  2370. options = L(options, Q(Y(Q("target"), Q(Target))));
  2371. options = L(options, Q(Y(Q("transformLambda"), Q(TransformLambda))));
  2372. if (!Settings.empty()) {
  2373. auto settings = Y();
  2374. for (auto&& [k, v] : Settings) {
  2375. if (v) {
  2376. settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k), v)));
  2377. } else {
  2378. settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k))));
  2379. }
  2380. }
  2381. options = L(options, Q(Y(Q("settings"), Q(settings))));
  2382. }
  2383. return options;
  2384. }
  2385. private:
  2386. const TString Source;
  2387. const TString Target;
  2388. const TString TransformLambda;
  2389. std::map<TString, TNodePtr> Settings;
  2390. }; // TCreateTransfer
  2391. TNodePtr BuildCreateTransfer(TPosition pos, const TString& id, const TString&& source, const TString&& target,
  2392. const TString&& transformLambda,
  2393. std::map<TString, TNodePtr>&& settings,
  2394. const TObjectOperatorContext& context)
  2395. {
  2396. return new TCreateTransfer(pos, id, std::move(source), std::move(target), std::move(transformLambda), std::move(settings), context);
  2397. }
  2398. class TDropTransfer final: public TTransfer {
  2399. public:
  2400. explicit TDropTransfer(TPosition pos, const TString& id, bool cascade, const TObjectOperatorContext& context)
  2401. : TTransfer(pos, id, cascade ? "dropCascade" : "drop", context)
  2402. {
  2403. }
  2404. protected:
  2405. INode::TPtr FillOptions(INode::TPtr options) const override {
  2406. return options;
  2407. }
  2408. }; // TDropTransfer
  2409. TNodePtr BuildDropTransfer(TPosition pos, const TString& id, bool cascade, const TObjectOperatorContext& context) {
  2410. return new TDropTransfer(pos, id, cascade, context);
  2411. }
  2412. class TAlterTransfer final: public TTransfer {
  2413. public:
  2414. explicit TAlterTransfer(TPosition pos, const TString& id, std::optional<TString>&& transformLambda,
  2415. std::map<TString, TNodePtr>&& settings,
  2416. const TObjectOperatorContext& context)
  2417. : TTransfer(pos, id, "alter", context)
  2418. , TransformLambda(std::move(transformLambda))
  2419. , Settings(std::move(settings))
  2420. {
  2421. }
  2422. protected:
  2423. INode::TPtr FillOptions(INode::TPtr options) const override {
  2424. options = L(options, Q(Y(Q("transformLambda"), Q(TransformLambda ? TransformLambda.value() : ""))));
  2425. if (!Settings.empty()) {
  2426. auto settings = Y();
  2427. for (auto&& [k, v] : Settings) {
  2428. if (v) {
  2429. settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k), v)));
  2430. } else {
  2431. settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k))));
  2432. }
  2433. }
  2434. options = L(options, Q(Y(Q("settings"), Q(settings))));
  2435. }
  2436. return options;
  2437. }
  2438. private:
  2439. const std::optional<TString> TransformLambda;
  2440. std::map<TString, TNodePtr> Settings;
  2441. }; // TAlterTransfer
  2442. TNodePtr BuildAlterTransfer(TPosition pos, const TString& id, std::optional<TString>&& transformLambda,
  2443. std::map<TString, TNodePtr>&& settings,
  2444. const TObjectOperatorContext& context)
  2445. {
  2446. return new TAlterTransfer(pos, id, std::move(transformLambda), std::move(settings), context);
  2447. }
  2448. static const TMap<EWriteColumnMode, TString> columnModeToStrMapMR {
  2449. {EWriteColumnMode::Default, ""},
  2450. {EWriteColumnMode::Insert, "append"},
  2451. {EWriteColumnMode::Renew, "renew"}
  2452. };
  2453. static const TMap<EWriteColumnMode, TString> columnModeToStrMapStat {
  2454. {EWriteColumnMode::Upsert, "upsert"}
  2455. };
  2456. static const TMap<EWriteColumnMode, TString> columnModeToStrMapKikimr {
  2457. {EWriteColumnMode::Default, ""},
  2458. {EWriteColumnMode::Insert, "insert_abort"},
  2459. {EWriteColumnMode::InsertOrAbort, "insert_abort"},
  2460. {EWriteColumnMode::InsertOrIgnore, "insert_ignore"},
  2461. {EWriteColumnMode::InsertOrRevert, "insert_revert"},
  2462. {EWriteColumnMode::Upsert, "upsert"},
  2463. {EWriteColumnMode::Replace, "replace"},
  2464. {EWriteColumnMode::Update, "update"},
  2465. {EWriteColumnMode::UpdateOn, "update_on"},
  2466. {EWriteColumnMode::Delete, "delete"},
  2467. {EWriteColumnMode::DeleteOn, "delete_on"},
  2468. };
  2469. class TWriteTableNode final : public TAstListNode {
  2470. public:
  2471. TWriteTableNode(TPosition pos, const TString& label, const TTableRef& table, EWriteColumnMode mode,
  2472. TNodePtr options, TScopedStatePtr scoped)
  2473. : TAstListNode(pos)
  2474. , Label(label)
  2475. , Table(table)
  2476. , Mode(mode)
  2477. , Options(options)
  2478. , Scoped(scoped)
  2479. {
  2480. scoped->UseCluster(Table.Service, Table.Cluster);
  2481. }
  2482. bool DoInit(TContext& ctx, ISource* src) override {
  2483. auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::WRITE);
  2484. if (!keys || !keys->Init(ctx, src)) {
  2485. return false;
  2486. }
  2487. auto getModesMap = [] (const TString& serviceName) -> const TMap<EWriteColumnMode, TString>& {
  2488. if (serviceName == KikimrProviderName || serviceName == YdbProviderName) {
  2489. return columnModeToStrMapKikimr;
  2490. } else if (serviceName == StatProviderName) {
  2491. return columnModeToStrMapStat;
  2492. } else {
  2493. return columnModeToStrMapMR;
  2494. }
  2495. };
  2496. auto options = Y();
  2497. if (Options) {
  2498. if (!Options->Init(ctx, src)) {
  2499. return false;
  2500. }
  2501. options = L(Options);
  2502. }
  2503. if (Mode != EWriteColumnMode::Default) {
  2504. auto modeStr = getModesMap(Table.Service).FindPtr(Mode);
  2505. options->Add(Q(Y(Q("mode"), Q(modeStr ? *modeStr : "unsupported"))));
  2506. }
  2507. Add("block", Q((Y(
  2508. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.Service), Scoped->WrapCluster(Table.Cluster, ctx))),
  2509. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Label, Q(options))),
  2510. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  2511. ))));
  2512. return TAstListNode::DoInit(ctx, src);
  2513. }
  2514. TPtr DoClone() const final {
  2515. return {};
  2516. }
  2517. private:
  2518. TString Label;
  2519. TTableRef Table;
  2520. EWriteColumnMode Mode;
  2521. TNodePtr Options;
  2522. TScopedStatePtr Scoped;
  2523. };
  2524. TNodePtr BuildWriteTable(TPosition pos, const TString& label, const TTableRef& table, EWriteColumnMode mode, TNodePtr options,
  2525. TScopedStatePtr scoped)
  2526. {
  2527. return new TWriteTableNode(pos, label, table, mode, std::move(options), scoped);
  2528. }
  2529. class TClustersSinkOperationBase : public TAstListNode {
  2530. protected:
  2531. TClustersSinkOperationBase(TPosition pos)
  2532. : TAstListNode(pos)
  2533. {}
  2534. virtual TPtr ProduceOperation() = 0;
  2535. bool DoInit(TContext& ctx, ISource* src) override {
  2536. auto block(Y());
  2537. auto op = ProduceOperation();
  2538. if (!op) {
  2539. return false;
  2540. }
  2541. block = L(block, op);
  2542. block = L(block, Y("return", "world"));
  2543. Add("block", Q(block));
  2544. return TAstListNode::DoInit(ctx, src);
  2545. }
  2546. TPtr DoClone() const final {
  2547. return {};
  2548. }
  2549. };
  2550. class TCommitClustersNode: public TClustersSinkOperationBase {
  2551. public:
  2552. TCommitClustersNode(TPosition pos)
  2553. : TClustersSinkOperationBase(pos)
  2554. {
  2555. }
  2556. TPtr ProduceOperation() override {
  2557. return Y("let", "world", Y("CommitAll!", "world"));
  2558. }
  2559. };
  2560. TNodePtr BuildCommitClusters(TPosition pos) {
  2561. return new TCommitClustersNode(pos);
  2562. }
  2563. class TRollbackClustersNode: public TClustersSinkOperationBase {
  2564. public:
  2565. TRollbackClustersNode(TPosition pos)
  2566. : TClustersSinkOperationBase(pos)
  2567. {
  2568. }
  2569. TPtr ProduceOperation() override {
  2570. return Y("let", "world", Y("CommitAll!", "world", Q(Y(Q(Y(Q("mode"), Q("rollback")))))));
  2571. }
  2572. };
  2573. TNodePtr BuildRollbackClusters(TPosition pos) {
  2574. return new TRollbackClustersNode(pos);
  2575. }
  2576. class TWriteResultNode final : public TAstListNode {
  2577. public:
  2578. TWriteResultNode(TPosition pos, const TString& label, TNodePtr settings)
  2579. : TAstListNode(pos)
  2580. , Label(label)
  2581. , Settings(settings)
  2582. , CommitClusters(BuildCommitClusters(Pos))
  2583. {}
  2584. bool DoInit(TContext& ctx, ISource* src) override {
  2585. auto block(Y(
  2586. Y("let", "result_sink", Y("DataSink", Q(TString(ResultProviderName)))),
  2587. Y("let", "world", Y(TString(WriteName), "world", "result_sink", Y("Key"), Label, Q(Settings)))
  2588. ));
  2589. if (ctx.PragmaAutoCommit) {
  2590. block = L(block, Y("let", "world", CommitClusters));
  2591. }
  2592. block = L(block, Y("return", Y(TString(CommitName), "world", "result_sink")));
  2593. Add("block", Q(block));
  2594. return TAstListNode::DoInit(ctx, src);
  2595. }
  2596. TPtr DoClone() const final {
  2597. return {};
  2598. }
  2599. private:
  2600. TString Label;
  2601. TNodePtr Settings;
  2602. TNodePtr CommitClusters;
  2603. };
  2604. TNodePtr BuildWriteResult(TPosition pos, const TString& label, TNodePtr settings) {
  2605. return new TWriteResultNode(pos, label, settings);
  2606. }
  2607. class TYqlProgramNode : public TAstListNode {
  2608. public:
  2609. TYqlProgramNode(TPosition pos, const TVector<TNodePtr>& blocks, bool topLevel, TScopedStatePtr scoped, bool useSeq)
  2610. : TAstListNode(pos)
  2611. , Blocks(blocks)
  2612. , TopLevel(topLevel)
  2613. , Scoped(scoped)
  2614. , UseSeq(useSeq)
  2615. {}
  2616. bool DoInit(TContext& ctx, ISource* src) override {
  2617. bool hasError = false;
  2618. INode::TPtr currentWorldsHolder;
  2619. INode::TPtr seqNode;
  2620. if (UseSeq) {
  2621. currentWorldsHolder = new TAstListNodeImpl(GetPos());
  2622. seqNode = new TAstListNodeImpl(GetPos());
  2623. seqNode->Add("Seq!","world");
  2624. }
  2625. INode* currentWorlds = UseSeq ? currentWorldsHolder.Get() : this;
  2626. auto flushCurrentWorlds = [&](bool changeSeq, bool finish) {
  2627. currentWorldsHolder->Add(Y("return","world"));
  2628. auto lambda = BuildLambda(GetPos(), Y("world"), Y("block", Q(currentWorldsHolder)));
  2629. seqNode->Add(lambda);
  2630. if (finish) {
  2631. Add(Y("let", "world", seqNode));
  2632. } else {
  2633. currentWorldsHolder = new TAstListNodeImpl(GetPos());
  2634. currentWorlds = currentWorldsHolder.Get();
  2635. }
  2636. if (changeSeq) {
  2637. Add(Y("let", "world", seqNode));
  2638. seqNode = new TAstListNodeImpl(GetPos());
  2639. seqNode->Add("Seq!","world");
  2640. }
  2641. };
  2642. if (TopLevel) {
  2643. for (auto& var: ctx.Variables) {
  2644. if (!var.second.second->Init(ctx, src)) {
  2645. hasError = true;
  2646. continue;
  2647. }
  2648. Add(Y(
  2649. "declare",
  2650. new TAstAtomNodeImpl(var.second.first, var.first, TNodeFlags::ArbitraryContent),
  2651. var.second.second));
  2652. }
  2653. for (const auto& overrideLibrary: ctx.OverrideLibraries) {
  2654. auto node = Y(
  2655. "override_library",
  2656. new TAstAtomNodeImpl(
  2657. std::get<TPosition>(overrideLibrary.second),
  2658. overrideLibrary.first, TNodeFlags::ArbitraryContent
  2659. ));
  2660. Add(node);
  2661. }
  2662. for (const auto& package: ctx.Packages) {
  2663. const auto& [url, urlPosition] = std::get<1U>(package.second);
  2664. auto node = Y(
  2665. "package",
  2666. new TAstAtomNodeImpl(
  2667. std::get<TPosition>(package.second), package.first,
  2668. TNodeFlags::ArbitraryContent
  2669. ),
  2670. new TAstAtomNodeImpl(urlPosition, url, TNodeFlags::ArbitraryContent));
  2671. if (const auto& tokenWithPosition = std::get<2U>(package.second)) {
  2672. const auto& [token, tokenPosition] = *tokenWithPosition;
  2673. node = L(node, new TAstAtomNodeImpl(tokenPosition, token, TNodeFlags::ArbitraryContent));
  2674. }
  2675. Add(node);
  2676. }
  2677. for (const auto& lib : ctx.Libraries) {
  2678. auto node = Y("library", new TAstAtomNodeImpl(std::get<TPosition>(lib.second), lib.first, TNodeFlags::ArbitraryContent));
  2679. if (const auto& first = std::get<1U>(lib.second)) {
  2680. node = L(node, new TAstAtomNodeImpl(first->second, first->first, TNodeFlags::ArbitraryContent));
  2681. if (const auto& second = std::get<2U>(lib.second)) {
  2682. node = L(node, new TAstAtomNodeImpl(second->second, second->first, TNodeFlags::ArbitraryContent));
  2683. }
  2684. }
  2685. Add(node);
  2686. }
  2687. for (const auto& p : ctx.PackageVersions) {
  2688. Add(Y("set_package_version", BuildQuotedAtom(Pos, p.first), BuildQuotedAtom(Pos, ToString(p.second))));
  2689. }
  2690. Add(Y("import", "aggregate_module", BuildQuotedAtom(Pos, "/lib/yql/aggregate.yqls")));
  2691. Add(Y("import", "window_module", BuildQuotedAtom(Pos, "/lib/yql/window.yqls")));
  2692. for (const auto& module : ctx.Settings.ModuleMapping) {
  2693. TString moduleName(module.first + "_module");
  2694. moduleName.to_lower();
  2695. Add(Y("import", moduleName, BuildQuotedAtom(Pos, module.second)));
  2696. }
  2697. for (const auto& moduleAlias : ctx.ImportModuleAliases) {
  2698. Add(Y("import", moduleAlias.second, BuildQuotedAtom(Pos, moduleAlias.first)));
  2699. }
  2700. for (const auto& x : ctx.SimpleUdfs) {
  2701. Add(Y("let", x.second, Y("Udf", BuildQuotedAtom(Pos, x.first))));
  2702. }
  2703. if (!ctx.CompactNamedExprs) {
  2704. for (auto& nodes: Scoped->NamedNodes) {
  2705. if (src || ctx.Exports.contains(nodes.first)) {
  2706. auto& item = nodes.second.front();
  2707. if (!item->Node->Init(ctx, src)) {
  2708. hasError = true;
  2709. continue;
  2710. }
  2711. // Some constants may be used directly by YQL code and need to be translated without reference from SQL AST
  2712. if (item->Node->IsConstant() || ctx.Exports.contains(nodes.first)) {
  2713. Add(Y("let", BuildAtom(item->Node->GetPos(), nodes.first), item->Node));
  2714. }
  2715. }
  2716. }
  2717. }
  2718. if (ctx.Settings.Mode != NSQLTranslation::ESqlMode::LIBRARY) {
  2719. auto configSource = Y("DataSource", BuildQuotedAtom(Pos, TString(ConfigProviderName)));
  2720. auto resultSink = Y("DataSink", BuildQuotedAtom(Pos, TString(ResultProviderName)));
  2721. for (const auto& warningPragma : ctx.WarningPolicy.GetRules()) {
  2722. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2723. BuildQuotedAtom(Pos, "Warning"), BuildQuotedAtom(Pos, warningPragma.GetPattern()),
  2724. BuildQuotedAtom(Pos, to_lower(ToString(warningPragma.GetAction()))))));
  2725. }
  2726. if (ctx.ResultSizeLimit > 0) {
  2727. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", resultSink,
  2728. BuildQuotedAtom(Pos, "SizeLimit"), BuildQuotedAtom(Pos, ToString(ctx.ResultSizeLimit)))));
  2729. }
  2730. if (!ctx.PragmaPullUpFlatMapOverJoin) {
  2731. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2732. BuildQuotedAtom(Pos, "DisablePullUpFlatMapOverJoin"))));
  2733. }
  2734. if (ctx.FilterPushdownOverJoinOptionalSide) {
  2735. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2736. BuildQuotedAtom(Pos, "FilterPushdownOverJoinOptionalSide"))));
  2737. }
  2738. if (!ctx.RotateJoinTree) {
  2739. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2740. BuildQuotedAtom(Pos, "RotateJoinTree"), BuildQuotedAtom(Pos, "false"))));
  2741. }
  2742. if (ctx.DiscoveryMode) {
  2743. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2744. BuildQuotedAtom(Pos, "DiscoveryMode"))));
  2745. }
  2746. if (ctx.DqEngineEnable) {
  2747. TString mode = "auto";
  2748. if (ctx.PqReadByRtmrCluster && ctx.PqReadByRtmrCluster != "dq") {
  2749. mode = "disable";
  2750. } else if (ctx.DqEngineForce) {
  2751. mode = "force";
  2752. }
  2753. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2754. BuildQuotedAtom(Pos, "DqEngine"), BuildQuotedAtom(Pos, mode))));
  2755. }
  2756. if (ctx.CostBasedOptimizer) {
  2757. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2758. BuildQuotedAtom(Pos, "CostBasedOptimizer"), BuildQuotedAtom(Pos, ctx.CostBasedOptimizer))));
  2759. }
  2760. if (ctx.JsonQueryReturnsJsonDocument.Defined()) {
  2761. TString pragmaName = "DisableJsonQueryReturnsJsonDocument";
  2762. if (*ctx.JsonQueryReturnsJsonDocument) {
  2763. pragmaName = "JsonQueryReturnsJsonDocument";
  2764. }
  2765. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource, BuildQuotedAtom(Pos, pragmaName))));
  2766. }
  2767. if (ctx.OrderedColumns) {
  2768. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2769. BuildQuotedAtom(Pos, "OrderedColumns"))));
  2770. }
  2771. if (ctx.PqReadByRtmrCluster) {
  2772. auto pqSourceAll = Y("DataSource", BuildQuotedAtom(Pos, TString(PqProviderName)), BuildQuotedAtom(Pos, "$all"));
  2773. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", pqSourceAll,
  2774. BuildQuotedAtom(Pos, "Attr"), BuildQuotedAtom(Pos, "PqReadByRtmrCluster_"), BuildQuotedAtom(Pos, ctx.PqReadByRtmrCluster))));
  2775. auto rtmrSourceAll = Y("DataSource", BuildQuotedAtom(Pos, TString(RtmrProviderName)), BuildQuotedAtom(Pos, "$all"));
  2776. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", rtmrSourceAll,
  2777. BuildQuotedAtom(Pos, "Attr"), BuildQuotedAtom(Pos, "PqReadByRtmrCluster_"), BuildQuotedAtom(Pos, ctx.PqReadByRtmrCluster))));
  2778. if (ctx.PqReadByRtmrCluster != "dq") {
  2779. // set any dynamic settings for particular RTMR cluster for CommitAll!
  2780. auto rtmrSource = Y("DataSource", BuildQuotedAtom(Pos, TString(RtmrProviderName)), BuildQuotedAtom(Pos, ctx.PqReadByRtmrCluster));
  2781. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", rtmrSource,
  2782. BuildQuotedAtom(Pos, "Attr"), BuildQuotedAtom(Pos, "Dummy_"), BuildQuotedAtom(Pos, "1"))));
  2783. }
  2784. }
  2785. if (ctx.YsonCastToString.Defined()) {
  2786. const TString pragmaName = *ctx.YsonCastToString ? "YsonCastToString" : "DisableYsonCastToString";
  2787. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource, BuildQuotedAtom(Pos, pragmaName))));
  2788. }
  2789. if (ctx.UseBlocks) {
  2790. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource, BuildQuotedAtom(Pos, "UseBlocks"))));
  2791. }
  2792. if (ctx.BlockEngineEnable) {
  2793. TString mode = ctx.BlockEngineForce ? "force" : "auto";
  2794. currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2795. BuildQuotedAtom(Pos, "BlockEngine"), BuildQuotedAtom(Pos, mode))));
  2796. }
  2797. if (ctx.Engine) {
  2798. Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
  2799. BuildQuotedAtom(Pos, "Engine"), BuildQuotedAtom(Pos, *ctx.Engine))));
  2800. }
  2801. }
  2802. }
  2803. for (auto& block: Blocks) {
  2804. if (block->SubqueryAlias()) {
  2805. continue;
  2806. }
  2807. if (!block->Init(ctx, nullptr)) {
  2808. hasError = true;
  2809. continue;
  2810. }
  2811. }
  2812. for (const auto& x : Scoped->Local.ExprClusters) {
  2813. auto& data = Scoped->Local.ExprClustersMap[x.Get()];
  2814. auto& node = data.second;
  2815. if (!node->Init(ctx, nullptr)) {
  2816. hasError = true;
  2817. continue;
  2818. }
  2819. Add(Y("let", data.first, node));
  2820. }
  2821. if (UseSeq) {
  2822. flushCurrentWorlds(false, false);
  2823. }
  2824. for (auto& block: Blocks) {
  2825. const auto subqueryAliasPtr = block->SubqueryAlias();
  2826. if (subqueryAliasPtr) {
  2827. if (block->UsedSubquery()) {
  2828. if (UseSeq) {
  2829. flushCurrentWorlds(true, false);
  2830. }
  2831. const auto& ref = block->GetLabel();
  2832. YQL_ENSURE(!ref.empty());
  2833. Add(block);
  2834. currentWorlds->Add(Y("let", "world", Y("Nth", *subqueryAliasPtr, Q("0"))));
  2835. Add(Y("let", ref, Y("Nth", *subqueryAliasPtr, Q("1"))));
  2836. }
  2837. } else {
  2838. const auto& ref = block->GetLabel();
  2839. if (ref) {
  2840. Add(Y("let", ref, block));
  2841. } else {
  2842. currentWorlds->Add(Y("let", "world", block));
  2843. if (UseSeq) {
  2844. flushCurrentWorlds(false, false);
  2845. }
  2846. }
  2847. }
  2848. }
  2849. if (UseSeq) {
  2850. flushCurrentWorlds(false, true);
  2851. }
  2852. if (TopLevel) {
  2853. if (ctx.UniversalAliases) {
  2854. decltype(Nodes) preparedNodes;
  2855. preparedNodes.swap(Nodes);
  2856. for (const auto& [name, node] : ctx.UniversalAliases) {
  2857. Add(Y("let", name, node));
  2858. }
  2859. Nodes.insert(Nodes.end(), preparedNodes.begin(), preparedNodes.end());
  2860. }
  2861. decltype(Nodes) imports;
  2862. for (const auto& [alias, path]: ctx.RequiredModules) {
  2863. imports.push_back(Y("import", alias, BuildQuotedAtom(Pos, path)));
  2864. }
  2865. Nodes.insert(Nodes.begin(), std::make_move_iterator(imports.begin()), std::make_move_iterator(imports.end()));
  2866. for (const auto& symbol: ctx.Exports) {
  2867. if (ctx.CompactNamedExprs) {
  2868. auto node = Scoped->LookupNode(symbol);
  2869. YQL_ENSURE(node);
  2870. if (!node->Init(ctx, src)) {
  2871. hasError = true;
  2872. continue;
  2873. }
  2874. Add(Y("let", BuildAtom(node->GetPos(), symbol), node));
  2875. }
  2876. Add(Y("export", symbol));
  2877. }
  2878. }
  2879. if (!TopLevel || ctx.Settings.Mode != NSQLTranslation::ESqlMode::LIBRARY) {
  2880. Add(Y("return", "world"));
  2881. }
  2882. return !hasError;
  2883. }
  2884. TPtr DoClone() const final {
  2885. return {};
  2886. }
  2887. private:
  2888. TVector<TNodePtr> Blocks;
  2889. const bool TopLevel;
  2890. TScopedStatePtr Scoped;
  2891. const bool UseSeq;
  2892. };
  2893. TNodePtr BuildQuery(TPosition pos, const TVector<TNodePtr>& blocks, bool topLevel, TScopedStatePtr scoped, bool useSeq) {
  2894. return new TYqlProgramNode(pos, blocks, topLevel, scoped, useSeq);
  2895. }
  2896. class TPragmaNode final : public INode {
  2897. public:
  2898. TPragmaNode(TPosition pos, const TString& prefix, const TString& name, const TVector<TDeferredAtom>& values, bool valueDefault)
  2899. : INode(pos)
  2900. , Prefix(prefix)
  2901. , Name(name)
  2902. , Values(values)
  2903. , ValueDefault(valueDefault)
  2904. {
  2905. FakeSource = BuildFakeSource(pos);
  2906. }
  2907. bool DoInit(TContext& ctx, ISource* src) override {
  2908. Y_UNUSED(src);
  2909. TString serviceName;
  2910. TString cluster;
  2911. if (std::find(Providers.cbegin(), Providers.cend(), Prefix) != Providers.cend()) {
  2912. cluster = "$all";
  2913. serviceName = Prefix;
  2914. } else {
  2915. serviceName = *ctx.GetClusterProvider(Prefix, cluster);
  2916. }
  2917. auto datasource = Y("DataSource", BuildQuotedAtom(Pos, serviceName));
  2918. if (Prefix != ConfigProviderName) {
  2919. datasource = L(datasource, BuildQuotedAtom(Pos, cluster));
  2920. }
  2921. Node = Y();
  2922. Node = L(Node, AstNode(TString(ConfigureName)));
  2923. Node = L(Node, AstNode(TString(TStringBuf("world"))));
  2924. Node = L(Node, datasource);
  2925. if (Name == TStringBuf("flags")) {
  2926. for (ui32 i = 0; i < Values.size(); ++i) {
  2927. Node = L(Node, Values[i].Build());
  2928. }
  2929. }
  2930. else if (Name == TStringBuf("AddFileByUrl") || Name == TStringBuf("SetFileOption") || Name == TStringBuf("AddFolderByUrl") || Name == TStringBuf("ImportUdfs") || Name == TStringBuf("SetPackageVersion")) {
  2931. Node = L(Node, BuildQuotedAtom(Pos, Name));
  2932. for (ui32 i = 0; i < Values.size(); ++i) {
  2933. Node = L(Node, Values[i].Build());
  2934. }
  2935. }
  2936. else if (Name == TStringBuf("auth")) {
  2937. Node = L(Node, BuildQuotedAtom(Pos, "Auth"));
  2938. Node = L(Node, Values.empty() ? BuildQuotedAtom(Pos, TString()) : Values.front().Build());
  2939. }
  2940. else {
  2941. Node = L(Node, BuildQuotedAtom(Pos, "Attr"));
  2942. Node = L(Node, BuildQuotedAtom(Pos, Name));
  2943. if (!ValueDefault) {
  2944. Node = L(Node, Values.empty() ? BuildQuotedAtom(Pos, TString()) : Values.front().Build());
  2945. }
  2946. }
  2947. if (!Node->Init(ctx, FakeSource.Get())) {
  2948. return false;
  2949. }
  2950. return true;
  2951. }
  2952. TAstNode* Translate(TContext& ctx) const final {
  2953. return Node->Translate(ctx);
  2954. }
  2955. TPtr DoClone() const final {
  2956. return {};
  2957. }
  2958. private:
  2959. TString Prefix;
  2960. TString Name;
  2961. TVector<TDeferredAtom> Values;
  2962. bool ValueDefault;
  2963. TNodePtr Node;
  2964. TSourcePtr FakeSource;
  2965. };
  2966. TNodePtr BuildPragma(TPosition pos, const TString& prefix, const TString& name, const TVector<TDeferredAtom>& values, bool valueDefault) {
  2967. return new TPragmaNode(pos, prefix, name, values, valueDefault);
  2968. }
  2969. class TSqlLambda final : public TAstListNode {
  2970. public:
  2971. TSqlLambda(TPosition pos, TVector<TString>&& args, TVector<TNodePtr>&& exprSeq)
  2972. : TAstListNode(pos)
  2973. , Args(args)
  2974. , ExprSeq(exprSeq)
  2975. {
  2976. FakeSource = BuildFakeSource(pos);
  2977. }
  2978. bool DoInit(TContext& ctx, ISource* src) override {
  2979. Y_UNUSED(src);
  2980. for (auto& exprPtr: ExprSeq) {
  2981. if (!exprPtr->Init(ctx, FakeSource.Get())) {
  2982. return {};
  2983. }
  2984. }
  2985. YQL_ENSURE(!ExprSeq.empty());
  2986. auto body = Y();
  2987. auto end = ExprSeq.end() - 1;
  2988. for (auto iter = ExprSeq.begin(); iter != end; ++iter) {
  2989. auto exprPtr = *iter;
  2990. const auto& label = exprPtr->GetLabel();
  2991. YQL_ENSURE(label);
  2992. body = L(body, Y("let", label, exprPtr));
  2993. }
  2994. body = Y("block", Q(L(body, Y("return", *end))));
  2995. auto args = Y();
  2996. for (const auto& arg: Args) {
  2997. args = L(args, BuildAtom(GetPos(), arg));
  2998. }
  2999. Add("lambda", Q(args), body);
  3000. return TAstListNode::DoInit(ctx, src);
  3001. }
  3002. TPtr DoClone() const final {
  3003. return new TSqlLambda(Pos, TVector<TString>(Args), CloneContainer(ExprSeq));
  3004. }
  3005. void DoUpdateState() const override {
  3006. State.Set(ENodeState::Const);
  3007. }
  3008. private:
  3009. TVector<TString> Args;
  3010. TVector<TNodePtr> ExprSeq;
  3011. TSourcePtr FakeSource;
  3012. };
  3013. TNodePtr BuildSqlLambda(TPosition pos, TVector<TString>&& args, TVector<TNodePtr>&& exprSeq) {
  3014. return new TSqlLambda(pos, std::move(args), std::move(exprSeq));
  3015. }
  3016. class TWorldIf final : public TAstListNode {
  3017. public:
  3018. TWorldIf(TPosition pos, TNodePtr predicate, TNodePtr thenNode, TNodePtr elseNode, bool isEvaluate)
  3019. : TAstListNode(pos)
  3020. , Predicate(predicate)
  3021. , ThenNode(thenNode)
  3022. , ElseNode(elseNode)
  3023. , IsEvaluate(isEvaluate)
  3024. {
  3025. FakeSource = BuildFakeSource(pos);
  3026. }
  3027. bool DoInit(TContext& ctx, ISource* src) override {
  3028. if (!Predicate->Init(ctx, FakeSource.Get())) {
  3029. return{};
  3030. }
  3031. Add(IsEvaluate ? "EvaluateIf!" : "If!");
  3032. Add("world");
  3033. auto coalesced = Y("Coalesce", Predicate, Y("Bool", Q("false")));
  3034. Add(IsEvaluate ? Y("EvaluateExpr", Y("EnsureType", coalesced, Y("DataType", Q("Bool")))) : coalesced);
  3035. if (!ThenNode->Init(ctx, FakeSource.Get())) {
  3036. return{};
  3037. }
  3038. Add(ThenNode);
  3039. if (ElseNode) {
  3040. if (!ElseNode->Init(ctx, FakeSource.Get())) {
  3041. return{};
  3042. }
  3043. Add(ElseNode);
  3044. }
  3045. return TAstListNode::DoInit(ctx, src);
  3046. }
  3047. TPtr DoClone() const final {
  3048. return new TWorldIf(GetPos(), SafeClone(Predicate), SafeClone(ThenNode), SafeClone(ElseNode), IsEvaluate);
  3049. }
  3050. private:
  3051. TNodePtr Predicate;
  3052. TNodePtr ThenNode;
  3053. TNodePtr ElseNode;
  3054. bool IsEvaluate;
  3055. TSourcePtr FakeSource;
  3056. };
  3057. TNodePtr BuildWorldIfNode(TPosition pos, TNodePtr predicate, TNodePtr thenNode, TNodePtr elseNode, bool isEvaluate) {
  3058. return new TWorldIf(pos, predicate, thenNode, elseNode, isEvaluate);
  3059. }
  3060. class TWorldFor final : public TAstListNode {
  3061. public:
  3062. TWorldFor(TPosition pos, TNodePtr list, TNodePtr bodyNode, TNodePtr elseNode, bool isEvaluate, bool isParallel)
  3063. : TAstListNode(pos)
  3064. , List(list)
  3065. , BodyNode(bodyNode)
  3066. , ElseNode(elseNode)
  3067. , IsEvaluate(isEvaluate)
  3068. , IsParallel(isParallel)
  3069. {
  3070. FakeSource = BuildFakeSource(pos);
  3071. }
  3072. bool DoInit(TContext& ctx, ISource* src) override {
  3073. if (!List->Init(ctx, FakeSource.Get())) {
  3074. return{};
  3075. }
  3076. Add(TStringBuilder() << (IsEvaluate ? "Evaluate": "") << (IsParallel ? "Parallel" : "") << "For!");
  3077. Add("world");
  3078. Add(IsEvaluate ? Y("EvaluateExpr", List) : List);
  3079. if (!BodyNode->Init(ctx, FakeSource.Get())) {
  3080. return{};
  3081. }
  3082. Add(BodyNode);
  3083. if (ElseNode) {
  3084. if (!ElseNode->Init(ctx, FakeSource.Get())) {
  3085. return{};
  3086. }
  3087. Add(ElseNode);
  3088. }
  3089. return TAstListNode::DoInit(ctx, src);
  3090. }
  3091. TPtr DoClone() const final {
  3092. return new TWorldFor(GetPos(), SafeClone(List), SafeClone(BodyNode), SafeClone(ElseNode), IsEvaluate, IsParallel);
  3093. }
  3094. private:
  3095. TNodePtr List;
  3096. TNodePtr BodyNode;
  3097. TNodePtr ElseNode;
  3098. bool IsEvaluate;
  3099. bool IsParallel;
  3100. TSourcePtr FakeSource;
  3101. };
  3102. TNodePtr BuildWorldForNode(TPosition pos, TNodePtr list, TNodePtr bodyNode, TNodePtr elseNode, bool isEvaluate, bool isParallel) {
  3103. return new TWorldFor(pos, list, bodyNode, elseNode, isEvaluate, isParallel);
  3104. }
  3105. class TAnalyzeNode final : public TAstListNode {
  3106. public:
  3107. TAnalyzeNode(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TAnalyzeParams& params, TScopedStatePtr scoped)
  3108. : TAstListNode(pos)
  3109. , Service(service)
  3110. , Cluster(cluster)
  3111. , Params(params)
  3112. , Scoped(scoped)
  3113. {
  3114. FakeSource = BuildFakeSource(pos);
  3115. scoped->UseCluster(Service, Cluster);
  3116. }
  3117. bool DoInit(TContext& ctx, ISource* src) override {
  3118. Y_UNUSED(src);
  3119. auto keys = Params.Table->Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::DROP);
  3120. if (!keys || !keys->Init(ctx, FakeSource.Get())) {
  3121. return false;
  3122. }
  3123. auto opts = Y();
  3124. auto columns = Y();
  3125. for (const auto& column: Params.Columns) {
  3126. columns->Add(Q(column));
  3127. }
  3128. opts->Add(Q(Y(Q("columns"), Q(columns))));
  3129. opts->Add(Q(Y(Q("mode"), Q("analyze"))));
  3130. Add("block", Q(Y(
  3131. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), Scoped->WrapCluster(Cluster, ctx))),
  3132. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  3133. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  3134. )));
  3135. return TAstListNode::DoInit(ctx, FakeSource.Get());
  3136. }
  3137. TPtr DoClone() const final {
  3138. return {};
  3139. }
  3140. private:
  3141. TString Service;
  3142. TDeferredAtom Cluster;
  3143. TAnalyzeParams Params;
  3144. TScopedStatePtr Scoped;
  3145. TSourcePtr FakeSource;
  3146. };
  3147. TNodePtr BuildAnalyze(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TAnalyzeParams& params, TScopedStatePtr scoped) {
  3148. return new TAnalyzeNode(pos, service, cluster, params, scoped);
  3149. }
  3150. class TShowCreateNode final : public TAstListNode {
  3151. public:
  3152. TShowCreateNode(TPosition pos, const TTableRef& tr, TScopedStatePtr scoped)
  3153. : TAstListNode(pos)
  3154. , Table(tr)
  3155. , Scoped(scoped)
  3156. , FakeSource(BuildFakeSource(pos))
  3157. {
  3158. Scoped->UseCluster(Table.Service, Table.Cluster);
  3159. }
  3160. bool DoInit(TContext& ctx, ISource* src) override {
  3161. if (Table.Options) {
  3162. if (!Table.Options->Init(ctx, src)) {
  3163. return false;
  3164. }
  3165. Table.Options = L(Table.Options, Q(Y(Q("showCreateTable"))));
  3166. } else {
  3167. Table.Options = Y(Q(Y(Q("showCreateTable"))));
  3168. }
  3169. bool asRef = ctx.PragmaRefSelect;
  3170. bool asAutoRef = true;
  3171. if (ctx.PragmaSampleSelect) {
  3172. asRef = false;
  3173. asAutoRef = false;
  3174. }
  3175. auto settings = Y(Q(Y(Q("type"))));
  3176. if (asRef) {
  3177. settings = L(settings, Q(Y(Q("ref"))));
  3178. } else if (asAutoRef) {
  3179. settings = L(settings, Q(Y(Q("autoref"))));
  3180. }
  3181. TNodePtr node(BuildInputTables(Pos, {Table}, false, Scoped));
  3182. if (!node->Init(ctx, src)) {
  3183. return false;
  3184. }
  3185. auto source = BuildTableSource(TPosition(ctx.Pos()), Table);
  3186. if (!source) {
  3187. return false;
  3188. }
  3189. auto output = source->Build(ctx);
  3190. if (!output) {
  3191. return false;
  3192. }
  3193. node = L(node, Y("let", "output", output));
  3194. auto writeResult(BuildWriteResult(Pos, "output", settings));
  3195. if (!writeResult->Init(ctx, src)) {
  3196. return false;
  3197. }
  3198. node = L(node, Y("let", "world", writeResult));
  3199. node = L(node, Y("return", "world"));
  3200. Add("block", Q(node));
  3201. return TAstListNode::DoInit(ctx, FakeSource.Get());
  3202. }
  3203. TPtr DoClone() const final {
  3204. return {};
  3205. }
  3206. private:
  3207. TTableRef Table;
  3208. TScopedStatePtr Scoped;
  3209. TSourcePtr FakeSource;
  3210. };
  3211. TNodePtr BuildShowCreate(TPosition pos, const TTableRef& tr, TScopedStatePtr scoped) {
  3212. return new TShowCreateNode(pos, tr, scoped);
  3213. }
  3214. class TBaseBackupCollectionNode
  3215. : public TAstListNode
  3216. , public TObjectOperatorContext
  3217. {
  3218. using TBase = TAstListNode;
  3219. public:
  3220. TBaseBackupCollectionNode(
  3221. TPosition pos,
  3222. const TString& prefix,
  3223. const TString& objectId,
  3224. const TObjectOperatorContext& context)
  3225. : TBase(pos)
  3226. , TObjectOperatorContext(context)
  3227. , Prefix(prefix)
  3228. , Id(objectId)
  3229. {}
  3230. bool DoInit(TContext& ctx, ISource* src) final {
  3231. auto keys = Y("Key");
  3232. keys = L(keys, Q(Y(Q("backupCollection"), Y("String", BuildQuotedAtom(Pos, Id)), Y("String", BuildQuotedAtom(Pos, Prefix)))));
  3233. auto options = this->FillOptions(ctx, Y());
  3234. Add("block", Q(Y(
  3235. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
  3236. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(options))),
  3237. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  3238. )));
  3239. return TAstListNode::DoInit(ctx, src);
  3240. }
  3241. virtual INode::TPtr FillOptions(TContext& ctx, INode::TPtr options) const = 0;
  3242. protected:
  3243. TString Prefix;
  3244. TString Id;
  3245. };
  3246. class TCreateBackupCollectionNode
  3247. : public TBaseBackupCollectionNode
  3248. {
  3249. using TBase = TBaseBackupCollectionNode;
  3250. public:
  3251. TCreateBackupCollectionNode(
  3252. TPosition pos,
  3253. const TString& prefix,
  3254. const TString& objectId,
  3255. const TCreateBackupCollectionParameters& params,
  3256. const TObjectOperatorContext& context)
  3257. : TBase(pos, prefix, objectId, context)
  3258. , Params(params)
  3259. {}
  3260. virtual INode::TPtr FillOptions(TContext& ctx, INode::TPtr options) const final {
  3261. options->Add(Q(Y(Q("mode"), Q("create"))));
  3262. auto settings = Y();
  3263. for (auto& [key, value] : Params.Settings) {
  3264. settings->Add(Q(Y(BuildQuotedAtom(Pos, key), Y("String", value.Build()))));
  3265. }
  3266. options->Add(Q(Y(Q("settings"), Q(settings))));
  3267. auto entries = Y();
  3268. if (Params.Database) {
  3269. entries->Add(Q(Y(Q(Y(Q("type"), Q("database"))))));
  3270. }
  3271. for (auto& table : Params.Tables) {
  3272. auto path = ctx.GetPrefixedPath(ServiceId, Cluster, table);
  3273. entries->Add(Q(Y(Q(Y(Q("type"), Q("table"))), Q(Y(Q("path"), path)))));
  3274. }
  3275. options->Add(Q(Y(Q("entries"), Q(entries))));
  3276. return options;
  3277. }
  3278. TPtr DoClone() const final {
  3279. return new TCreateBackupCollectionNode(GetPos(), Prefix, Id, Params, *this);
  3280. }
  3281. private:
  3282. TCreateBackupCollectionParameters Params;
  3283. };
  3284. class TAlterBackupCollectionNode
  3285. : public TBaseBackupCollectionNode
  3286. {
  3287. using TBase = TBaseBackupCollectionNode;
  3288. public:
  3289. TAlterBackupCollectionNode(
  3290. TPosition pos,
  3291. const TString& prefix,
  3292. const TString& objectId,
  3293. const TAlterBackupCollectionParameters& params,
  3294. const TObjectOperatorContext& context)
  3295. : TBase(pos, prefix, objectId, context)
  3296. , Params(params)
  3297. {}
  3298. virtual INode::TPtr FillOptions(TContext& ctx, INode::TPtr options) const final {
  3299. options->Add(Q(Y(Q("mode"), Q("alter"))));
  3300. auto settings = Y();
  3301. for (auto& [key, value] : Params.Settings) {
  3302. settings->Add(Q(Y(BuildQuotedAtom(Pos, key), Y("String", value.Build()))));
  3303. }
  3304. options->Add(Q(Y(Q("settings"), Q(settings))));
  3305. auto resetSettings = Y();
  3306. for (auto& key : Params.SettingsToReset) {
  3307. resetSettings->Add(BuildQuotedAtom(Pos, key));
  3308. }
  3309. options->Add(Q(Y(Q("resetSettings"), Q(resetSettings))));
  3310. auto entries = Y();
  3311. if (Params.Database != TAlterBackupCollectionParameters::EDatabase::Unchanged) {
  3312. entries->Add(Q(Y(Q(Y(Q("type"), Q("database"))), Q(Y(Q("action"), Q(Params.Database == TAlterBackupCollectionParameters::EDatabase::Add ? "add" : "drop"))))));
  3313. }
  3314. for (auto& table : Params.TablesToAdd) {
  3315. auto path = ctx.GetPrefixedPath(ServiceId, Cluster, table);
  3316. entries->Add(Q(Y(Q(Y(Q("type"), Q("table"))), Q(Y(Q("path"), path)), Q(Y(Q("action"), Q("add"))))));
  3317. }
  3318. for (auto& table : Params.TablesToDrop) {
  3319. auto path = ctx.GetPrefixedPath(ServiceId, Cluster, table);
  3320. entries->Add(Q(Y(Q(Y(Q("type"), Q("table"))), Q(Y(Q("path"), path)), Q(Y(Q("action"), Q("drop"))))));
  3321. }
  3322. options->Add(Q(Y(Q("alterEntries"), Q(entries))));
  3323. return options;
  3324. }
  3325. TPtr DoClone() const final {
  3326. return new TAlterBackupCollectionNode(GetPos(), Prefix, Id, Params, *this);
  3327. }
  3328. private:
  3329. TAlterBackupCollectionParameters Params;
  3330. };
  3331. class TDropBackupCollectionNode
  3332. : public TBaseBackupCollectionNode
  3333. {
  3334. using TBase = TBaseBackupCollectionNode;
  3335. public:
  3336. TDropBackupCollectionNode(
  3337. TPosition pos,
  3338. const TString& prefix,
  3339. const TString& objectId,
  3340. const TDropBackupCollectionParameters&,
  3341. const TObjectOperatorContext& context)
  3342. : TBase(pos, prefix, objectId, context)
  3343. {}
  3344. virtual INode::TPtr FillOptions(TContext&, INode::TPtr options) const final {
  3345. options->Add(Q(Y(Q("mode"), Q("drop"))));
  3346. return options;
  3347. }
  3348. TPtr DoClone() const final {
  3349. TDropBackupCollectionParameters params;
  3350. return new TDropBackupCollectionNode(GetPos(), Prefix, Id, params, *this);
  3351. }
  3352. };
  3353. TNodePtr BuildCreateBackupCollection(
  3354. TPosition pos,
  3355. const TString& prefix,
  3356. const TString& id,
  3357. const TCreateBackupCollectionParameters& params,
  3358. const TObjectOperatorContext& context)
  3359. {
  3360. return new TCreateBackupCollectionNode(pos, prefix, id, params, context);
  3361. }
  3362. TNodePtr BuildAlterBackupCollection(
  3363. TPosition pos,
  3364. const TString& prefix,
  3365. const TString& id,
  3366. const TAlterBackupCollectionParameters& params,
  3367. const TObjectOperatorContext& context)
  3368. {
  3369. return new TAlterBackupCollectionNode(pos, prefix, id, params, context);
  3370. }
  3371. TNodePtr BuildDropBackupCollection(
  3372. TPosition pos,
  3373. const TString& prefix,
  3374. const TString& id,
  3375. const TDropBackupCollectionParameters& params,
  3376. const TObjectOperatorContext& context)
  3377. {
  3378. return new TDropBackupCollectionNode(pos, prefix, id, params, context);
  3379. }
  3380. class TBackupNode final
  3381. : public TAstListNode
  3382. , public TObjectOperatorContext
  3383. {
  3384. using TBase = TAstListNode;
  3385. public:
  3386. TBackupNode(
  3387. TPosition pos,
  3388. const TString& prefix,
  3389. const TString& id,
  3390. const TBackupParameters& params,
  3391. const TObjectOperatorContext& context)
  3392. : TBase(pos)
  3393. , TObjectOperatorContext(context)
  3394. , Prefix(prefix)
  3395. , Id(id)
  3396. , Params(params)
  3397. {
  3398. Y_UNUSED(Params);
  3399. }
  3400. bool DoInit(TContext& ctx, ISource* src) override {
  3401. auto keys = Y("Key");
  3402. keys = L(keys, Q(Y(Q("backup"), Y("String", BuildQuotedAtom(Pos, Id)), Y("String", BuildQuotedAtom(Pos, Prefix)))));
  3403. auto opts = Y();
  3404. if (Params.Incremental) {
  3405. opts->Add(Q(Y(Q("mode"), Q("backupIncremental"))));
  3406. } else {
  3407. opts->Add(Q(Y(Q("mode"), Q("backup"))));
  3408. }
  3409. Add("block", Q(Y(
  3410. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
  3411. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  3412. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  3413. )));
  3414. return TAstListNode::DoInit(ctx, src);
  3415. }
  3416. TPtr DoClone() const final {
  3417. return new TBackupNode(GetPos(), Prefix, Id, Params, *this);
  3418. }
  3419. private:
  3420. TString Prefix;
  3421. TString Id;
  3422. TBackupParameters Params;
  3423. };
  3424. TNodePtr BuildBackup(
  3425. TPosition pos,
  3426. const TString& prefix,
  3427. const TString& id,
  3428. const TBackupParameters& params,
  3429. const TObjectOperatorContext& context)
  3430. {
  3431. return new TBackupNode(pos, prefix, id, params, context);
  3432. }
  3433. class TRestoreNode final
  3434. : public TAstListNode
  3435. , public TObjectOperatorContext
  3436. {
  3437. using TBase = TAstListNode;
  3438. public:
  3439. TRestoreNode(
  3440. TPosition pos,
  3441. const TString& prefix,
  3442. const TString& id,
  3443. const TRestoreParameters& params,
  3444. const TObjectOperatorContext& context)
  3445. : TBase(pos)
  3446. , TObjectOperatorContext(context)
  3447. , Prefix(prefix)
  3448. , Id(id)
  3449. , Params(params)
  3450. {
  3451. Y_UNUSED(Params);
  3452. }
  3453. bool DoInit(TContext& ctx, ISource* src) override {
  3454. auto keys = Y("Key");
  3455. keys = L(keys, Q(Y(Q("restore"), Y("String", BuildQuotedAtom(Pos, Id)), Y("String", BuildQuotedAtom(Pos, Prefix)))));
  3456. auto opts = Y();
  3457. opts->Add(Q(Y(Q("mode"), Q("restore"))));
  3458. if (Params.At) {
  3459. opts->Add(Q(Y(Q("at"), BuildQuotedAtom(Pos, Params.At))));
  3460. }
  3461. Add("block", Q(Y(
  3462. Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
  3463. Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
  3464. Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
  3465. )));
  3466. return TAstListNode::DoInit(ctx, src);
  3467. }
  3468. TPtr DoClone() const final {
  3469. return new TRestoreNode(GetPos(), Prefix, Id, Params, *this);
  3470. }
  3471. private:
  3472. TString Prefix;
  3473. TString Id;
  3474. TRestoreParameters Params;
  3475. };
  3476. TNodePtr BuildRestore(
  3477. TPosition pos,
  3478. const TString& prefix,
  3479. const TString& id,
  3480. const TRestoreParameters& params,
  3481. const TObjectOperatorContext& context)
  3482. {
  3483. return new TRestoreNode(pos, prefix, id, params, context);
  3484. }
  3485. } // namespace NSQLTranslationV1