12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758 |
- #include "node.h"
- #include "context.h"
- #include "object_processing.h"
- #include <yql/essentials/ast/yql_type_string.h>
- #include <yql/essentials/core/sql_types/yql_callable_names.h>
- #include <yql/essentials/providers/common/provider/yql_provider_names.h>
- #include <library/cpp/charset/ci_string.h>
- #include <util/digest/fnv.h>
- using namespace NYql;
- namespace NSQLTranslationV1 {
- bool ValidateView(TPosition pos, TContext& ctx, TStringBuf service, TViewDescription& view) {
- if (view.PrimaryFlag && !(service == KikimrProviderName || service == YdbProviderName)) {
- ctx.Error(pos) << "primary view is not supported for " << service << " tables";
- return false;
- }
- return true;
- }
- class TUniqueTableKey: public ITableKeys {
- public:
- TUniqueTableKey(TPosition pos, const TString& service, const TDeferredAtom& cluster,
- const TDeferredAtom& name, const TViewDescription& view)
- : ITableKeys(pos)
- , Service(service)
- , Cluster(cluster)
- , Name(name)
- , View(view)
- , Full(name.GetRepr())
- {
- if (!View.ViewName.empty()) {
- Full += ":" + View.ViewName;
- }
- }
- bool SetPrimaryView(TContext& ctx, TPosition pos) override {
- Y_UNUSED(ctx);
- Y_UNUSED(pos);
- View = {"", true};
- return true;
- }
- bool SetViewName(TContext& ctx, TPosition pos, const TString& view) override {
- Y_UNUSED(ctx);
- Y_UNUSED(pos);
- Full = Name.GetRepr();
- View = {view};
- if (!View.empty()) {
- Full = ":" + View.ViewName;
- }
- return true;
- }
- const TString* GetTableName() const override {
- return Name.GetLiteral() ? &Full : nullptr;
- }
- TNodePtr BuildKeys(TContext& ctx, ITableKeys::EBuildKeysMode mode) override {
- if (View == TViewDescription{"@"}) {
- auto key = Y("TempTable", Name.Build());
- return key;
- }
- bool tableScheme = mode == ITableKeys::EBuildKeysMode::CREATE;
- if (tableScheme && !View.empty()) {
- ctx.Error(Pos) << "Table view can not be created with CREATE TABLE clause";
- return nullptr;
- }
- auto path = ctx.GetPrefixedPath(Service, Cluster, Name);
- if (!path) {
- return nullptr;
- }
- auto key = Y("Key", Q(Y(Q(tableScheme ? "tablescheme" : "table"), Y("String", path))));
- key = AddView(key, View);
- if (!ValidateView(GetPos(), ctx, Service, View)) {
- return nullptr;
- }
- if (mode == ITableKeys::EBuildKeysMode::INPUT &&
- IsQueryMode(ctx.Settings.Mode) &&
- Service != KikimrProviderName &&
- Service != RtmrProviderName &&
- Service != YdbProviderName) {
- key = Y("MrTableConcat", key);
- }
- return key;
- }
- private:
- TString Service;
- TDeferredAtom Cluster;
- TDeferredAtom Name;
- TViewDescription View;
- TString Full;
- };
- TNodePtr BuildTableKey(TPosition pos, const TString& service, const TDeferredAtom& cluster,
- const TDeferredAtom& name, const TViewDescription& view) {
- return new TUniqueTableKey(pos, service, cluster, name, view);
- }
- class TTopicKey: public ITableKeys {
- public:
- TTopicKey(TPosition pos, const TDeferredAtom& cluster, const TDeferredAtom& name)
- : ITableKeys(pos)
- , Cluster(cluster)
- , Name(name)
- , Full(name.GetRepr())
- {
- }
- const TString* GetTableName() const override {
- return Name.GetLiteral() ? &Full : nullptr;
- }
- TNodePtr BuildKeys(TContext& ctx, ITableKeys::EBuildKeysMode) override {
- const auto path = ctx.GetPrefixedPath(Service, Cluster, Name);
- if (!path) {
- return nullptr;
- }
- auto key = Y("Key", Q(Y(Q("topic"), Y("String", path))));
- return key;
- }
- private:
- TString Service;
- TDeferredAtom Cluster;
- TDeferredAtom Name;
- TString View;
- TString Full;
- };
- TNodePtr BuildTopicKey(TPosition pos, const TDeferredAtom& cluster, const TDeferredAtom& name) {
- return new TTopicKey(pos, cluster, name);
- }
- static INode::TPtr CreateIndexType(TIndexDescription::EType type, const INode& node) {
- switch (type) {
- case TIndexDescription::EType::GlobalSync:
- return node.Q("syncGlobal");
- case TIndexDescription::EType::GlobalAsync:
- return node.Q("asyncGlobal");
- case TIndexDescription::EType::GlobalSyncUnique:
- return node.Q("syncGlobalUnique");
- case TIndexDescription::EType::GlobalVectorKmeansTree:
- return node.Q("globalVectorKmeansTree");
- }
- }
- enum class ETableSettingsParsingMode {
- Create,
- Alter
- };
- static INode::TPtr CreateTableSettings(const TTableSettings& tableSettings, ETableSettingsParsingMode parsingMode, const INode& node) {
- // short aliases for member function calls
- auto Y = [&node](auto&&... args) { return node.Y(std::forward<decltype(args)>(args)...); };
- auto Q = [&node](auto&&... args) { return node.Q(std::forward<decltype(args)>(args)...); };
- auto L = [&node](auto&&... args) { return node.L(std::forward<decltype(args)>(args)...); };
- auto settings = Y();
- if (tableSettings.DataSourcePath) {
- settings = L(settings, Q(Y(Q("data_source_path"), tableSettings.DataSourcePath)));
- }
- if (tableSettings.Location) {
- if (tableSettings.Location.IsSet()) {
- settings = L(settings, Q(Y(Q("location"), tableSettings.Location.GetValueSet())));
- } else {
- Y_ENSURE(parsingMode != ETableSettingsParsingMode::Create, "Can't reset LOCATION in create mode");
- settings = L(settings, Q(Y(Q("location"))));
- }
- }
- for (const auto& resetableParam : tableSettings.ExternalSourceParameters) {
- Y_ENSURE(resetableParam, "Empty parameter");
- if (resetableParam.IsSet()) {
- const auto& [id, value] = resetableParam.GetValueSet();
- settings = L(settings, Q(Y(Q(id.Name), value)));
- } else {
- Y_ENSURE(parsingMode != ETableSettingsParsingMode::Create,
- "Can't reset " << resetableParam.GetValueReset().Name << " in create mode"
- );
- settings = L(settings, Q(Y(Q(resetableParam.GetValueReset().Name))));
- }
- }
- if (tableSettings.CompactionPolicy) {
- settings = L(settings, Q(Y(Q("compactionPolicy"), tableSettings.CompactionPolicy)));
- }
- if (tableSettings.AutoPartitioningBySize) {
- const auto& ref = tableSettings.AutoPartitioningBySize.GetRef();
- settings = L(settings, Q(Y(Q("autoPartitioningBySize"), BuildQuotedAtom(ref.Pos, ref.Name))));
- }
- if (tableSettings.UniformPartitions && parsingMode == ETableSettingsParsingMode::Create) {
- settings = L(settings, Q(Y(Q("uniformPartitions"), tableSettings.UniformPartitions)));
- }
- if (tableSettings.PartitionAtKeys && parsingMode == ETableSettingsParsingMode::Create) {
- auto keysDesc = Y();
- for (const auto& key : tableSettings.PartitionAtKeys) {
- auto columnsDesc = Y();
- for (auto column : key) {
- columnsDesc = L(columnsDesc, column);
- }
- keysDesc = L(keysDesc, Q(columnsDesc));
- }
- settings = L(settings, Q(Y(Q("partitionAtKeys"), Q(keysDesc))));
- }
- if (tableSettings.PartitionSizeMb) {
- settings = L(settings, Q(Y(Q("partitionSizeMb"), tableSettings.PartitionSizeMb)));
- }
- if (tableSettings.AutoPartitioningByLoad) {
- const auto& ref = tableSettings.AutoPartitioningByLoad.GetRef();
- settings = L(settings, Q(Y(Q("autoPartitioningByLoad"), BuildQuotedAtom(ref.Pos, ref.Name))));
- }
- if (tableSettings.MinPartitions) {
- settings = L(settings, Q(Y(Q("minPartitions"), tableSettings.MinPartitions)));
- }
- if (tableSettings.MaxPartitions) {
- settings = L(settings, Q(Y(Q("maxPartitions"), tableSettings.MaxPartitions)));
- }
- if (tableSettings.PartitionCount) {
- settings = L(settings, Q(Y(Q("maxPartitions"), tableSettings.PartitionCount)));
- settings = L(settings, Q(Y(Q("minPartitions"), tableSettings.PartitionCount)));
- }
- if (tableSettings.KeyBloomFilter) {
- const auto& ref = tableSettings.KeyBloomFilter.GetRef();
- settings = L(settings, Q(Y(Q("keyBloomFilter"), BuildQuotedAtom(ref.Pos, ref.Name))));
- }
- if (tableSettings.ReadReplicasSettings) {
- settings = L(settings, Q(Y(Q("readReplicasSettings"), tableSettings.ReadReplicasSettings)));
- }
- if (const auto& ttl = tableSettings.TtlSettings) {
- if (ttl.IsSet()) {
- const auto& ttlSettings = ttl.GetValueSet();
- auto opts = Y();
- opts = L(opts, Q(Y(Q("columnName"), BuildQuotedAtom(ttlSettings.ColumnName.Pos, ttlSettings.ColumnName.Name))));
- auto tiersDesc = Y();
- for (const auto& tier : ttlSettings.Tiers) {
- auto tierDesc = Y();
- tierDesc = L(tierDesc, Q(Y(Q("evictionDelay"), tier.EvictionDelay)));
- if (tier.StorageName) {
- tierDesc = L(tierDesc, Q(Y(Q("storageName"), BuildQuotedAtom(tier.StorageName->Pos, tier.StorageName->Name))));
- }
- tiersDesc = L(tiersDesc, Q(tierDesc));
- }
- opts = L(opts, Q(Y(Q("tiers"), Q(tiersDesc))));
- if (ttlSettings.ColumnUnit) {
- opts = L(opts, Q(Y(Q("columnUnit"), Q(ToString(*ttlSettings.ColumnUnit)))));
- }
- settings = L(settings, Q(Y(Q("setTtlSettings"), Q(opts))));
- } else {
- YQL_ENSURE(parsingMode != ETableSettingsParsingMode::Create, "Can't reset TTL settings in create mode");
- settings = L(settings, Q(Y(Q("resetTtlSettings"), Q(Y()))));
- }
- }
- if (const auto& tiering = tableSettings.Tiering) {
- if (tiering.IsSet()) {
- settings = L(settings, Q(Y(Q("setTiering"), tiering.GetValueSet())));
- } else {
- YQL_ENSURE(parsingMode != ETableSettingsParsingMode::Create, "Can't reset TIERING in create mode");
- settings = L(settings, Q(Y(Q("resetTiering"), Q(Y()))));
- }
- }
- if (tableSettings.StoreExternalBlobs) {
- const auto& ref = tableSettings.StoreExternalBlobs.GetRef();
- settings = L(settings, Q(Y(Q("storeExternalBlobs"), BuildQuotedAtom(ref.Pos, ref.Name))));
- }
- if (tableSettings.StoreType && parsingMode == ETableSettingsParsingMode::Create) {
- const auto& ref = tableSettings.StoreType.GetRef();
- settings = L(settings, Q(Y(Q("storeType"), BuildQuotedAtom(ref.Pos, ref.Name))));
- }
- if (tableSettings.PartitionByHashFunction && parsingMode == ETableSettingsParsingMode::Create) {
- settings = L(settings, Q(Y(Q("partitionByHashFunction"), tableSettings.PartitionByHashFunction)));
- }
- return settings;
- }
- static INode::TPtr CreateVectorIndexSettings(const TVectorIndexSettings& vectorIndexSettings, const INode& node) {
- // short aliases for member function calls
- auto Y = [&node](auto&&... args) { return node.Y(std::forward<decltype(args)>(args)...); };
- auto Q = [&node](auto&&... args) { return node.Q(std::forward<decltype(args)>(args)...); };
- auto L = [&node](auto&&... args) { return node.L(std::forward<decltype(args)>(args)...); };
- auto settings = Y();
- if (vectorIndexSettings.Distance && vectorIndexSettings.Similarity) {
- Y_ENSURE(false, "distance and similarity shouldn't be set at the same time");
- } else if (vectorIndexSettings.Distance) {
- settings = L(settings, Q(Y(Q("distance"), Q(ToString(*vectorIndexSettings.Distance)))));
- } else if (vectorIndexSettings.Similarity) {
- settings = L(settings, Q(Y(Q("similarity"), Q(ToString(*vectorIndexSettings.Similarity)))));
- } else {
- Y_ENSURE(false, "distance or similarity should be set");
- }
- settings = L(settings, Q(Y(Q("vector_type"), Q(ToString(*vectorIndexSettings.VectorType)))));
- settings = L(settings, Q(Y(Q("vector_dimension"), Q(ToString(vectorIndexSettings.VectorDimension)))));
- settings = L(settings, Q(Y(Q("clusters"), Q(ToString(vectorIndexSettings.Clusters)))));
- settings = L(settings, Q(Y(Q("levels"), Q(ToString(vectorIndexSettings.Levels)))));
- return settings;
- }
- static INode::TPtr CreateIndexDesc(const TIndexDescription& index, ETableSettingsParsingMode parsingMode, const INode& node) {
- auto indexColumns = node.Y();
- for (const auto& col : index.IndexColumns) {
- indexColumns = node.L(indexColumns, BuildQuotedAtom(col.Pos, col.Name));
- }
- auto dataColumns = node.Y();
- for (const auto& col : index.DataColumns) {
- dataColumns = node.L(dataColumns, BuildQuotedAtom(col.Pos, col.Name));
- }
- const auto& indexType = node.Y(node.Q("indexType"), CreateIndexType(index.Type, node));
- const auto& indexName = node.Y(node.Q("indexName"), BuildQuotedAtom(index.Name.Pos, index.Name.Name));
- auto indexNode = node.Y(
- node.Q(indexName),
- node.Q(indexType),
- node.Q(node.Y(node.Q("indexColumns"), node.Q(indexColumns))),
- node.Q(node.Y(node.Q("dataColumns"), node.Q(dataColumns)))
- );
- if (index.TableSettings.IsSet()) {
- const auto& tableSettings = node.Q(node.Y(
- node.Q("tableSettings"),
- node.Q(CreateTableSettings(index.TableSettings, parsingMode, node))
- ));
- indexNode = node.L(indexNode, tableSettings);
- }
- if (const auto* indexSettingsPtr = std::get_if<TVectorIndexSettings>(&index.IndexSettings)) {
- const auto& indexSettings = node.Q(node.Y(
- node.Q("indexSettings"),
- node.Q(CreateVectorIndexSettings(*indexSettingsPtr, node))));
- indexNode = node.L(indexNode, indexSettings);
- }
- return indexNode;
- }
- static INode::TPtr CreateAlterIndex(const TIndexDescription& index, const INode& node) {
- const auto& indexName = node.Y(node.Q("indexName"), BuildQuotedAtom(index.Name.Pos, index.Name.Name));
- const auto& tableSettings = node.Y(
- node.Q("tableSettings"),
- node.Q(CreateTableSettings(index.TableSettings, ETableSettingsParsingMode::Alter, node))
- );
- return node.Y(
- node.Q(indexName),
- node.Q(tableSettings)
- );
- }
- static INode::TPtr CreateChangefeedDesc(const TChangefeedDescription& desc, const INode& node) {
- auto settings = node.Y();
- if (desc.Settings.Mode) {
- settings = node.L(settings, node.Q(node.Y(node.Q("mode"), desc.Settings.Mode)));
- }
- if (desc.Settings.Format) {
- settings = node.L(settings, node.Q(node.Y(node.Q("format"), desc.Settings.Format)));
- }
- if (desc.Settings.InitialScan) {
- settings = node.L(settings, node.Q(node.Y(node.Q("initial_scan"), desc.Settings.InitialScan)));
- }
- if (desc.Settings.VirtualTimestamps) {
- settings = node.L(settings, node.Q(node.Y(node.Q("virtual_timestamps"), desc.Settings.VirtualTimestamps)));
- }
- if (desc.Settings.ResolvedTimestamps) {
- settings = node.L(settings, node.Q(node.Y(node.Q("resolved_timestamps"), desc.Settings.ResolvedTimestamps)));
- }
- if (desc.Settings.RetentionPeriod) {
- settings = node.L(settings, node.Q(node.Y(node.Q("retention_period"), desc.Settings.RetentionPeriod)));
- }
- if (desc.Settings.TopicAutoPartitioning) {
- settings = node.L(settings, node.Q(node.Y(node.Q("topic_auto_partitioning"), desc.Settings.TopicAutoPartitioning)));
- }
- if (desc.Settings.TopicMaxActivePartitions) {
- settings = node.L(settings, node.Q(node.Y(node.Q("topic_max_active_partitions"), desc.Settings.TopicMaxActivePartitions)));
- }
- if (desc.Settings.TopicPartitions) {
- settings = node.L(settings, node.Q(node.Y(node.Q("topic_min_active_partitions"), desc.Settings.TopicPartitions)));
- }
- if (desc.Settings.AwsRegion) {
- settings = node.L(settings, node.Q(node.Y(node.Q("aws_region"), desc.Settings.AwsRegion)));
- }
- if (const auto& sink = desc.Settings.SinkSettings) {
- switch (sink->index()) {
- case 0: // local
- settings = node.L(settings, node.Q(node.Y(node.Q("local"), node.Q(node.Y()))));
- break;
- default:
- YQL_ENSURE(false, "Unexpected sink settings");
- }
- }
- auto state = node.Y();
- if (desc.Disable) {
- state = node.Q("disable");
- }
- return node.Y(
- node.Q(node.Y(node.Q("name"), BuildQuotedAtom(desc.Name.Pos, desc.Name.Name))),
- node.Q(node.Y(node.Q("settings"), node.Q(settings))),
- node.Q(node.Y(node.Q("state"), node.Q(state)))
- );
- }
- class TPrepTableKeys: public ITableKeys {
- public:
- TPrepTableKeys(TPosition pos, const TString& service, const TDeferredAtom& cluster,
- const TString& func, const TVector<TTableArg>& args)
- : ITableKeys(pos)
- , Service(service)
- , Cluster(cluster)
- , Func(func)
- , Args(args)
- {
- }
- void ExtractTableName(TContext&ctx, TTableArg& arg) {
- MakeTableFromExpression(Pos, ctx, arg.Expr, arg.Id);
- }
- TNodePtr BuildKeys(TContext& ctx, ITableKeys::EBuildKeysMode mode) override {
- if (mode == ITableKeys::EBuildKeysMode::CREATE) {
- // TODO: allow creation of multiple tables
- ctx.Error(Pos) << "Mutiple table creation is not implemented yet";
- return nullptr;
- }
- TCiString func(Func);
- if (func != "object" && func != "walkfolders") {
- for (auto& arg: Args) {
- if (arg.Expr->GetLabel()) {
- ctx.Error(Pos) << "Named arguments are not supported for table function " << to_upper(Func);
- return nullptr;
- }
- }
- }
- if (func == "concat_strict") {
- auto tuple = Y();
- for (auto& arg: Args) {
- ExtractTableName(ctx, arg);
- TNodePtr key;
- if (arg.HasAt) {
- key = Y("TempTable", arg.Id.Build());
- } else {
- auto path = ctx.GetPrefixedPath(Service, Cluster, arg.Id);
- if (!path) {
- return nullptr;
- }
- key = Y("Key", Q(Y(Q("table"), Y("String", path))));
- key = AddView(key, arg.View);
- if (!ValidateView(GetPos(), ctx, Service, arg.View)) {
- return nullptr;
- }
- }
- tuple = L(tuple, key);
- }
- return Q(tuple);
- }
- else if (func == "concat") {
- auto concat = Y("MrTableConcat");
- for (auto& arg : Args) {
- ExtractTableName(ctx, arg);
- TNodePtr key;
- if (arg.HasAt) {
- key = Y("TempTable", arg.Id.Build());
- } else {
- auto path = ctx.GetPrefixedPath(Service, Cluster, arg.Id);
- if (!path) {
- return nullptr;
- }
- key = Y("Key", Q(Y(Q("table"), Y("String", path))));
- key = AddView(key, arg.View);
- if (!ValidateView(GetPos(), ctx, Service, arg.View)) {
- return nullptr;
- }
- }
- concat = L(concat, key);
- }
- return concat;
- }
- else if (func == "range" || func == "range_strict" || func == "like" || func == "like_strict" ||
- func == "regexp" || func == "regexp_strict" || func == "filter" || func == "filter_strict") {
- bool isRange = func.StartsWith("range");
- bool isFilter = func.StartsWith("filter");
- size_t minArgs = isRange ? 1 : 2;
- size_t maxArgs = isRange ? 5 : 4;
- if (Args.size() < minArgs || Args.size() > maxArgs) {
- ctx.Error(Pos) << Func << " requires from " << minArgs << " to " << maxArgs << " arguments, but got: " << Args.size();
- return nullptr;
- }
- if (ctx.DiscoveryMode) {
- ctx.Error(Pos, TIssuesIds::YQL_NOT_ALLOWED_IN_DISCOVERY) << Func << " is not allowed in Discovery mode";
- return nullptr;
- }
- for (ui32 index=0; index < Args.size(); ++index) {
- auto& arg = Args[index];
- if (arg.HasAt) {
- ctx.Error(Pos) << "Temporary tables are not supported here";
- return nullptr;
- }
- if (!arg.View.empty()) {
- TStringBuilder sb;
- sb << "Use the last argument of " << Func << " to specify a VIEW." << Endl;
- if (isRange) {
- sb << "Possible arguments are: prefix, from, to, suffix, view." << Endl;
- } else if (isFilter) {
- sb << "Possible arguments are: prefix, filtering callable, suffix, view." << Endl;
- } else {
- sb << "Possible arguments are: prefix, pattern, suffix, view." << Endl;
- }
- sb << "Pass empty string in arguments if you want to skip.";
- ctx.Error(Pos) << sb;
- return nullptr;
- }
- if (!func.StartsWith("filter") || index != 1) {
- ExtractTableName(ctx, arg);
- }
- }
- auto path = ctx.GetPrefixedPath(Service, Cluster, Args[0].Id);
- if (!path) {
- return nullptr;
- }
- auto range = Y(func.EndsWith("_strict") ? "MrTableRangeStrict" : "MrTableRange", path);
- TNodePtr predicate;
- TDeferredAtom suffix;
- if (func.StartsWith("range")) {
- TDeferredAtom min;
- TDeferredAtom max;
- if (Args.size() > 1) {
- min = Args[1].Id;
- }
- if (Args.size() > 2) {
- max = Args[2].Id;
- }
- if (Args.size() > 3) {
- suffix = Args[3].Id;
- }
- if (min.Empty() && max.Empty()) {
- predicate = BuildLambda(Pos, Y("item"), Y("Bool", Q("true")));
- }
- else {
- auto minPred = !min.Empty() ? Y(">=", "item", Y("String", min.Build())) : nullptr;
- auto maxPred = !max.Empty() ? Y("<=", "item", Y("String", max.Build())) : nullptr;
- if (!minPred) {
- predicate = BuildLambda(Pos, Y("item"), maxPred);
- } else if (!maxPred) {
- predicate = BuildLambda(Pos, Y("item"), minPred);
- } else {
- predicate = BuildLambda(Pos, Y("item"), Y("And", minPred, maxPred));
- }
- }
- } else {
- if (Args.size() > 2) {
- suffix = Args[2].Id;
- }
- if (func.StartsWith("regexp")) {
- if (!ctx.PragmaRegexUseRe2) {
- ctx.Warning(Pos, TIssuesIds::CORE_LEGACY_REGEX_ENGINE) << "Legacy regex engine works incorrectly with unicode. Use PRAGMA RegexUseRe2='true';";
- }
- auto pattern = Args[1].Id;
- auto udf = ctx.PragmaRegexUseRe2 ?
- Y("Udf", Q("Re2.Grep"), Q(Y(Y("String", pattern.Build()), Y("Null")))):
- Y("Udf", Q("Pcre.BacktrackingGrep"), Y("String", pattern.Build()));
- predicate = BuildLambda(Pos, Y("item"), Y("Apply", udf, "item"));
- } else if (func.StartsWith("like")) {
- auto pattern = Args[1].Id;
- auto convertedPattern = Y("Apply", Y("Udf", Q("Re2.PatternFromLike")),
- Y("String", pattern.Build()));
- auto udf = Y("Udf", Q("Re2.Match"), Q(Y(convertedPattern, Y("Null"))));
- predicate = BuildLambda(Pos, Y("item"), Y("Apply", udf, "item"));
- } else {
- predicate = BuildLambda(Pos, Y("item"), Y("Apply", Args[1].Expr, "item"));
- }
- }
- range = L(range, predicate);
- range = L(range, suffix.Build() ? suffix.Build() : BuildQuotedAtom(Pos, ""));
- auto key = Y("Key", Q(Y(Q("table"), range)));
- if (Args.size() == maxArgs) {
- const auto& lastArg = Args.back();
- if (!lastArg.View.empty()) {
- ctx.Error(Pos) << Func << " requires that view should be set as last argument";
- return nullptr;
- }
- if (!lastArg.Id.Empty()) {
- key = L(key, Q(Y(Q("view"), Y("String", lastArg.Id.Build()))));
- }
- }
- return key;
- } else if (func == "each" || func == "each_strict") {
- auto each = Y(func == "each" ? "MrTableEach" : "MrTableEachStrict");
- for (auto& arg : Args) {
- if (arg.HasAt) {
- ctx.Error(Pos) << "Temporary tables are not supported here";
- return nullptr;
- }
- auto type = Y("ListType", Y("DataType", Q("String")));
- auto key = Y("Key", Q(Y(Q("table"), Y("EvaluateExpr",
- Y("EnsureType", Y("Coalesce", arg.Expr,
- Y("List", type)), type)))));
- key = AddView(key, arg.View);
- if (!ValidateView(GetPos(), ctx, Service, arg.View)) {
- return nullptr;
- }
- each = L(each, key);
- }
- if (ctx.PragmaUseTablePrefixForEach) {
- TStringBuf prefixPath = ctx.GetPrefixPath(Service, Cluster);
- if (prefixPath) {
- each = L(each, BuildQuotedAtom(Pos, TString(prefixPath)));
- }
- }
- return each;
- }
- else if (func == "folder") {
- size_t minArgs = 1;
- size_t maxArgs = 2;
- if (Args.size() < minArgs || Args.size() > maxArgs) {
- ctx.Error(Pos) << Func << " requires from " << minArgs << " to " << maxArgs << " arguments, but found: " << Args.size();
- return nullptr;
- }
- if (ctx.DiscoveryMode) {
- ctx.Error(Pos, TIssuesIds::YQL_NOT_ALLOWED_IN_DISCOVERY) << Func << " is not allowed in Discovery mode";
- return nullptr;
- }
- for (ui32 index = 0; index < Args.size(); ++index) {
- auto& arg = Args[index];
- if (arg.HasAt) {
- ctx.Error(Pos) << "Temporary tables are not supported here";
- return nullptr;
- }
- if (!arg.View.empty()) {
- ctx.Error(Pos) << Func << " doesn't supports views";
- return nullptr;
- }
- ExtractTableName(ctx, arg);
- }
- auto folder = Y("MrFolder");
- folder = L(folder, Args[0].Id.Build());
- folder = L(folder, Args.size() > 1 ? Args[1].Id.Build() : BuildQuotedAtom(Pos, ""));
- return folder;
- }
- else if (func == "walkfolders") {
- const size_t minPositionalArgs = 1;
- const size_t maxPositionalArgs = 2;
- size_t positionalArgsCnt = 0;
- for (const auto& arg : Args) {
- if (!arg.Expr->GetLabel()) {
- positionalArgsCnt++;
- } else {
- break;
- }
- }
- if (positionalArgsCnt < minPositionalArgs || positionalArgsCnt > maxPositionalArgs) {
- ctx.Error(Pos) << Func << " requires from " << minPositionalArgs
- << " to " << maxPositionalArgs
- << " positional arguments, but got: " << positionalArgsCnt;
- return nullptr;
- }
- constexpr auto walkFoldersModuleName = "walk_folders_module";
- ctx.RequiredModules.emplace(walkFoldersModuleName, "/lib/yql/walk_folders.yql");
- auto& rootFolderArg = Args[0];
- if (rootFolderArg.HasAt) {
- ctx.Error(Pos) << "Temporary tables are not supported here";
- return nullptr;
- }
- if (!rootFolderArg.View.empty()) {
- ctx.Error(Pos) << Func << " doesn't supports views";
- return nullptr;
- }
- ExtractTableName(ctx, rootFolderArg);
- const auto initState =
- positionalArgsCnt > 1
- ? Args[1].Expr
- : Y("List", Y("ListType", Y("DataType", Q("String"))));
- TNodePtr rootAttributes;
- TNodePtr preHandler;
- TNodePtr resolveHandler;
- TNodePtr diveHandler;
- TNodePtr postHandler;
- for (auto it = Args.begin() + positionalArgsCnt; it != Args.end(); ++it) {
- auto& arg = *it;
- const auto label = arg.Expr->GetLabel();
- if (label == "RootAttributes") {
- ExtractTableName(ctx, arg);
- rootAttributes = arg.Id.Build();
- }
- else if (label == "PreHandler") {
- preHandler = arg.Expr;
- }
- else if (label == "ResolveHandler") {
- resolveHandler = arg.Expr;
- }
- else if (label == "DiveHandler") {
- diveHandler = arg.Expr;
- }
- else if (label == "PostHandler") {
- postHandler = arg.Expr;
- }
- else {
- ctx.Warning(Pos, DEFAULT_ERROR) << "Unsupported named argument: "
- << label << " in " << Func;
- }
- }
- if (rootAttributes == nullptr) {
- rootAttributes = BuildQuotedAtom(Pos, "");
- }
- if (preHandler != nullptr || postHandler != nullptr) {
- const auto makePrePostHandlerType = BuildBind(Pos, walkFoldersModuleName, "MakePrePostHandlersType");
- const auto prePostHandlerType = Y("EvaluateType", Y("TypeHandle", Y("Apply", makePrePostHandlerType, Y("TypeOf", initState))));
- if (preHandler != nullptr) {
- preHandler = Y("Callable", prePostHandlerType, preHandler);
- }
- if (postHandler != nullptr) {
- postHandler = Y("Callable", prePostHandlerType, postHandler);
- }
- }
- if (preHandler == nullptr) {
- preHandler = Y("Void");
- }
- if (postHandler == nullptr) {
- postHandler = Y("Void");
- }
- const auto makeResolveDiveHandlerType = BuildBind(Pos, walkFoldersModuleName, "MakeResolveDiveHandlersType");
- const auto resolveDiveHandlerType = Y("EvaluateType", Y("TypeHandle", Y("Apply", makeResolveDiveHandlerType, Y("TypeOf", initState))));
- if (resolveHandler == nullptr) {
- resolveHandler = BuildBind(Pos, walkFoldersModuleName, "AnyNodeDiveHandler");
- }
- if (diveHandler == nullptr) {
- diveHandler = BuildBind(Pos, walkFoldersModuleName, "AnyNodeDiveHandler");
- }
- resolveHandler = Y("Callable", resolveDiveHandlerType, resolveHandler);
- diveHandler = Y("Callable", resolveDiveHandlerType, diveHandler);
- const auto initStateType = Y("EvaluateType", Y("TypeHandle", Y("TypeOf", initState)));
- const auto pickledInitState = Y("Pickle", initState);
- const auto initPath = rootFolderArg.Id.Build();
- return Y("MrWalkFolders", initPath, rootAttributes, pickledInitState, initStateType,
- preHandler, resolveHandler, diveHandler, postHandler);
- }
- else if (func == "tables") {
- if (!Args.empty()) {
- ctx.Error(Pos) << Func << " doesn't accept arguments";
- return nullptr;
- }
- return L(Y("DataTables"));
- }
- else if (func == "object") {
- const size_t positionalArgs = 2;
- auto result = Y("MrObject");
- auto settings = Y();
- //TVector<TNodePtr> settings;
- size_t argc = 0;
- for (ui32 index = 0; index < Args.size(); ++index) {
- auto& arg = Args[index];
- if (arg.HasAt) {
- ctx.Error(arg.Expr->GetPos()) << "Temporary tables are not supported here";
- return nullptr;
- }
- if (!arg.View.empty()) {
- ctx.Error(Pos) << to_upper(Func) << " doesn't supports views";
- return nullptr;
- }
- if (!arg.Expr->GetLabel()) {
- ExtractTableName(ctx, arg);
- result = L(result, arg.Id.Build());
- ++argc;
- } else {
- settings = L(settings, Q(Y(BuildQuotedAtom(arg.Expr->GetPos(), arg.Expr->GetLabel()), arg.Expr)));
- }
- }
- if (argc != positionalArgs) {
- ctx.Error(Pos) << to_upper(Func) << " requires exacty " << positionalArgs << " positional args, but got " << argc;
- return nullptr;
- }
- result = L(result, Q(settings));
- return result;
- }
- ctx.Error(Pos) << "Unknown table name preprocessor: " << Func;
- return nullptr;
- }
- private:
- TString Service;
- TDeferredAtom Cluster;
- TString Func;
- TVector<TTableArg> Args;
- };
- TNodePtr BuildTableKeys(TPosition pos, const TString& service, const TDeferredAtom& cluster,
- const TString& func, const TVector<TTableArg>& args) {
- return new TPrepTableKeys(pos, service, cluster, func, args);
- }
- class TInputOptions final: public TAstListNode {
- public:
- TInputOptions(TPosition pos, const TTableHints& hints)
- : TAstListNode(pos)
- , Hints(hints)
- {
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- for (auto& hint: Hints) {
- TString hintName = hint.first;
- TMaybe<TIssue> normalizeError = NormalizeName(Pos, hintName);
- if (!normalizeError.Empty()) {
- ctx.Error() << normalizeError->GetMessage();
- ctx.IncrementMonCounter("sql_errors", "NormalizeHintError");
- return false;
- }
- TNodePtr option = Y(BuildQuotedAtom(Pos, hintName));
- for (auto& x : hint.second) {
- if (!x->Init(ctx, src)) {
- return false;
- }
- option = L(option, x);
- }
- Nodes.push_back(Q(option));
- }
- return true;
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- TTableHints Hints;
- };
- TNodePtr BuildInputOptions(TPosition pos, const TTableHints& hints) {
- if (hints.empty()) {
- return nullptr;
- }
- return new TInputOptions(pos, hints);
- }
- class TIntoTableOptions: public TAstListNode {
- public:
- TIntoTableOptions(TPosition pos, const TVector<TString>& columns, const TTableHints& hints)
- : TAstListNode(pos)
- , Columns(columns)
- , Hints(hints)
- {
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(ctx);
- Y_UNUSED(src);
- TNodePtr options = Y();
- for (const auto& column: Columns) {
- options->Add(Q(column));
- }
- if (Columns) {
- Add(Q(Y(Q("erase_columns"), Q(options))));
- }
- for (const auto& hint : Hints) {
- TString hintName = hint.first;
- TMaybe<TIssue> normalizeError = NormalizeName(Pos, hintName);
- if (!normalizeError.Empty()) {
- ctx.Error() << normalizeError->GetMessage();
- ctx.IncrementMonCounter("sql_errors", "NormalizeHintError");
- return false;
- }
- TNodePtr option = Y(BuildQuotedAtom(Pos, hintName));
- for (auto& x : hint.second) {
- if (!x->Init(ctx, src)) {
- return false;
- }
- option = L(option, x);
- }
- Add(Q(option));
- }
- return true;
- }
- TNodePtr DoClone() const final {
- return new TIntoTableOptions(GetPos(), Columns, CloneContainer(Hints));
- }
- private:
- TVector<TString> Columns;
- TTableHints Hints;
- };
- TNodePtr BuildIntoTableOptions(TPosition pos, const TVector<TString>& eraseColumns, const TTableHints& hints) {
- return new TIntoTableOptions(pos, eraseColumns, hints);
- }
- class TInputTablesNode final: public TAstListNode {
- public:
- TInputTablesNode(TPosition pos, const TTableList& tables, bool inSubquery, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Tables(tables)
- , InSubquery(inSubquery)
- , Scoped(scoped)
- {
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- THashSet<TString> processedTables;
- for (auto& tr: Tables) {
- if (!processedTables.insert(tr.RefName).second) {
- continue;
- }
- Scoped->UseCluster(tr.Service, tr.Cluster);
- auto tableKeys = tr.Keys->GetTableKeys();
- auto keys = tableKeys->BuildKeys(ctx, ITableKeys::EBuildKeysMode::INPUT);
- if (!keys || !keys->Init(ctx, src)) {
- return false;
- }
- auto fields = Y("Void");
- auto source = Y("DataSource", BuildQuotedAtom(Pos, tr.Service), Scoped->WrapCluster(tr.Cluster, ctx));
- auto options = tr.Options ? Q(tr.Options) : Q(Y());
- Add(Y("let", "x", keys->Y(TString(ReadName), "world", source, keys, fields, options)));
- if (IsIn({KikimrProviderName, YdbProviderName}, tr.Service) && InSubquery) {
- ctx.Error() << "Using of system '" << tr.Service << "' is not allowed in SUBQUERY";
- return false;
- }
- if (tr.Service != YtProviderName || ctx.Settings.SaveWorldDependencies) {
- Add(Y("let", "world", Y(TString(LeftName), "x")));
- }
- Add(Y("let", tr.RefName, Y(TString(RightName), "x")));
- }
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- TTableList Tables;
- const bool InSubquery;
- TScopedStatePtr Scoped;
- };
- TNodePtr BuildInputTables(TPosition pos, const TTableList& tables, bool inSubquery, TScopedStatePtr scoped) {
- return new TInputTablesNode(pos, tables, inSubquery, scoped);
- }
- class TCreateTableNode final: public TAstListNode {
- public:
- TCreateTableNode(TPosition pos, const TTableRef& tr, bool existingOk, bool replaceIfExists, const TCreateTableParameters& params, TSourcePtr values, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Table(tr)
- , Params(params)
- , ExistingOk(existingOk)
- , ReplaceIfExists(replaceIfExists)
- , Values(std::move(values))
- , Scoped(scoped)
- {
- scoped->UseCluster(Table.Service, Table.Cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
- if (!keys || !keys->Init(ctx, src)) {
- return false;
- }
- if (!Params.PkColumns.empty()
- || !Params.PartitionByColumns.empty()
- || !Params.OrderByColumns.empty()
- || !Params.Indexes.empty()
- || !Params.Changefeeds.empty())
- {
- THashSet<TString> columnsSet;
- for (auto& col : Params.Columns) {
- columnsSet.insert(col.Name);
- }
- const bool allowUndefinedColumns = (Values != nullptr) && columnsSet.empty();
- THashSet<TString> pkColumns;
- for (auto& keyColumn : Params.PkColumns) {
- if (!allowUndefinedColumns && !columnsSet.contains(keyColumn.Name)) {
- ctx.Error(keyColumn.Pos) << "Undefined column: " << keyColumn.Name;
- return false;
- }
- if (!pkColumns.insert(keyColumn.Name).second) {
- ctx.Error(keyColumn.Pos) << "Duplicated column in PK: " << keyColumn.Name;
- return false;
- }
- }
- for (auto& keyColumn : Params.PartitionByColumns) {
- if (!allowUndefinedColumns && !columnsSet.contains(keyColumn.Name)) {
- ctx.Error(keyColumn.Pos) << "Undefined column: " << keyColumn.Name;
- return false;
- }
- }
- for (auto& keyColumn : Params.OrderByColumns) {
- if (!allowUndefinedColumns && !columnsSet.contains(keyColumn.first.Name)) {
- ctx.Error(keyColumn.first.Pos) << "Undefined column: " << keyColumn.first.Name;
- return false;
- }
- }
- THashSet<TString> indexNames;
- for (const auto& index : Params.Indexes) {
- if (!indexNames.insert(index.Name.Name).second) {
- ctx.Error(index.Name.Pos) << "Index " << index.Name.Name << " must be defined once";
- return false;
- }
- for (const auto& indexColumn : index.IndexColumns) {
- if (!allowUndefinedColumns && !columnsSet.contains(indexColumn.Name)) {
- ctx.Error(indexColumn.Pos) << "Undefined column: " << indexColumn.Name;
- return false;
- }
- }
- for (const auto& dataColumn : index.DataColumns) {
- if (!allowUndefinedColumns && !columnsSet.contains(dataColumn.Name)) {
- ctx.Error(dataColumn.Pos) << "Undefined column: " << dataColumn.Name;
- return false;
- }
- }
- }
- THashSet<TString> cfNames;
- for (const auto& cf : Params.Changefeeds) {
- if (!cfNames.insert(cf.Name.Name).second) {
- ctx.Error(cf.Name.Pos) << "Changefeed " << cf.Name.Name << " must be defined once";
- return false;
- }
- }
- }
- auto opts = Y();
- if (Table.Options) {
- if (!Table.Options->Init(ctx, src)) {
- return false;
- }
- opts = Table.Options;
- }
- if (ExistingOk) {
- opts = L(opts, Q(Y(Q("mode"), Q("create_if_not_exists"))));
- } else if (ReplaceIfExists) {
- opts = L(opts, Q(Y(Q("mode"), Q("create_or_replace"))));
- } else {
- opts = L(opts, Q(Y(Q("mode"), Q("create"))));
- }
- THashSet<TString> columnFamilyNames;
- if (Params.ColumnFamilies) {
- auto columnFamilies = Y();
- for (const auto& family : Params.ColumnFamilies) {
- if (!columnFamilyNames.insert(family.Name.Name).second) {
- ctx.Error(family.Name.Pos) << "Family " << family.Name.Name << " specified more than once";
- return false;
- }
- auto familyDesc = Y();
- familyDesc = L(familyDesc, Q(Y(Q("name"), BuildQuotedAtom(family.Name.Pos, family.Name.Name))));
- if (family.Data) {
- familyDesc = L(familyDesc, Q(Y(Q("data"), family.Data)));
- }
- if (family.Compression) {
- familyDesc = L(familyDesc, Q(Y(Q("compression"), family.Compression)));
- }
- if (family.CompressionLevel) {
- familyDesc = L(familyDesc, Q(Y(Q("compression_level"), family.CompressionLevel)));
- }
- columnFamilies = L(columnFamilies, Q(familyDesc));
- }
- opts = L(opts, Q(Y(Q("columnFamilies"), Q(columnFamilies))));
- }
- auto columns = Y();
- THashSet<TString> columnsWithDefaultValue;
- auto columnsDefaultValueSettings = Y();
- for (auto& col : Params.Columns) {
- auto columnDesc = Y();
- columnDesc = L(columnDesc, BuildQuotedAtom(Pos, col.Name));
- auto type = col.Type;
- if (type) {
- if (col.Nullable) {
- type = Y("AsOptionalType", type);
- }
- columnDesc = L(columnDesc, type);
- auto columnConstraints = Y();
- if (!col.Nullable) {
- columnConstraints = L(columnConstraints, Q(Y(Q("not_null"))));
- }
- if (col.Serial) {
- columnConstraints = L(columnConstraints, Q(Y(Q("serial"))));
- }
- if (col.DefaultExpr) {
- if (!col.DefaultExpr->Init(ctx, src)) {
- return false;
- }
- columnConstraints = L(columnConstraints, Q(Y(Q("default"), col.DefaultExpr)));
- }
- columnDesc = L(columnDesc, Q(Y(Q("columnConstrains"), Q(columnConstraints))));
- auto familiesDesc = Y();
- if (col.Families) {
- for (const auto& family : col.Families) {
- if (columnFamilyNames.find(family.Name) == columnFamilyNames.end()) {
- ctx.Error(family.Pos) << "Unknown family " << family.Name;
- return false;
- }
- familiesDesc = L(familiesDesc, BuildQuotedAtom(family.Pos, family.Name));
- }
- }
- columnDesc = L(columnDesc, Q(familiesDesc));
- }
- columns = L(columns, Q(columnDesc));
- }
- opts = L(opts, Q(Y(Q("columns"), Q(columns))));
- if (!columnsWithDefaultValue.empty()) {
- opts = L(opts, Q(Y(Q("columnsDefaultValues"), Q(columnsDefaultValueSettings))));
- }
- if (Table.Service == RtmrProviderName) {
- if (!Params.PkColumns.empty() && !Params.PartitionByColumns.empty()) {
- ctx.Error() << "Only one of PRIMARY KEY or PARTITION BY constraints may be specified";
- return false;
- }
- } else {
- if (!Params.OrderByColumns.empty()) {
- ctx.Error() << "ORDER BY is supported only for " << RtmrProviderName << " provider";
- return false;
- }
- }
- if (!Params.PkColumns.empty()) {
- auto primaryKey = Y();
- for (auto& col : Params.PkColumns) {
- primaryKey = L(primaryKey, BuildQuotedAtom(col.Pos, col.Name));
- }
- opts = L(opts, Q(Y(Q("primarykey"), Q(primaryKey))));
- if (!Params.OrderByColumns.empty()) {
- ctx.Error() << "PRIMARY KEY cannot be used with ORDER BY, use PARTITION BY instead";
- return false;
- }
- }
- if (!Params.PartitionByColumns.empty()) {
- auto partitionBy = Y();
- for (auto& col : Params.PartitionByColumns) {
- partitionBy = L(partitionBy, BuildQuotedAtom(col.Pos, col.Name));
- }
- opts = L(opts, Q(Y(Q("partitionby"), Q(partitionBy))));
- }
- if (!Params.OrderByColumns.empty()) {
- auto orderBy = Y();
- for (auto& col : Params.OrderByColumns) {
- orderBy = L(orderBy, Q(Y(BuildQuotedAtom(col.first.Pos, col.first.Name), col.second ? Q("1") : Q("0"))));
- }
- opts = L(opts, Q(Y(Q("orderby"), Q(orderBy))));
- }
- for (const auto& index : Params.Indexes) {
- const auto& desc = CreateIndexDesc(index, ETableSettingsParsingMode::Create, *this);
- opts = L(opts, Q(Y(Q("index"), Q(desc))));
- }
- for (const auto& cf : Params.Changefeeds) {
- const auto& desc = CreateChangefeedDesc(cf, *this);
- opts = L(opts, Q(Y(Q("changefeed"), Q(desc))));
- }
- if (Params.TableSettings.IsSet()) {
- opts = L(opts, Q(Y(Q("tableSettings"), Q(
- CreateTableSettings(Params.TableSettings, ETableSettingsParsingMode::Create, *this)
- ))));
- }
- switch (Params.TableType) {
- case ETableType::TableStore:
- opts = L(opts, Q(Y(Q("tableType"), Q("tableStore"))));
- break;
- case ETableType::ExternalTable:
- opts = L(opts, Q(Y(Q("tableType"), Q("externalTable"))));
- break;
- case ETableType::Table:
- break;
- }
- if (Params.Temporary) {
- opts = L(opts, Q(Y(Q("temporary"))));
- }
- TNodePtr node = nullptr;
- if (Values) {
- if (!Values->Init(ctx, nullptr)) {
- return false;
- }
- TTableList tableList;
- Values->GetInputTables(tableList);
- auto valuesSource = Values.Get();
- auto values = Values->Build(ctx);
- if (!Values) {
- return false;
- }
- TNodePtr inputTables(BuildInputTables(Pos, tableList, false, Scoped));
- if (!inputTables->Init(ctx, valuesSource)) {
- return false;
- }
- node = inputTables;
- node = L(node, Y("let", "values", values));
- } else {
- node = Y(Y("let", "values", Y("Void")));
- }
- auto write = Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.Service), Scoped->WrapCluster(Table.Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", keys, "values", Q(opts))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- );
- node = L(node, Y("let", "world", Y("block", Q(write))));
- node = L(node, Y("return", "world"));
- Add("block", Q(node));
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- const TTableRef Table;
- const TCreateTableParameters Params;
- const bool ExistingOk;
- const bool ReplaceIfExists;
- const TSourcePtr Values;
- TScopedStatePtr Scoped;
- };
- TNodePtr BuildCreateTable(TPosition pos, const TTableRef& tr, bool existingOk, bool replaceIfExists, const TCreateTableParameters& params, TSourcePtr values, TScopedStatePtr scoped)
- {
- return new TCreateTableNode(pos, tr, existingOk, replaceIfExists, params, std::move(values), scoped);
- }
- class TAlterTableNode final: public TAstListNode {
- public:
- TAlterTableNode(TPosition pos, const TTableRef& tr, const TAlterTableParameters& params, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Table(tr)
- , Params(params)
- , Scoped(scoped)
- {
- scoped->UseCluster(Table.Service, Table.Cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
- if (!keys || !keys->Init(ctx, src)) {
- return false;
- }
- auto actions = Y();
- if (Params.AddColumns) {
- auto columns = Y();
- for (auto& col : Params.AddColumns) {
- auto columnDesc = Y();
- columnDesc = L(columnDesc, BuildQuotedAtom(Pos, col.Name));
- auto type = col.Type;
- if (col.Nullable) {
- type = Y("AsOptionalType", type);
- }
- columnDesc = L(columnDesc, type);
- auto columnConstraints = Y();
- if (!col.Nullable) {
- columnConstraints = L(columnConstraints, Q(Y(Q("not_null"))));
- }
- if (col.Serial) {
- columnConstraints = L(columnConstraints, Q(Y(Q("serial"))));
- }
- if (col.DefaultExpr) {
- if (!col.DefaultExpr->Init(ctx, src)) {
- return false;
- }
- columnConstraints = L(columnConstraints, Q(Y(Q("default"), col.DefaultExpr)));
- }
- columnDesc = L(columnDesc, Q(Y(Q("columnConstrains"), Q(columnConstraints))));
- auto familiesDesc = Y();
- for (const auto& family : col.Families) {
- familiesDesc = L(familiesDesc, BuildQuotedAtom(family.Pos, family.Name));
- }
- columnDesc = L(columnDesc, Q(familiesDesc));
- columns = L(columns, Q(columnDesc));
- }
- actions = L(actions, Q(Y(Q("addColumns"), Q(columns))));
- }
- if (Params.DropColumns) {
- auto columns = Y();
- for (auto& colName : Params.DropColumns) {
- columns = L(columns, BuildQuotedAtom(Pos, colName));
- }
- actions = L(actions, Q(Y(Q("dropColumns"), Q(columns))));
- }
- if (Params.AlterColumns) {
- auto columns = Y();
- for (auto& col : Params.AlterColumns) {
- if (col.TypeOfChange == TColumnSchema::ETypeOfChange::DropNotNullConstraint) {
- auto columnDesc = Y();
- columnDesc = L(columnDesc, BuildQuotedAtom(Pos, col.Name));
- auto columnConstraints = Y();
- columnConstraints = L(columnConstraints, Q(Y(Q("drop_not_null"))));
- columnDesc = L(columnDesc, Q(Y(Q("changeColumnConstraints"), Q(columnConstraints))));
- columns = L(columns, Q(columnDesc));
- } else if (col.TypeOfChange == TColumnSchema::ETypeOfChange::SetNotNullConstraint) {
- // todo flown4qqqq
- } else if (col.TypeOfChange == TColumnSchema::ETypeOfChange::SetFamily) {
- auto columnDesc = Y();
- columnDesc = L(columnDesc, BuildQuotedAtom(Pos, col.Name));
- auto familiesDesc = Y();
- for (const auto& family : col.Families) {
- familiesDesc = L(familiesDesc, BuildQuotedAtom(family.Pos, family.Name));
- }
- columnDesc = L(columnDesc, Q(Y(Q("setFamily"), Q(familiesDesc))));
- columns = L(columns, Q(columnDesc));
- } else if (col.TypeOfChange == TColumnSchema::ETypeOfChange::Nothing) {
- // do nothing
- } else {
- ctx.Error(Pos) << " action is not supported";
- }
- }
- actions = L(actions, Q(Y(Q("alterColumns"), Q(columns))));
- }
- if (Params.AddColumnFamilies) {
- auto columnFamilies = Y();
- for (const auto& family : Params.AddColumnFamilies) {
- auto familyDesc = Y();
- familyDesc = L(familyDesc, Q(Y(Q("name"), BuildQuotedAtom(family.Name.Pos, family.Name.Name))));
- if (family.Data) {
- familyDesc = L(familyDesc, Q(Y(Q("data"), family.Data)));
- }
- if (family.Compression) {
- familyDesc = L(familyDesc, Q(Y(Q("compression"), family.Compression)));
- }
- if (family.CompressionLevel) {
- familyDesc = L(familyDesc, Q(Y(Q("compression_level"), family.CompressionLevel)));
- }
- columnFamilies = L(columnFamilies, Q(familyDesc));
- }
- actions = L(actions, Q(Y(Q("addColumnFamilies"), Q(columnFamilies))));
- }
- if (Params.AlterColumnFamilies) {
- auto columnFamilies = Y();
- for (const auto& family : Params.AlterColumnFamilies) {
- auto familyDesc = Y();
- familyDesc = L(familyDesc, Q(Y(Q("name"), BuildQuotedAtom(family.Name.Pos, family.Name.Name))));
- if (family.Data) {
- familyDesc = L(familyDesc, Q(Y(Q("data"), family.Data)));
- }
- if (family.Compression) {
- familyDesc = L(familyDesc, Q(Y(Q("compression"), family.Compression)));
- }
- if (family.CompressionLevel) {
- familyDesc = L(familyDesc, Q(Y(Q("compression_level"), family.CompressionLevel)));
- }
- columnFamilies = L(columnFamilies, Q(familyDesc));
- }
- actions = L(actions, Q(Y(Q("alterColumnFamilies"), Q(columnFamilies))));
- }
- if (Params.TableSettings.IsSet()) {
- actions = L(actions, Q(Y(Q("setTableSettings"), Q(
- CreateTableSettings(Params.TableSettings, ETableSettingsParsingMode::Alter, *this)
- ))));
- }
- for (const auto& index : Params.AddIndexes) {
- const auto& desc = CreateIndexDesc(index, ETableSettingsParsingMode::Alter, *this);
- actions = L(actions, Q(Y(Q("addIndex"), Q(desc))));
- }
- for (const auto& index : Params.AlterIndexes) {
- const auto& desc = CreateAlterIndex(index, *this);
- actions = L(actions, Q(Y(Q("alterIndex"), Q(desc))));
- }
- for (const auto& id : Params.DropIndexes) {
- auto indexName = BuildQuotedAtom(id.Pos, id.Name);
- actions = L(actions, Q(Y(Q("dropIndex"), indexName)));
- }
- if (Params.RenameIndexTo) {
- auto src = BuildQuotedAtom(Params.RenameIndexTo->first.Pos, Params.RenameIndexTo->first.Name);
- auto dst = BuildQuotedAtom(Params.RenameIndexTo->second.Pos, Params.RenameIndexTo->second.Name);
- auto desc = Y();
- desc = L(desc, Q(Y(Q("src"), src)));
- desc = L(desc, Q(Y(Q("dst"), dst)));
- actions = L(actions, Q(Y(Q("renameIndexTo"), Q(desc))));
- }
- if (Params.RenameTo) {
- auto destination = ctx.GetPrefixedPath(Scoped->CurrService, Scoped->CurrCluster,
- TDeferredAtom(Params.RenameTo->Pos, Params.RenameTo->Name));
- actions = L(actions, Q(Y(Q("renameTo"), destination)));
- }
- for (const auto& cf : Params.AddChangefeeds) {
- const auto& desc = CreateChangefeedDesc(cf, *this);
- actions = L(actions, Q(Y(Q("addChangefeed"), Q(desc))));
- }
- for (const auto& cf : Params.AlterChangefeeds) {
- const auto& desc = CreateChangefeedDesc(cf, *this);
- actions = L(actions, Q(Y(Q("alterChangefeed"), Q(desc))));
- }
- for (const auto& id : Params.DropChangefeeds) {
- const auto name = BuildQuotedAtom(id.Pos, id.Name);
- actions = L(actions, Q(Y(Q("dropChangefeed"), name)));
- }
- auto opts = Y();
- opts = L(opts, Q(Y(Q("mode"), Q("alter"))));
- opts = L(opts, Q(Y(Q("actions"), Q(actions))));
- switch (Params.TableType) {
- case ETableType::TableStore:
- opts = L(opts, Q(Y(Q("tableType"), Q("tableStore"))));
- break;
- case ETableType::ExternalTable:
- opts = L(opts, Q(Y(Q("tableType"), Q("externalTable"))));
- break;
- case ETableType::Table:
- break;
- }
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.Service), Scoped->WrapCluster(Table.Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- TTableRef Table;
- const TAlterTableParameters Params;
- TScopedStatePtr Scoped;
- };
- TNodePtr BuildAlterTable(TPosition pos, const TTableRef& tr, const TAlterTableParameters& params, TScopedStatePtr scoped)
- {
- return new TAlterTableNode(pos, tr, params, scoped);
- }
- class TDropTableNode final: public TAstListNode {
- public:
- TDropTableNode(TPosition pos, const TTableRef& tr, bool missingOk, ETableType tableType, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Table(tr)
- , TableType(tableType)
- , Scoped(scoped)
- , MissingOk(missingOk)
- {
- FakeSource = BuildFakeSource(pos);
- scoped->UseCluster(Table.Service, Table.Cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(src);
- auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::DROP);
- if (!keys || !keys->Init(ctx, FakeSource.Get())) {
- return false;
- }
- auto opts = Y();
- opts = L(opts, Q(Y(Q("mode"), Q(MissingOk ? "drop_if_exists" : "drop"))));
- switch (TableType) {
- case ETableType::TableStore:
- opts = L(opts, Q(Y(Q("tableType"), Q("tableStore"))));
- break;
- case ETableType::ExternalTable:
- opts = L(opts, Q(Y(Q("tableType"), Q("externalTable"))));
- break;
- case ETableType::Table:
- break;
- }
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.Service), Scoped->WrapCluster(Table.Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, FakeSource.Get());
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- TTableRef Table;
- ETableType TableType;
- TScopedStatePtr Scoped;
- TSourcePtr FakeSource;
- const bool MissingOk;
- };
- TNodePtr BuildDropTable(TPosition pos, const TTableRef& tr, bool missingOk, ETableType tableType, TScopedStatePtr scoped) {
- return new TDropTableNode(pos, tr, missingOk, tableType, scoped);
- }
- static INode::TPtr CreateConsumerDesc(const TTopicConsumerDescription& desc, const INode& node, bool alter) {
- auto settings = node.Y();
- if (desc.Settings.Important) {
- settings = node.L(settings, node.Q(node.Y(node.Q("important"), desc.Settings.Important)));
- }
- if (const auto& readFromTs = desc.Settings.ReadFromTs) {
- if (readFromTs.IsSet()) {
- settings = node.L(settings, node.Q(node.Y(node.Q("setReadFromTs"), readFromTs.GetValueSet())));
- } else if (alter) {
- settings = node.L(settings, node.Q(node.Y(node.Q("resetReadFromTs"), node.Q(node.Y()))));
- } else {
- YQL_ENSURE(false, "Cannot reset on create");
- }
- }
- if (const auto& readFromTs = desc.Settings.SupportedCodecs) {
- if (readFromTs.IsSet()) {
- settings = node.L(settings, node.Q(node.Y(node.Q("setSupportedCodecs"), readFromTs.GetValueSet())));
- } else if (alter) {
- settings = node.L(settings, node.Q(node.Y(node.Q("resetSupportedCodecs"), node.Q(node.Y()))));
- } else {
- YQL_ENSURE(false, "Cannot reset on create");
- }
- }
- return node.Y(
- node.Q(node.Y(node.Q("name"), BuildQuotedAtom(desc.Name.Pos, desc.Name.Name))),
- node.Q(node.Y(node.Q("settings"), node.Q(settings)))
- );
- }
- class TCreateTopicNode final: public TAstListNode {
- public:
- TCreateTopicNode(TPosition pos, const TTopicRef& tr, const TCreateTopicParameters& params, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Topic(tr)
- , Params(params)
- , Scoped(scoped)
- {
- scoped->UseCluster(TString(KikimrProviderName), Topic.Cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- auto keys = Topic.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
- if (!keys || !keys->Init(ctx, src)) {
- return false;
- }
- if (!Params.Consumers.empty())
- {
- THashSet<TString> consumerNames;
- for (const auto& consumer : Params.Consumers) {
- if (!consumerNames.insert(consumer.Name.Name).second) {
- ctx.Error(consumer.Name.Pos) << "Consumer " << consumer.Name.Name << " defined more than once";
- return false;
- }
- }
- }
- auto opts = Y();
- TString mode = Params.ExistingOk ? "create_if_not_exists" : "create";
- opts = L(opts, Q(Y(Q("mode"), Q(mode))));
- for (const auto& consumer : Params.Consumers) {
- const auto& desc = CreateConsumerDesc(consumer, *this, false);
- opts = L(opts, Q(Y(Q("consumer"), Q(desc))));
- }
- if (Params.TopicSettings.IsSet()) {
- auto settings = Y();
- #define INSERT_TOPIC_SETTING(NAME) \
- if (const auto& NAME##Val = Params.TopicSettings.NAME) { \
- if (NAME##Val.IsSet()) { \
- settings = L(settings, Q(Y(Q(Y_STRINGIZE(set##NAME)), NAME##Val.GetValueSet()))); \
- } else { \
- YQL_ENSURE(false, "Can't reset on create"); \
- } \
- }
- INSERT_TOPIC_SETTING(MaxPartitions)
- INSERT_TOPIC_SETTING(MinPartitions)
- INSERT_TOPIC_SETTING(RetentionPeriod)
- INSERT_TOPIC_SETTING(SupportedCodecs)
- INSERT_TOPIC_SETTING(PartitionWriteSpeed)
- INSERT_TOPIC_SETTING(PartitionWriteBurstSpeed)
- INSERT_TOPIC_SETTING(MeteringMode)
- INSERT_TOPIC_SETTING(AutoPartitioningStabilizationWindow)
- INSERT_TOPIC_SETTING(AutoPartitioningUpUtilizationPercent)
- INSERT_TOPIC_SETTING(AutoPartitioningDownUtilizationPercent)
- INSERT_TOPIC_SETTING(AutoPartitioningStrategy)
- #undef INSERT_TOPIC_SETTING
- opts = L(opts, Q(Y(Q("topicSettings"), Q(settings))));
- }
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, TString(KikimrProviderName)),
- Scoped->WrapCluster(Topic.Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- const TTopicRef Topic;
- const TCreateTopicParameters Params;
- TScopedStatePtr Scoped;
- };
- TNodePtr BuildCreateTopic(
- TPosition pos, const TTopicRef& tr, const TCreateTopicParameters& params, TScopedStatePtr scoped
- ){
- return new TCreateTopicNode(pos, tr, params, scoped);
- }
- class TAlterTopicNode final: public TAstListNode {
- public:
- TAlterTopicNode(TPosition pos, const TTopicRef& tr, const TAlterTopicParameters& params, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Topic(tr)
- , Params(params)
- , Scoped(scoped)
- {
- scoped->UseCluster(TString(KikimrProviderName), Topic.Cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- auto keys = Topic.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::CREATE);
- if (!keys || !keys->Init(ctx, src)) {
- return false;
- }
- if (!Params.AddConsumers.empty())
- {
- THashSet<TString> consumerNames;
- for (const auto& consumer : Params.AddConsumers) {
- if (!consumerNames.insert(consumer.Name.Name).second) {
- ctx.Error(consumer.Name.Pos) << "Consumer " << consumer.Name.Name << " defined more than once";
- return false;
- }
- }
- }
- if (!Params.AlterConsumers.empty())
- {
- THashSet<TString> consumerNames;
- for (const auto& [_, consumer] : Params.AlterConsumers) {
- if (!consumerNames.insert(consumer.Name.Name).second) {
- ctx.Error(consumer.Name.Pos) << "Consumer " << consumer.Name.Name << " altered more than once";
- return false;
- }
- }
- }
- if (!Params.DropConsumers.empty())
- {
- THashSet<TString> consumerNames;
- for (const auto& consumer : Params.DropConsumers) {
- if (!consumerNames.insert(consumer.Name).second) {
- ctx.Error(consumer.Pos) << "Consumer " << consumer.Name << " dropped more than once";
- return false;
- }
- }
- }
- auto opts = Y();
- TString mode = Params.MissingOk ? "alter_if_exists" : "alter";
- opts = L(opts, Q(Y(Q("mode"), Q(mode))));
- for (const auto& consumer : Params.AddConsumers) {
- const auto& desc = CreateConsumerDesc(consumer, *this, false);
- opts = L(opts, Q(Y(Q("addConsumer"), Q(desc))));
- }
- for (const auto& [_, consumer] : Params.AlterConsumers) {
- const auto& desc = CreateConsumerDesc(consumer, *this, true);
- opts = L(opts, Q(Y(Q("alterConsumer"), Q(desc))));
- }
- for (const auto& consumer : Params.DropConsumers) {
- const auto name = BuildQuotedAtom(consumer.Pos, consumer.Name);
- opts = L(opts, Q(Y(Q("dropConsumer"), name)));
- }
- if (Params.TopicSettings.IsSet()) {
- auto settings = Y();
- #define INSERT_TOPIC_SETTING(NAME) \
- if (const auto& NAME##Val = Params.TopicSettings.NAME) { \
- if (NAME##Val.IsSet()) { \
- settings = L(settings, Q(Y(Q(Y_STRINGIZE(set##NAME)), NAME##Val.GetValueSet()))); \
- } else { \
- settings = L(settings, Q(Y(Q(Y_STRINGIZE(reset##NAME)), Y()))); \
- } \
- }
- INSERT_TOPIC_SETTING(MaxPartitions)
- INSERT_TOPIC_SETTING(MinPartitions)
- INSERT_TOPIC_SETTING(RetentionPeriod)
- INSERT_TOPIC_SETTING(SupportedCodecs)
- INSERT_TOPIC_SETTING(PartitionWriteSpeed)
- INSERT_TOPIC_SETTING(PartitionWriteBurstSpeed)
- INSERT_TOPIC_SETTING(MeteringMode)
- INSERT_TOPIC_SETTING(AutoPartitioningStabilizationWindow)
- INSERT_TOPIC_SETTING(AutoPartitioningUpUtilizationPercent)
- INSERT_TOPIC_SETTING(AutoPartitioningDownUtilizationPercent)
- INSERT_TOPIC_SETTING(AutoPartitioningStrategy)
- #undef INSERT_TOPIC_SETTING
- opts = L(opts, Q(Y(Q("topicSettings"), Q(settings))));
- }
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, TString(KikimrProviderName)),
- Scoped->WrapCluster(Topic.Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- const TTopicRef Topic;
- const TAlterTopicParameters Params;
- TScopedStatePtr Scoped;
- };
- TNodePtr BuildAlterTopic(
- TPosition pos, const TTopicRef& tr, const TAlterTopicParameters& params, TScopedStatePtr scoped
- ){
- return new TAlterTopicNode(pos, tr, params, scoped);
- }
- class TDropTopicNode final: public TAstListNode {
- public:
- TDropTopicNode(TPosition pos, const TTopicRef& tr, const TDropTopicParameters& params, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Topic(tr)
- , Params(params)
- , Scoped(scoped)
- {
- scoped->UseCluster(TString(KikimrProviderName), Topic.Cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(src);
- auto keys = Topic.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::DROP);
- if (!keys || !keys->Init(ctx, FakeSource.Get())) {
- return false;
- }
- auto opts = Y();
- TString mode = Params.MissingOk ? "drop_if_exists" : "drop";
- opts = L(opts, Q(Y(Q("mode"), Q(mode))));
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, TString(KikimrProviderName)),
- Scoped->WrapCluster(Topic.Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, FakeSource.Get());
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- TTopicRef Topic;
- TDropTopicParameters Params;
- TScopedStatePtr Scoped;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildDropTopic(TPosition pos, const TTopicRef& tr, const TDropTopicParameters& params, TScopedStatePtr scoped) {
- return new TDropTopicNode(pos, tr, params, scoped);
- }
- class TCreateRole final: public TAstListNode {
- public:
- TCreateRole(TPosition pos, bool isUser, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TMaybe<TRoleParameters>& params, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , IsUser(isUser)
- , Service(service)
- , Cluster(cluster)
- , Name(name)
- , Params(params)
- , Scoped(scoped)
- {
- FakeSource = BuildFakeSource(pos);
- scoped->UseCluster(service, cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(src);
- auto name = Name.Build();
- TNodePtr password;
- if (Params && Params->Password) {
- password = Params->Password->Build();
- }
- TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
- if (!name->Init(ctx, FakeSource.Get()) || !cluster->Init(ctx, FakeSource.Get())) {
- return false;
- }
- if (password && !password->Init(ctx, FakeSource.Get())) {
- return false;
- }
- TVector<TNodePtr> roles;
- if (Params && !Params->Roles.empty()) {
- for (auto& item : Params->Roles) {
- roles.push_back(item.Build());
- if (!roles.back()->Init(ctx, FakeSource.Get())) {
- return false;
- }
- }
- }
- auto options = Y(Q(Y(Q("mode"), Q(IsUser ? "createUser" : "createGroup"))));
- if (Params) {
- if (Params->IsPasswordEncrypted) {
- options = L(options, Q(Y(Q("passwordEncrypted"))));
- }
- if (Params->Password) {
- options = L(options, Q(Y(Q("password"), password)));
- } else {
- options = L(options, Q(Y(Q("nullPassword"))));
- }
- if (!Params->Roles.empty()) {
- options = L(options, Q(Y(Q("roles"), Q(new TAstListNodeImpl(Pos, std::move(roles))))));
- }
- }
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)),
- Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, FakeSource.Get());
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- const bool IsUser;
- const TString Service;
- TDeferredAtom Cluster;
- TDeferredAtom Name;
- const TMaybe<TRoleParameters> Params;
- TScopedStatePtr Scoped;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildCreateUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TMaybe<TRoleParameters>& params, TScopedStatePtr scoped) {
- bool isUser = true;
- return new TCreateRole(pos, isUser, service, cluster, name, params, scoped);
- }
- TNodePtr BuildCreateGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TMaybe<TRoleParameters>& params, TScopedStatePtr scoped) {
- bool isUser = false;
- return new TCreateRole(pos, isUser, service, cluster, name, params, scoped);
- }
- class TAlterUser final: public TAstListNode {
- public:
- TAlterUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TRoleParameters& params, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Service(service)
- , Cluster(cluster)
- , Name(name)
- , Params(params)
- , Scoped(scoped)
- {
- FakeSource = BuildFakeSource(pos);
- scoped->UseCluster(service, cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(src);
- auto name = Name.Build();
- TNodePtr password;
- if (Params.Password) {
- password = Params.Password->Build();
- }
- TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
- if (!name->Init(ctx, FakeSource.Get()) || !cluster->Init(ctx, FakeSource.Get())) {
- return false;
- }
- if (password && !password->Init(ctx, FakeSource.Get())) {
- return false;
- }
- auto options = Y(Q(Y(Q("mode"), Q("alterUser"))));
- if (Params.IsPasswordEncrypted) {
- options = L(options, Q(Y(Q("passwordEncrypted"))));
- }
- if (Params.Password) {
- options = L(options, Q(Y(Q("password"), password)));
- } else {
- options = L(options, Q(Y(Q("nullPassword"))));
- }
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)),
- Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, FakeSource.Get());
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- const TString Service;
- TDeferredAtom Cluster;
- TDeferredAtom Name;
- const TRoleParameters Params;
- TScopedStatePtr Scoped;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildAlterUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TRoleParameters& params, TScopedStatePtr scoped) {
- return new TAlterUser(pos, service, cluster, name, params, scoped);
- }
- class TAlterSequence final: public TAstListNode {
- public:
- TAlterSequence(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TString& id, const TSequenceParameters& params, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Service(service)
- , Cluster(cluster)
- , Id(id)
- , Params(params)
- , Scoped(scoped)
- {
- FakeSource = BuildFakeSource(pos);
- scoped->UseCluster(service, cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(src);
- TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
- if (!cluster->Init(ctx, FakeSource.Get())) {
- return false;
- }
- auto options = Y();
- TString mode = Params.MissingOk ? "alter_if_exists" : "alter";
- options = L(options, Q(Y(Q("mode"), Q(mode))));
- if (Params.IsRestart) {
- if (Params.RestartValue) {
- TString strValue = Params.RestartValue->Build()->GetLiteralValue();
- ui64 value = FromString<ui64>(strValue);
- ui64 maxValue = ui64(std::numeric_limits<i64>::max());
- ui64 minValue = 1;
- if (value > maxValue) {
- ctx.Error(Pos) << "Restart value: " << value << " cannot be greater than max value: " << maxValue;
- return false;
- }
- if (value < minValue) {
- ctx.Error(Pos) << "Restart value: " << value << " cannot be less than min value: " << minValue;
- return false;
- }
- options = L(options, Q(Y(Q("restart"), Q(ToString(value)))));
- } else {
- options = L(options, Q(Y(Q("restart"), Q(TString()))));
- }
- }
- if (Params.StartValue) {
- TString strValue = Params.StartValue->Build()->GetLiteralValue();
- ui64 value = FromString<ui64>(strValue);
- ui64 maxValue = ui64(std::numeric_limits<i64>::max());
- ui64 minValue = 1;
- if (value > maxValue) {
- ctx.Error(Pos) << "Start value: " << value << " cannot be greater than max value: " << maxValue;
- return false;
- }
- if (value < minValue) {
- ctx.Error(Pos) << "Start value: " << value << " cannot be less than min value: " << minValue;
- return false;
- }
- options = L(options, Q(Y(Q("start"), Q(ToString(value)))));
- }
- if (Params.Increment) {
- TString strValue = Params.Increment->Build()->GetLiteralValue();
- ui64 value = FromString<ui64>(strValue);
- ui64 maxValue = ui64(std::numeric_limits<i64>::max());
- if (value > maxValue) {
- ctx.Error(Pos) << "Increment: " << value << " cannot be greater than max value: " << maxValue;
- return false;
- }
- if (value == 0) {
- ctx.Error(Pos) << "Increment must not be zero";
- return false;
- }
- options = L(options, Q(Y(Q("increment"), Q(ToString(value)))));
- }
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, TString(KikimrProviderName)),
- Scoped->WrapCluster(Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("sequence"), Y("String", BuildQuotedAtom(Pos, Id))))), Y("Void"), Q(options))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- const TString Service;
- TDeferredAtom Cluster;
- TString Id;
- const TSequenceParameters Params;
- TScopedStatePtr Scoped;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildAlterSequence(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TString& id, const TSequenceParameters& params, TScopedStatePtr scoped) {
- return new TAlterSequence(pos, service, cluster, id, params, scoped);
- }
- class TRenameRole final: public TAstListNode {
- public:
- TRenameRole(TPosition pos, bool isUser, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TDeferredAtom& newName, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , IsUser(isUser)
- , Service(service)
- , Cluster(cluster)
- , Name(name)
- , NewName(newName)
- , Scoped(scoped)
- {
- FakeSource = BuildFakeSource(pos);
- scoped->UseCluster(service, cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(src);
- auto name = Name.Build();
- auto newName = NewName.Build();
- TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
- if (!name->Init(ctx, FakeSource.Get()) ||
- !newName->Init(ctx, FakeSource.Get()) ||
- !cluster->Init(ctx, FakeSource.Get()))
- {
- return false;
- }
- auto options = Y(Q(Y(Q("mode"), Q(IsUser ? "renameUser" : "renameGroup"))));
- options = L(options, Q(Y(Q("newName"), newName)));
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)),
- Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, FakeSource.Get());
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- const bool IsUser;
- const TString Service;
- TDeferredAtom Cluster;
- TDeferredAtom Name;
- TDeferredAtom NewName;
- TScopedStatePtr Scoped;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildRenameUser(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TDeferredAtom& newName, TScopedStatePtr scoped) {
- const bool isUser = true;
- return new TRenameRole(pos, isUser, service, cluster, name, newName, scoped);
- }
- TNodePtr BuildRenameGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TDeferredAtom& newName, TScopedStatePtr scoped) {
- const bool isUser = false;
- return new TRenameRole(pos, isUser, service, cluster, name, newName, scoped);
- }
- class TAlterGroup final: public TAstListNode {
- public:
- TAlterGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TVector<TDeferredAtom>& toChange, bool isDrop, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Service(service)
- , Cluster(cluster)
- , Name(name)
- , ToChange(toChange)
- , IsDrop(isDrop)
- , Scoped(scoped)
- {
- FakeSource = BuildFakeSource(pos);
- scoped->UseCluster(service, cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(src);
- auto name = Name.Build();
- TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
- if (!name->Init(ctx, FakeSource.Get()) || !cluster->Init(ctx, FakeSource.Get())) {
- return false;
- }
- TVector<TNodePtr> toChange;
- for (auto& item : ToChange) {
- toChange.push_back(item.Build());
- if (!toChange.back()->Init(ctx, FakeSource.Get())) {
- return false;
- }
- }
- auto options = Y(Q(Y(Q("mode"), Q(IsDrop ? "dropUsersFromGroup" : "addUsersToGroup"))));
- options = L(options, Q(Y(Q("roles"), Q(new TAstListNodeImpl(Pos, std::move(toChange))))));
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)),
- Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, FakeSource.Get());
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- const TString Service;
- TDeferredAtom Cluster;
- TDeferredAtom Name;
- TVector<TDeferredAtom> ToChange;
- const bool IsDrop;
- TScopedStatePtr Scoped;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildAlterGroup(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TDeferredAtom& name, const TVector<TDeferredAtom>& toChange, bool isDrop,
- TScopedStatePtr scoped)
- {
- return new TAlterGroup(pos, service, cluster, name, toChange, isDrop, scoped);
- }
- class TDropRoles final: public TAstListNode {
- public:
- TDropRoles(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& toDrop, bool isUser, bool missingOk, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Service(service)
- , Cluster(cluster)
- , ToDrop(toDrop)
- , IsUser(isUser)
- , MissingOk(missingOk)
- , Scoped(scoped)
- {
- FakeSource = BuildFakeSource(pos);
- scoped->UseCluster(service, cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(src);
- TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
- if (!cluster->Init(ctx, FakeSource.Get())) {
- return false;
- }
- const char* mode = IsUser ?
- (MissingOk ? "dropUserIfExists" : "dropUser") :
- (MissingOk ? "dropGroupIfExists" : "dropGroup");
- auto options = Y(Q(Y(Q("mode"), Q(mode))));
- auto block = Y(Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)));
- for (auto& item : ToDrop) {
- auto name = item.Build();
- if (!name->Init(ctx, FakeSource.Get())) {
- return false;
- }
- block = L(block, Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("role"), Y("String", name)))), Y("Void"), Q(options))));
- }
- block = L(block, Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world")));
- Add("block", Q(block));
- return TAstListNode::DoInit(ctx, FakeSource.Get());
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- const TString Service;
- TDeferredAtom Cluster;
- TVector<TDeferredAtom> ToDrop;
- const bool IsUser;
- const bool MissingOk;
- TScopedStatePtr Scoped;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildUpsertObjectOperation(TPosition pos, const TString& objectId, const TString& typeId,
- std::map<TString, TDeferredAtom>&& features, const TObjectOperatorContext& context) {
- return new TUpsertObject(pos, objectId, typeId, false, false, std::move(features), std::set<TString>(), context);
- }
- TNodePtr BuildCreateObjectOperation(TPosition pos, const TString& objectId, const TString& typeId,
- bool existingOk, bool replaceIfExists, std::map<TString, TDeferredAtom>&& features, const TObjectOperatorContext& context) {
- return new TCreateObject(pos, objectId, typeId, existingOk, replaceIfExists, std::move(features), std::set<TString>(), context);
- }
- TNodePtr BuildAlterObjectOperation(TPosition pos, const TString& secretId, const TString& typeId,
- std::map<TString, TDeferredAtom>&& features, std::set<TString>&& featuresToReset, const TObjectOperatorContext& context)
- {
- return new TAlterObject(pos, secretId, typeId, false, false, std::move(features), std::move(featuresToReset), context);
- }
- TNodePtr BuildDropObjectOperation(TPosition pos, const TString& secretId, const TString& typeId,
- bool missingOk, std::map<TString, TDeferredAtom>&& options, const TObjectOperatorContext& context)
- {
- return new TDropObject(pos, secretId, typeId, missingOk, false, std::move(options), std::set<TString>(), context);
- }
- TNodePtr BuildDropRoles(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& toDrop, bool isUser, bool missingOk, TScopedStatePtr scoped) {
- return new TDropRoles(pos, service, cluster, toDrop, isUser, missingOk, scoped);
- }
- class TPermissionsAction final : public TAstListNode {
- public:
- struct TPermissionParameters {
- TString PermissionAction;
- TVector<TDeferredAtom> Permissions;
- TVector<TDeferredAtom> SchemaPaths;
- TVector<TDeferredAtom> RoleNames;
- };
- TPermissionsAction(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TPermissionParameters& parameters, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Service(service)
- , Cluster(cluster)
- , Parameters(parameters)
- , Scoped(scoped)
- {
- FakeSource = BuildFakeSource(pos);
- scoped->UseCluster(service, cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(src);
- TNodePtr cluster = Scoped->WrapCluster(Cluster, ctx);
- TNodePtr permissionAction = TDeferredAtom(Pos, Parameters.PermissionAction).Build();
- if (!permissionAction->Init(ctx, FakeSource.Get()) ||
- !cluster->Init(ctx, FakeSource.Get())) {
- return false;
- }
- TVector<TNodePtr> paths;
- paths.reserve(Parameters.SchemaPaths.size());
- for (auto& item : Parameters.SchemaPaths) {
- paths.push_back(item.Build());
- if (!paths.back()->Init(ctx, FakeSource.Get())) {
- return false;
- }
- }
- auto options = Y(Q(Y(Q("paths"), Q(new TAstListNodeImpl(Pos, std::move(paths))))));
- TVector<TNodePtr> permissions;
- permissions.reserve(Parameters.Permissions.size());
- for (auto& item : Parameters.Permissions) {
- permissions.push_back(item.Build());
- if (!permissions.back()->Init(ctx, FakeSource.Get())) {
- return false;
- }
- }
- options = L(options, Q(Y(Q("permissions"), Q(new TAstListNodeImpl(Pos, std::move(permissions))))));
- TVector<TNodePtr> roles;
- roles.reserve(Parameters.RoleNames.size());
- for (auto& item : Parameters.RoleNames) {
- roles.push_back(item.Build());
- if (!roles.back()->Init(ctx, FakeSource.Get())) {
- return false;
- }
- }
- options = L(options, Q(Y(Q("roles"), Q(new TAstListNodeImpl(Pos, std::move(roles))))));
- auto block = Y(Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), cluster)));
- block = L(block, Y("let", "world", Y(TString(WriteName), "world", "sink", Y("Key", Q(Y(Q("permission"), Y("String", permissionAction)))), Y("Void"), Q(options))));
- block = L(block, Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world")));
- Add("block", Q(block));
- return TAstListNode::DoInit(ctx, FakeSource.Get());
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- const TString Service;
- TDeferredAtom Cluster;
- TPermissionParameters Parameters;
- TScopedStatePtr Scoped;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildGrantPermissions(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& permissions, const TVector<TDeferredAtom>& schemaPaths, const TVector<TDeferredAtom>& roleNames, TScopedStatePtr scoped) {
- return new TPermissionsAction(pos,
- service,
- cluster,
- {.PermissionAction = "grant",
- .Permissions = permissions,
- .SchemaPaths = schemaPaths,
- .RoleNames = roleNames},
- scoped);
- }
- TNodePtr BuildRevokePermissions(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TVector<TDeferredAtom>& permissions, const TVector<TDeferredAtom>& schemaPaths, const TVector<TDeferredAtom>& roleNames, TScopedStatePtr scoped) {
- return new TPermissionsAction(pos,
- service,
- cluster,
- {.PermissionAction = "revoke",
- .Permissions = permissions,
- .SchemaPaths = schemaPaths,
- .RoleNames = roleNames},
- scoped);
- }
- class TAsyncReplication
- : public TAstListNode
- , protected TObjectOperatorContext
- {
- protected:
- virtual INode::TPtr FillOptions(INode::TPtr options) const = 0;
- public:
- explicit TAsyncReplication(TPosition pos, const TString& id, const TString& mode, const TObjectOperatorContext& context)
- : TAstListNode(pos)
- , TObjectOperatorContext(context)
- , Id(id)
- , Mode(mode)
- {
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Scoped->UseCluster(ServiceId, Cluster);
- auto keys = Y("Key", Q(Y(Q("replication"), Y("String", BuildQuotedAtom(Pos, Id)))));
- auto options = FillOptions(Y(Q(Y(Q("mode"), Q(Mode)))));
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(options))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- const TString Id;
- const TString Mode;
- }; // TAsyncReplication
- class TCreateAsyncReplication final: public TAsyncReplication {
- public:
- explicit TCreateAsyncReplication(TPosition pos, const TString& id,
- std::vector<std::pair<TString, TString>>&& targets,
- std::map<TString, TNodePtr>&& settings,
- const TObjectOperatorContext& context)
- : TAsyncReplication(pos, id, "create", context)
- , Targets(std::move(targets))
- , Settings(std::move(settings))
- {
- }
- protected:
- INode::TPtr FillOptions(INode::TPtr options) const override {
- if (!Targets.empty()) {
- auto targets = Y();
- for (auto&& [remote, local] : Targets) {
- auto target = Y();
- target = L(target, Q(Y(Q("remote"), Q(remote))));
- target = L(target, Q(Y(Q("local"), Q(local))));
- targets = L(targets, Q(target));
- }
- options = L(options, Q(Y(Q("targets"), Q(targets))));
- }
- if (!Settings.empty()) {
- auto settings = Y();
- for (auto&& [k, v] : Settings) {
- if (v) {
- settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k), v)));
- } else {
- settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k))));
- }
- }
- options = L(options, Q(Y(Q("settings"), Q(settings))));
- }
- return options;
- }
- private:
- std::vector<std::pair<TString, TString>> Targets; // (remote, local)
- std::map<TString, TNodePtr> Settings;
- }; // TCreateAsyncReplication
- TNodePtr BuildCreateAsyncReplication(TPosition pos, const TString& id,
- std::vector<std::pair<TString, TString>>&& targets,
- std::map<TString, TNodePtr>&& settings,
- const TObjectOperatorContext& context)
- {
- return new TCreateAsyncReplication(pos, id, std::move(targets), std::move(settings), context);
- }
- class TDropAsyncReplication final: public TAsyncReplication {
- public:
- explicit TDropAsyncReplication(TPosition pos, const TString& id, bool cascade, const TObjectOperatorContext& context)
- : TAsyncReplication(pos, id, cascade ? "dropCascade" : "drop", context)
- {
- }
- protected:
- INode::TPtr FillOptions(INode::TPtr options) const override {
- return options;
- }
- }; // TDropAsyncReplication
- TNodePtr BuildDropAsyncReplication(TPosition pos, const TString& id, bool cascade, const TObjectOperatorContext& context) {
- return new TDropAsyncReplication(pos, id, cascade, context);
- }
- class TAlterAsyncReplication final: public TAsyncReplication {
- public:
- explicit TAlterAsyncReplication(TPosition pos, const TString& id,
- std::map<TString, TNodePtr>&& settings,
- const TObjectOperatorContext& context)
- : TAsyncReplication(pos, id, "alter", context)
- , Settings(std::move(settings))
- {
- }
- protected:
- INode::TPtr FillOptions(INode::TPtr options) const override {
- if (!Settings.empty()) {
- auto settings = Y();
- for (auto&& [k, v] : Settings) {
- if (v) {
- settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k), v)));
- } else {
- settings = L(settings, Q(Y(BuildQuotedAtom(Pos, k))));
- }
- }
- options = L(options, Q(Y(Q("settings"), Q(settings))));
- }
- return options;
- }
- private:
- std::map<TString, TNodePtr> Settings;
- }; // TAlterAsyncReplication
- TNodePtr BuildAlterAsyncReplication(TPosition pos, const TString& id,
- std::map<TString, TNodePtr>&& settings,
- const TObjectOperatorContext& context)
- {
- return new TAlterAsyncReplication(pos, id, std::move(settings), context);
- }
- static const TMap<EWriteColumnMode, TString> columnModeToStrMapMR {
- {EWriteColumnMode::Default, ""},
- {EWriteColumnMode::Insert, "append"},
- {EWriteColumnMode::Renew, "renew"}
- };
- static const TMap<EWriteColumnMode, TString> columnModeToStrMapStat {
- {EWriteColumnMode::Upsert, "upsert"}
- };
- static const TMap<EWriteColumnMode, TString> columnModeToStrMapKikimr {
- {EWriteColumnMode::Default, ""},
- {EWriteColumnMode::Insert, "insert_abort"},
- {EWriteColumnMode::InsertOrAbort, "insert_abort"},
- {EWriteColumnMode::InsertOrIgnore, "insert_ignore"},
- {EWriteColumnMode::InsertOrRevert, "insert_revert"},
- {EWriteColumnMode::Upsert, "upsert"},
- {EWriteColumnMode::Replace, "replace"},
- {EWriteColumnMode::Update, "update"},
- {EWriteColumnMode::UpdateOn, "update_on"},
- {EWriteColumnMode::Delete, "delete"},
- {EWriteColumnMode::DeleteOn, "delete_on"},
- };
- class TWriteTableNode final: public TAstListNode {
- public:
- TWriteTableNode(TPosition pos, const TString& label, const TTableRef& table, EWriteColumnMode mode,
- TNodePtr options, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Label(label)
- , Table(table)
- , Mode(mode)
- , Options(options)
- , Scoped(scoped)
- {
- scoped->UseCluster(Table.Service, Table.Cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- auto keys = Table.Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::WRITE);
- if (!keys || !keys->Init(ctx, src)) {
- return false;
- }
- auto getModesMap = [] (const TString& serviceName) -> const TMap<EWriteColumnMode, TString>& {
- if (serviceName == KikimrProviderName || serviceName == YdbProviderName) {
- return columnModeToStrMapKikimr;
- } else if (serviceName == StatProviderName) {
- return columnModeToStrMapStat;
- } else {
- return columnModeToStrMapMR;
- }
- };
- auto options = Y();
- if (Options) {
- if (!Options->Init(ctx, src)) {
- return false;
- }
- options = L(Options);
- }
- if (Mode != EWriteColumnMode::Default) {
- auto modeStr = getModesMap(Table.Service).FindPtr(Mode);
- options->Add(Q(Y(Q("mode"), Q(modeStr ? *modeStr : "unsupported"))));
- }
- Add("block", Q((Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Table.Service), Scoped->WrapCluster(Table.Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Label, Q(options))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- ))));
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- TString Label;
- TTableRef Table;
- EWriteColumnMode Mode;
- TNodePtr Options;
- TScopedStatePtr Scoped;
- };
- TNodePtr BuildWriteTable(TPosition pos, const TString& label, const TTableRef& table, EWriteColumnMode mode, TNodePtr options,
- TScopedStatePtr scoped)
- {
- return new TWriteTableNode(pos, label, table, mode, std::move(options), scoped);
- }
- class TClustersSinkOperationBase: public TAstListNode {
- protected:
- TClustersSinkOperationBase(TPosition pos)
- : TAstListNode(pos)
- {}
- virtual TPtr ProduceOperation() = 0;
- bool DoInit(TContext& ctx, ISource* src) override {
- auto block(Y());
- auto op = ProduceOperation();
- if (!op) {
- return false;
- }
- block = L(block, op);
- block = L(block, Y("return", "world"));
- Add("block", Q(block));
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return {};
- }
- };
- class TCommitClustersNode: public TClustersSinkOperationBase {
- public:
- TCommitClustersNode(TPosition pos)
- : TClustersSinkOperationBase(pos)
- {
- }
- TPtr ProduceOperation() override {
- return Y("let", "world", Y("CommitAll!", "world"));
- }
- };
- TNodePtr BuildCommitClusters(TPosition pos) {
- return new TCommitClustersNode(pos);
- }
- class TRollbackClustersNode: public TClustersSinkOperationBase {
- public:
- TRollbackClustersNode(TPosition pos)
- : TClustersSinkOperationBase(pos)
- {
- }
- TPtr ProduceOperation() override {
- return Y("let", "world", Y("CommitAll!", "world", Q(Y(Q(Y(Q("mode"), Q("rollback")))))));
- }
- };
- TNodePtr BuildRollbackClusters(TPosition pos) {
- return new TRollbackClustersNode(pos);
- }
- class TWriteResultNode final: public TAstListNode {
- public:
- TWriteResultNode(TPosition pos, const TString& label, TNodePtr settings)
- : TAstListNode(pos)
- , Label(label)
- , Settings(settings)
- , CommitClusters(BuildCommitClusters(Pos))
- {}
- bool DoInit(TContext& ctx, ISource* src) override {
- auto block(Y(
- Y("let", "result_sink", Y("DataSink", Q(TString(ResultProviderName)))),
- Y("let", "world", Y(TString(WriteName), "world", "result_sink", Y("Key"), Label, Q(Settings)))
- ));
- if (ctx.PragmaAutoCommit) {
- block = L(block, Y("let", "world", CommitClusters));
- }
- block = L(block, Y("return", Y(TString(CommitName), "world", "result_sink")));
- Add("block", Q(block));
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- TString Label;
- TNodePtr Settings;
- TNodePtr CommitClusters;
- };
- TNodePtr BuildWriteResult(TPosition pos, const TString& label, TNodePtr settings) {
- return new TWriteResultNode(pos, label, settings);
- }
- class TYqlProgramNode: public TAstListNode {
- public:
- TYqlProgramNode(TPosition pos, const TVector<TNodePtr>& blocks, bool topLevel, TScopedStatePtr scoped, bool useSeq)
- : TAstListNode(pos)
- , Blocks(blocks)
- , TopLevel(topLevel)
- , Scoped(scoped)
- , UseSeq(useSeq)
- {}
- bool DoInit(TContext& ctx, ISource* src) override {
- bool hasError = false;
- INode::TPtr currentWorldsHolder;
- INode::TPtr seqNode;
- if (UseSeq) {
- currentWorldsHolder = new TAstListNodeImpl(GetPos());
- seqNode = new TAstListNodeImpl(GetPos());
- seqNode->Add("Seq!","world");
- }
- INode* currentWorlds = UseSeq ? currentWorldsHolder.Get() : this;
- auto flushCurrentWorlds = [&](bool changeSeq, bool finish) {
- currentWorldsHolder->Add(Y("return","world"));
- auto lambda = BuildLambda(GetPos(), Y("world"), Y("block", Q(currentWorldsHolder)));
- seqNode->Add(lambda);
- if (finish) {
- Add(Y("let", "world", seqNode));
- } else {
- currentWorldsHolder = new TAstListNodeImpl(GetPos());
- currentWorlds = currentWorldsHolder.Get();
- }
- if (changeSeq) {
- Add(Y("let", "world", seqNode));
- seqNode = new TAstListNodeImpl(GetPos());
- seqNode->Add("Seq!","world");
- }
- };
- if (TopLevel) {
- for (auto& var: ctx.Variables) {
- if (!var.second.second->Init(ctx, src)) {
- hasError = true;
- continue;
- }
- Add(Y(
- "declare",
- new TAstAtomNodeImpl(var.second.first, var.first, TNodeFlags::ArbitraryContent),
- var.second.second));
- }
- for (const auto& overrideLibrary: ctx.OverrideLibraries) {
- auto node = Y(
- "override_library",
- new TAstAtomNodeImpl(
- std::get<TPosition>(overrideLibrary.second),
- overrideLibrary.first, TNodeFlags::ArbitraryContent
- ));
- Add(node);
- }
- for (const auto& package: ctx.Packages) {
- const auto& [url, urlPosition] = std::get<1U>(package.second);
- auto node = Y(
- "package",
- new TAstAtomNodeImpl(
- std::get<TPosition>(package.second), package.first,
- TNodeFlags::ArbitraryContent
- ),
- new TAstAtomNodeImpl(urlPosition, url, TNodeFlags::ArbitraryContent));
- if (const auto& tokenWithPosition = std::get<2U>(package.second)) {
- const auto& [token, tokenPosition] = *tokenWithPosition;
- node = L(node, new TAstAtomNodeImpl(tokenPosition, token, TNodeFlags::ArbitraryContent));
- }
- Add(node);
- }
- for (const auto& lib : ctx.Libraries) {
- auto node = Y("library", new TAstAtomNodeImpl(std::get<TPosition>(lib.second), lib.first, TNodeFlags::ArbitraryContent));
- if (const auto& first = std::get<1U>(lib.second)) {
- node = L(node, new TAstAtomNodeImpl(first->second, first->first, TNodeFlags::ArbitraryContent));
- if (const auto& second = std::get<2U>(lib.second)) {
- node = L(node, new TAstAtomNodeImpl(second->second, second->first, TNodeFlags::ArbitraryContent));
- }
- }
- Add(node);
- }
- for (const auto& p : ctx.PackageVersions) {
- Add(Y("set_package_version", BuildQuotedAtom(Pos, p.first), BuildQuotedAtom(Pos, ToString(p.second))));
- }
- Add(Y("import", "aggregate_module", BuildQuotedAtom(Pos, "/lib/yql/aggregate.yql")));
- Add(Y("import", "window_module", BuildQuotedAtom(Pos, "/lib/yql/window.yql")));
- for (const auto& module : ctx.Settings.ModuleMapping) {
- TString moduleName(module.first + "_module");
- moduleName.to_lower();
- Add(Y("import", moduleName, BuildQuotedAtom(Pos, module.second)));
- }
- for (const auto& moduleAlias : ctx.ImportModuleAliases) {
- Add(Y("import", moduleAlias.second, BuildQuotedAtom(Pos, moduleAlias.first)));
- }
- for (const auto& x : ctx.SimpleUdfs) {
- Add(Y("let", x.second, Y("Udf", BuildQuotedAtom(Pos, x.first))));
- }
- if (!ctx.CompactNamedExprs) {
- for (auto& nodes: Scoped->NamedNodes) {
- if (src || ctx.Exports.contains(nodes.first)) {
- auto& item = nodes.second.front();
- if (!item->Node->Init(ctx, src)) {
- hasError = true;
- continue;
- }
- // Some constants may be used directly by YQL code and need to be translated without reference from SQL AST
- if (item->Node->IsConstant() || ctx.Exports.contains(nodes.first)) {
- Add(Y("let", BuildAtom(item->Node->GetPos(), nodes.first), item->Node));
- }
- }
- }
- }
- if (ctx.Settings.Mode != NSQLTranslation::ESqlMode::LIBRARY) {
- auto configSource = Y("DataSource", BuildQuotedAtom(Pos, TString(ConfigProviderName)));
- auto resultSink = Y("DataSink", BuildQuotedAtom(Pos, TString(ResultProviderName)));
- for (const auto& warningPragma : ctx.WarningPolicy.GetRules()) {
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
- BuildQuotedAtom(Pos, "Warning"), BuildQuotedAtom(Pos, warningPragma.GetPattern()),
- BuildQuotedAtom(Pos, to_lower(ToString(warningPragma.GetAction()))))));
- }
- if (ctx.ResultSizeLimit > 0) {
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", resultSink,
- BuildQuotedAtom(Pos, "SizeLimit"), BuildQuotedAtom(Pos, ToString(ctx.ResultSizeLimit)))));
- }
- if (!ctx.PragmaPullUpFlatMapOverJoin) {
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
- BuildQuotedAtom(Pos, "DisablePullUpFlatMapOverJoin"))));
- }
- if (ctx.FilterPushdownOverJoinOptionalSide) {
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
- BuildQuotedAtom(Pos, "FilterPushdownOverJoinOptionalSide"))));
- }
- if (!ctx.RotateJoinTree) {
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
- BuildQuotedAtom(Pos, "RotateJoinTree"), BuildQuotedAtom(Pos, "false"))));
- }
- if (ctx.DiscoveryMode) {
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
- BuildQuotedAtom(Pos, "DiscoveryMode"))));
- }
- if (ctx.DqEngineEnable) {
- TString mode = "auto";
- if (ctx.PqReadByRtmrCluster && ctx.PqReadByRtmrCluster != "dq") {
- mode = "disable";
- } else if (ctx.DqEngineForce) {
- mode = "force";
- }
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
- BuildQuotedAtom(Pos, "DqEngine"), BuildQuotedAtom(Pos, mode))));
- }
- if (ctx.CostBasedOptimizer) {
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
- BuildQuotedAtom(Pos, "CostBasedOptimizer"), BuildQuotedAtom(Pos, ctx.CostBasedOptimizer))));
- }
- if (ctx.JsonQueryReturnsJsonDocument.Defined()) {
- TString pragmaName = "DisableJsonQueryReturnsJsonDocument";
- if (*ctx.JsonQueryReturnsJsonDocument) {
- pragmaName = "JsonQueryReturnsJsonDocument";
- }
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource, BuildQuotedAtom(Pos, pragmaName))));
- }
- if (ctx.OrderedColumns) {
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
- BuildQuotedAtom(Pos, "OrderedColumns"))));
- }
- if (ctx.PqReadByRtmrCluster) {
- auto pqSourceAll = Y("DataSource", BuildQuotedAtom(Pos, TString(PqProviderName)), BuildQuotedAtom(Pos, "$all"));
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", pqSourceAll,
- BuildQuotedAtom(Pos, "Attr"), BuildQuotedAtom(Pos, "PqReadByRtmrCluster_"), BuildQuotedAtom(Pos, ctx.PqReadByRtmrCluster))));
- auto rtmrSourceAll = Y("DataSource", BuildQuotedAtom(Pos, TString(RtmrProviderName)), BuildQuotedAtom(Pos, "$all"));
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", rtmrSourceAll,
- BuildQuotedAtom(Pos, "Attr"), BuildQuotedAtom(Pos, "PqReadByRtmrCluster_"), BuildQuotedAtom(Pos, ctx.PqReadByRtmrCluster))));
- if (ctx.PqReadByRtmrCluster != "dq") {
- // set any dynamic settings for particular RTMR cluster for CommitAll!
- auto rtmrSource = Y("DataSource", BuildQuotedAtom(Pos, TString(RtmrProviderName)), BuildQuotedAtom(Pos, ctx.PqReadByRtmrCluster));
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", rtmrSource,
- BuildQuotedAtom(Pos, "Attr"), BuildQuotedAtom(Pos, "Dummy_"), BuildQuotedAtom(Pos, "1"))));
- }
- }
- if (ctx.YsonCastToString.Defined()) {
- const TString pragmaName = *ctx.YsonCastToString ? "YsonCastToString" : "DisableYsonCastToString";
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource, BuildQuotedAtom(Pos, pragmaName))));
- }
- if (ctx.UseBlocks) {
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource, BuildQuotedAtom(Pos, "UseBlocks"))));
- }
- if (ctx.BlockEngineEnable) {
- TString mode = ctx.BlockEngineForce ? "force" : "auto";
- currentWorlds->Add(Y("let", "world", Y(TString(ConfigureName), "world", configSource,
- BuildQuotedAtom(Pos, "BlockEngine"), BuildQuotedAtom(Pos, mode))));
- }
- }
- }
- for (auto& block: Blocks) {
- if (block->SubqueryAlias()) {
- continue;
- }
- if (!block->Init(ctx, nullptr)) {
- hasError = true;
- continue;
- }
- }
- for (const auto& x : Scoped->Local.ExprClusters) {
- auto& data = Scoped->Local.ExprClustersMap[x.Get()];
- auto& node = data.second;
- if (!node->Init(ctx, nullptr)) {
- hasError = true;
- continue;
- }
- Add(Y("let", data.first, node));
- }
- if (UseSeq) {
- flushCurrentWorlds(false, false);
- }
- for (auto& block: Blocks) {
- const auto subqueryAliasPtr = block->SubqueryAlias();
- if (subqueryAliasPtr) {
- if (block->UsedSubquery()) {
- if (UseSeq) {
- flushCurrentWorlds(true, false);
- }
- const auto& ref = block->GetLabel();
- YQL_ENSURE(!ref.empty());
- Add(block);
- currentWorlds->Add(Y("let", "world", Y("Nth", *subqueryAliasPtr, Q("0"))));
- Add(Y("let", ref, Y("Nth", *subqueryAliasPtr, Q("1"))));
- }
- } else {
- const auto& ref = block->GetLabel();
- if (ref) {
- Add(Y("let", ref, block));
- } else {
- currentWorlds->Add(Y("let", "world", block));
- if (UseSeq) {
- flushCurrentWorlds(false, false);
- }
- }
- }
- }
- if (UseSeq) {
- flushCurrentWorlds(false, true);
- }
- if (TopLevel) {
- if (ctx.UniversalAliases) {
- decltype(Nodes) preparedNodes;
- preparedNodes.swap(Nodes);
- for (const auto& [name, node] : ctx.UniversalAliases) {
- Add(Y("let", name, node));
- }
- Nodes.insert(Nodes.end(), preparedNodes.begin(), preparedNodes.end());
- }
- decltype(Nodes) imports;
- for (const auto& [alias, path]: ctx.RequiredModules) {
- imports.push_back(Y("import", alias, BuildQuotedAtom(Pos, path)));
- }
- Nodes.insert(Nodes.begin(), std::make_move_iterator(imports.begin()), std::make_move_iterator(imports.end()));
- for (const auto& symbol: ctx.Exports) {
- if (ctx.CompactNamedExprs) {
- auto node = Scoped->LookupNode(symbol);
- YQL_ENSURE(node);
- if (!node->Init(ctx, src)) {
- hasError = true;
- continue;
- }
- Add(Y("let", BuildAtom(node->GetPos(), symbol), node));
- }
- Add(Y("export", symbol));
- }
- }
- if (!TopLevel || ctx.Settings.Mode != NSQLTranslation::ESqlMode::LIBRARY) {
- Add(Y("return", "world"));
- }
- return !hasError;
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- TVector<TNodePtr> Blocks;
- const bool TopLevel;
- TScopedStatePtr Scoped;
- const bool UseSeq;
- };
- TNodePtr BuildQuery(TPosition pos, const TVector<TNodePtr>& blocks, bool topLevel, TScopedStatePtr scoped, bool useSeq) {
- return new TYqlProgramNode(pos, blocks, topLevel, scoped, useSeq);
- }
- class TPragmaNode final: public INode {
- public:
- TPragmaNode(TPosition pos, const TString& prefix, const TString& name, const TVector<TDeferredAtom>& values, bool valueDefault)
- : INode(pos)
- , Prefix(prefix)
- , Name(name)
- , Values(values)
- , ValueDefault(valueDefault)
- {
- FakeSource = BuildFakeSource(pos);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(src);
- TString serviceName;
- TString cluster;
- if (std::find(Providers.cbegin(), Providers.cend(), Prefix) != Providers.cend()) {
- cluster = "$all";
- serviceName = Prefix;
- } else {
- serviceName = *ctx.GetClusterProvider(Prefix, cluster);
- }
- auto datasource = Y("DataSource", BuildQuotedAtom(Pos, serviceName));
- if (Prefix != ConfigProviderName) {
- datasource = L(datasource, BuildQuotedAtom(Pos, cluster));
- }
- Node = Y();
- Node = L(Node, AstNode(TString(ConfigureName)));
- Node = L(Node, AstNode(TString(TStringBuf("world"))));
- Node = L(Node, datasource);
- if (Name == TStringBuf("flags")) {
- for (ui32 i = 0; i < Values.size(); ++i) {
- Node = L(Node, Values[i].Build());
- }
- }
- else if (Name == TStringBuf("AddFileByUrl") || Name == TStringBuf("SetFileOption") || Name == TStringBuf("AddFolderByUrl") || Name == TStringBuf("ImportUdfs") || Name == TStringBuf("SetPackageVersion")) {
- Node = L(Node, BuildQuotedAtom(Pos, Name));
- for (ui32 i = 0; i < Values.size(); ++i) {
- Node = L(Node, Values[i].Build());
- }
- }
- else if (Name == TStringBuf("auth")) {
- Node = L(Node, BuildQuotedAtom(Pos, "Auth"));
- Node = L(Node, Values.empty() ? BuildQuotedAtom(Pos, TString()) : Values.front().Build());
- }
- else {
- Node = L(Node, BuildQuotedAtom(Pos, "Attr"));
- Node = L(Node, BuildQuotedAtom(Pos, Name));
- if (!ValueDefault) {
- Node = L(Node, Values.empty() ? BuildQuotedAtom(Pos, TString()) : Values.front().Build());
- }
- }
- if (!Node->Init(ctx, FakeSource.Get())) {
- return false;
- }
- return true;
- }
- TAstNode* Translate(TContext& ctx) const final {
- return Node->Translate(ctx);
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- TString Prefix;
- TString Name;
- TVector<TDeferredAtom> Values;
- bool ValueDefault;
- TNodePtr Node;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildPragma(TPosition pos, const TString& prefix, const TString& name, const TVector<TDeferredAtom>& values, bool valueDefault) {
- return new TPragmaNode(pos, prefix, name, values, valueDefault);
- }
- class TSqlLambda final: public TAstListNode {
- public:
- TSqlLambda(TPosition pos, TVector<TString>&& args, TVector<TNodePtr>&& exprSeq)
- : TAstListNode(pos)
- , Args(args)
- , ExprSeq(exprSeq)
- {
- FakeSource = BuildFakeSource(pos);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(src);
- for (auto& exprPtr: ExprSeq) {
- if (!exprPtr->Init(ctx, FakeSource.Get())) {
- return {};
- }
- }
- YQL_ENSURE(!ExprSeq.empty());
- auto body = Y();
- auto end = ExprSeq.end() - 1;
- for (auto iter = ExprSeq.begin(); iter != end; ++iter) {
- auto exprPtr = *iter;
- const auto& label = exprPtr->GetLabel();
- YQL_ENSURE(label);
- body = L(body, Y("let", label, exprPtr));
- }
- body = Y("block", Q(L(body, Y("return", *end))));
- auto args = Y();
- for (const auto& arg: Args) {
- args = L(args, BuildAtom(GetPos(), arg));
- }
- Add("lambda", Q(args), body);
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return new TSqlLambda(Pos, TVector<TString>(Args), CloneContainer(ExprSeq));
- }
- void DoUpdateState() const override {
- State.Set(ENodeState::Const);
- }
- private:
- TVector<TString> Args;
- TVector<TNodePtr> ExprSeq;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildSqlLambda(TPosition pos, TVector<TString>&& args, TVector<TNodePtr>&& exprSeq) {
- return new TSqlLambda(pos, std::move(args), std::move(exprSeq));
- }
- class TWorldIf final : public TAstListNode {
- public:
- TWorldIf(TPosition pos, TNodePtr predicate, TNodePtr thenNode, TNodePtr elseNode, bool isEvaluate)
- : TAstListNode(pos)
- , Predicate(predicate)
- , ThenNode(thenNode)
- , ElseNode(elseNode)
- , IsEvaluate(isEvaluate)
- {
- FakeSource = BuildFakeSource(pos);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- if (!Predicate->Init(ctx, FakeSource.Get())) {
- return{};
- }
- Add(IsEvaluate ? "EvaluateIf!" : "If!");
- Add("world");
- auto coalesced = Y("Coalesce", Predicate, Y("Bool", Q("false")));
- Add(IsEvaluate ? Y("EvaluateExpr", Y("EnsureType", coalesced, Y("DataType", Q("Bool")))) : coalesced);
- if (!ThenNode->Init(ctx, FakeSource.Get())) {
- return{};
- }
- Add(ThenNode);
- if (ElseNode) {
- if (!ElseNode->Init(ctx, FakeSource.Get())) {
- return{};
- }
- Add(ElseNode);
- }
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return new TWorldIf(GetPos(), SafeClone(Predicate), SafeClone(ThenNode), SafeClone(ElseNode), IsEvaluate);
- }
- private:
- TNodePtr Predicate;
- TNodePtr ThenNode;
- TNodePtr ElseNode;
- bool IsEvaluate;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildWorldIfNode(TPosition pos, TNodePtr predicate, TNodePtr thenNode, TNodePtr elseNode, bool isEvaluate) {
- return new TWorldIf(pos, predicate, thenNode, elseNode, isEvaluate);
- }
- class TWorldFor final : public TAstListNode {
- public:
- TWorldFor(TPosition pos, TNodePtr list, TNodePtr bodyNode, TNodePtr elseNode, bool isEvaluate, bool isParallel)
- : TAstListNode(pos)
- , List(list)
- , BodyNode(bodyNode)
- , ElseNode(elseNode)
- , IsEvaluate(isEvaluate)
- , IsParallel(isParallel)
- {
- FakeSource = BuildFakeSource(pos);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- if (!List->Init(ctx, FakeSource.Get())) {
- return{};
- }
- Add(TStringBuilder() << (IsEvaluate ? "Evaluate": "") << (IsParallel ? "Parallel" : "") << "For!");
- Add("world");
- Add(IsEvaluate ? Y("EvaluateExpr", List) : List);
- if (!BodyNode->Init(ctx, FakeSource.Get())) {
- return{};
- }
- Add(BodyNode);
- if (ElseNode) {
- if (!ElseNode->Init(ctx, FakeSource.Get())) {
- return{};
- }
- Add(ElseNode);
- }
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return new TWorldFor(GetPos(), SafeClone(List), SafeClone(BodyNode), SafeClone(ElseNode), IsEvaluate, IsParallel);
- }
- private:
- TNodePtr List;
- TNodePtr BodyNode;
- TNodePtr ElseNode;
- bool IsEvaluate;
- bool IsParallel;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildWorldForNode(TPosition pos, TNodePtr list, TNodePtr bodyNode, TNodePtr elseNode, bool isEvaluate, bool isParallel) {
- return new TWorldFor(pos, list, bodyNode, elseNode, isEvaluate, isParallel);
- }
- class TAnalyzeNode final: public TAstListNode {
- public:
- TAnalyzeNode(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TAnalyzeParams& params, TScopedStatePtr scoped)
- : TAstListNode(pos)
- , Service(service)
- , Cluster(cluster)
- , Params(params)
- , Scoped(scoped)
- {
- FakeSource = BuildFakeSource(pos);
- scoped->UseCluster(Service, Cluster);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- Y_UNUSED(src);
- auto keys = Params.Table->Keys->GetTableKeys()->BuildKeys(ctx, ITableKeys::EBuildKeysMode::DROP);
- if (!keys || !keys->Init(ctx, FakeSource.Get())) {
- return false;
- }
- auto opts = Y();
- auto columns = Y();
- for (const auto& column: Params.Columns) {
- columns->Add(Q(column));
- }
- opts->Add(Q(Y(Q("columns"), Q(columns))));
- opts->Add(Q(Y(Q("mode"), Q("analyze"))));
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, Service), Scoped->WrapCluster(Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, FakeSource.Get());
- }
- TPtr DoClone() const final {
- return {};
- }
- private:
- TString Service;
- TDeferredAtom Cluster;
- TAnalyzeParams Params;
- TScopedStatePtr Scoped;
- TSourcePtr FakeSource;
- };
- TNodePtr BuildAnalyze(TPosition pos, const TString& service, const TDeferredAtom& cluster, const TAnalyzeParams& params, TScopedStatePtr scoped) {
- return new TAnalyzeNode(pos, service, cluster, params, scoped);
- }
- class TBaseBackupCollectionNode
- : public TAstListNode
- , public TObjectOperatorContext
- {
- using TBase = TAstListNode;
- public:
- TBaseBackupCollectionNode(
- TPosition pos,
- const TString& prefix,
- const TString& objectId,
- const TObjectOperatorContext& context)
- : TBase(pos)
- , TObjectOperatorContext(context)
- , Prefix(prefix)
- , Id(objectId)
- {}
- bool DoInit(TContext& ctx, ISource* src) final {
- auto keys = Y("Key");
- keys = L(keys, Q(Y(Q("backupCollection"), Y("String", BuildQuotedAtom(Pos, Id)), Y("String", BuildQuotedAtom(Pos, Prefix)))));
- auto options = this->FillOptions(ctx, Y());
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(options))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, src);
- }
- virtual INode::TPtr FillOptions(TContext& ctx, INode::TPtr options) const = 0;
- protected:
- TString Prefix;
- TString Id;
- };
- class TCreateBackupCollectionNode
- : public TBaseBackupCollectionNode
- {
- using TBase = TBaseBackupCollectionNode;
- public:
- TCreateBackupCollectionNode(
- TPosition pos,
- const TString& prefix,
- const TString& objectId,
- const TCreateBackupCollectionParameters& params,
- const TObjectOperatorContext& context)
- : TBase(pos, prefix, objectId, context)
- , Params(params)
- {}
- virtual INode::TPtr FillOptions(TContext& ctx, INode::TPtr options) const final {
- options->Add(Q(Y(Q("mode"), Q("create"))));
- auto settings = Y();
- for (auto& [key, value] : Params.Settings) {
- settings->Add(Q(Y(BuildQuotedAtom(Pos, key), Y("String", value.Build()))));
- }
- options->Add(Q(Y(Q("settings"), Q(settings))));
- auto entries = Y();
- if (Params.Database) {
- entries->Add(Q(Y(Q(Y(Q("type"), Q("database"))))));
- }
- for (auto& table : Params.Tables) {
- auto path = ctx.GetPrefixedPath(ServiceId, Cluster, table);
- entries->Add(Q(Y(Q(Y(Q("type"), Q("table"))), Q(Y(Q("path"), path)))));
- }
- options->Add(Q(Y(Q("entries"), Q(entries))));
- return options;
- }
- TPtr DoClone() const final {
- return new TCreateBackupCollectionNode(GetPos(), Prefix, Id, Params, *this);
- }
- private:
- TCreateBackupCollectionParameters Params;
- };
- class TAlterBackupCollectionNode
- : public TBaseBackupCollectionNode
- {
- using TBase = TBaseBackupCollectionNode;
- public:
- TAlterBackupCollectionNode(
- TPosition pos,
- const TString& prefix,
- const TString& objectId,
- const TAlterBackupCollectionParameters& params,
- const TObjectOperatorContext& context)
- : TBase(pos, prefix, objectId, context)
- , Params(params)
- {}
- virtual INode::TPtr FillOptions(TContext& ctx, INode::TPtr options) const final {
- options->Add(Q(Y(Q("mode"), Q("alter"))));
- auto settings = Y();
- for (auto& [key, value] : Params.Settings) {
- settings->Add(Q(Y(BuildQuotedAtom(Pos, key), Y("String", value.Build()))));
- }
- options->Add(Q(Y(Q("settings"), Q(settings))));
- auto resetSettings = Y();
- for (auto& key : Params.SettingsToReset) {
- resetSettings->Add(BuildQuotedAtom(Pos, key));
- }
- options->Add(Q(Y(Q("resetSettings"), Q(resetSettings))));
- auto entries = Y();
- if (Params.Database != TAlterBackupCollectionParameters::EDatabase::Unchanged) {
- entries->Add(Q(Y(Q(Y(Q("type"), Q("database"))), Q(Y(Q("action"), Q(Params.Database == TAlterBackupCollectionParameters::EDatabase::Add ? "add" : "drop"))))));
- }
- for (auto& table : Params.TablesToAdd) {
- auto path = ctx.GetPrefixedPath(ServiceId, Cluster, table);
- entries->Add(Q(Y(Q(Y(Q("type"), Q("table"))), Q(Y(Q("path"), path)), Q(Y(Q("action"), Q("add"))))));
- }
- for (auto& table : Params.TablesToDrop) {
- auto path = ctx.GetPrefixedPath(ServiceId, Cluster, table);
- entries->Add(Q(Y(Q(Y(Q("type"), Q("table"))), Q(Y(Q("path"), path)), Q(Y(Q("action"), Q("drop"))))));
- }
- options->Add(Q(Y(Q("alterEntries"), Q(entries))));
- return options;
- }
- TPtr DoClone() const final {
- return new TAlterBackupCollectionNode(GetPos(), Prefix, Id, Params, *this);
- }
- private:
- TAlterBackupCollectionParameters Params;
- };
- class TDropBackupCollectionNode
- : public TBaseBackupCollectionNode
- {
- using TBase = TBaseBackupCollectionNode;
- public:
- TDropBackupCollectionNode(
- TPosition pos,
- const TString& prefix,
- const TString& objectId,
- const TDropBackupCollectionParameters&,
- const TObjectOperatorContext& context)
- : TBase(pos, prefix, objectId, context)
- {}
- virtual INode::TPtr FillOptions(TContext&, INode::TPtr options) const final {
- options->Add(Q(Y(Q("mode"), Q("drop"))));
- return options;
- }
- TPtr DoClone() const final {
- TDropBackupCollectionParameters params;
- return new TDropBackupCollectionNode(GetPos(), Prefix, Id, params, *this);
- }
- };
- TNodePtr BuildCreateBackupCollection(
- TPosition pos,
- const TString& prefix,
- const TString& id,
- const TCreateBackupCollectionParameters& params,
- const TObjectOperatorContext& context)
- {
- return new TCreateBackupCollectionNode(pos, prefix, id, params, context);
- }
- TNodePtr BuildAlterBackupCollection(
- TPosition pos,
- const TString& prefix,
- const TString& id,
- const TAlterBackupCollectionParameters& params,
- const TObjectOperatorContext& context)
- {
- return new TAlterBackupCollectionNode(pos, prefix, id, params, context);
- }
- TNodePtr BuildDropBackupCollection(
- TPosition pos,
- const TString& prefix,
- const TString& id,
- const TDropBackupCollectionParameters& params,
- const TObjectOperatorContext& context)
- {
- return new TDropBackupCollectionNode(pos, prefix, id, params, context);
- }
- class TBackupNode final
- : public TAstListNode
- , public TObjectOperatorContext
- {
- using TBase = TAstListNode;
- public:
- TBackupNode(
- TPosition pos,
- const TString& prefix,
- const TString& id,
- const TBackupParameters& params,
- const TObjectOperatorContext& context)
- : TBase(pos)
- , TObjectOperatorContext(context)
- , Prefix(prefix)
- , Id(id)
- , Params(params)
- {
- Y_UNUSED(Params);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- auto keys = Y("Key");
- keys = L(keys, Q(Y(Q("backup"), Y("String", BuildQuotedAtom(Pos, Id)), Y("String", BuildQuotedAtom(Pos, Prefix)))));
- auto opts = Y();
- if (Params.Incremental) {
- opts->Add(Q(Y(Q("mode"), Q("backupIncremental"))));
- } else {
- opts->Add(Q(Y(Q("mode"), Q("backup"))));
- }
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return new TBackupNode(GetPos(), Prefix, Id, Params, *this);
- }
- private:
- TString Prefix;
- TString Id;
- TBackupParameters Params;
- };
- TNodePtr BuildBackup(
- TPosition pos,
- const TString& prefix,
- const TString& id,
- const TBackupParameters& params,
- const TObjectOperatorContext& context)
- {
- return new TBackupNode(pos, prefix, id, params, context);
- }
- class TRestoreNode final
- : public TAstListNode
- , public TObjectOperatorContext
- {
- using TBase = TAstListNode;
- public:
- TRestoreNode(
- TPosition pos,
- const TString& prefix,
- const TString& id,
- const TRestoreParameters& params,
- const TObjectOperatorContext& context)
- : TBase(pos)
- , TObjectOperatorContext(context)
- , Prefix(prefix)
- , Id(id)
- , Params(params)
- {
- Y_UNUSED(Params);
- }
- bool DoInit(TContext& ctx, ISource* src) override {
- auto keys = Y("Key");
- keys = L(keys, Q(Y(Q("restore"), Y("String", BuildQuotedAtom(Pos, Id)), Y("String", BuildQuotedAtom(Pos, Prefix)))));
- auto opts = Y();
- opts->Add(Q(Y(Q("mode"), Q("restore"))));
- if (Params.At) {
- opts->Add(Q(Y(Q("at"), BuildQuotedAtom(Pos, Params.At))));
- }
- Add("block", Q(Y(
- Y("let", "sink", Y("DataSink", BuildQuotedAtom(Pos, ServiceId), Scoped->WrapCluster(Cluster, ctx))),
- Y("let", "world", Y(TString(WriteName), "world", "sink", keys, Y("Void"), Q(opts))),
- Y("return", ctx.PragmaAutoCommit ? Y(TString(CommitName), "world", "sink") : AstNode("world"))
- )));
- return TAstListNode::DoInit(ctx, src);
- }
- TPtr DoClone() const final {
- return new TRestoreNode(GetPos(), Prefix, Id, Params, *this);
- }
- private:
- TString Prefix;
- TString Id;
- TRestoreParameters Params;
- };
- TNodePtr BuildRestore(
- TPosition pos,
- const TString& prefix,
- const TString& id,
- const TRestoreParameters& params,
- const TObjectOperatorContext& context)
- {
- return new TRestoreNode(pos, prefix, id, params, context);
- }
- } // namespace NSQLTranslationV1
|