sql.cpp 215 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358
  1. #include "sql.h"
  2. #include <yql/essentials/sql/v0/lexer/lexer.h>
  3. #include "context.h"
  4. #include "node.h"
  5. #include <yql/essentials/ast/yql_expr.h>
  6. #include <yql/essentials/parser/proto_ast/collect_issues/collect_issues.h>
  7. #include <yql/essentials/parser/proto_ast/gen/v0/SQLLexer.h>
  8. #include <yql/essentials/parser/proto_ast/gen/v0/SQLParser.h>
  9. #include <yql/essentials/parser/proto_ast/gen/v0_proto_split/SQLParser.pb.main.h>
  10. #include <yql/essentials/minikql/mkql_program_builder.h>
  11. #include <yql/essentials/minikql/mkql_type_ops.h>
  12. #include <yql/essentials/providers/common/provider/yql_provider_names.h>
  13. #include <yql/essentials/sql/settings/translation_settings.h>
  14. #include <library/cpp/charset/ci_string.h>
  15. #include <google/protobuf/repeated_field.h>
  16. #include <util/generic/array_ref.h>
  17. #include <util/generic/set.h>
  18. #include <util/string/ascii.h>
  19. #include <util/string/cast.h>
  20. #include <util/string/reverse.h>
  21. #include <util/string/split.h>
  22. #include <util/string/hex.h>
  23. #include <util/string/join.h>
  24. #if defined(_tsan_enabled_)
  25. #include <util/system/mutex.h>
  26. #endif
  27. using namespace NYql;
  28. namespace NSQLTranslationV0 {
  29. using NALP::SQLLexerTokens;
  30. #if defined(_tsan_enabled_)
  31. TMutex SanitizerSQLTranslationMutex;
  32. #endif
  33. using namespace NSQLGenerated;
  34. static TPosition GetPos(const TToken& token) {
  35. return TPosition(token.GetColumn(), token.GetLine());
  36. }
  37. template <typename TToken>
  38. TIdentifier GetIdentifier(TTranslation& ctx, const TToken& node) {
  39. auto token = node.GetToken1();
  40. return TIdentifier(TPosition(token.GetColumn(), token.GetLine()), ctx.Identifier(token));
  41. }
  42. inline TIdentifier GetKeywordId(TTranslation& ctx, const TRule_keyword_restricted& node) {
  43. switch (node.Alt_case()) {
  44. case TRule_keyword_restricted::kAltKeywordRestricted1:
  45. return GetIdentifier(ctx, node.GetAlt_keyword_restricted1().GetRule_keyword_compat1());
  46. case TRule_keyword_restricted::kAltKeywordRestricted2:
  47. return GetIdentifier(ctx, node.GetAlt_keyword_restricted2().GetRule_keyword_expr_uncompat1());
  48. case TRule_keyword_restricted::kAltKeywordRestricted3:
  49. return GetIdentifier(ctx, node.GetAlt_keyword_restricted3().GetRule_keyword_select_uncompat1());
  50. case TRule_keyword_restricted::kAltKeywordRestricted4:
  51. return GetIdentifier(ctx, node.GetAlt_keyword_restricted4().GetRule_keyword_in_uncompat1());
  52. default:
  53. Y_ABORT("You should change implementation according grammar changes");
  54. }
  55. }
  56. inline TIdentifier GetKeywordId(TTranslation& ctx, const TRule_keyword& node) {
  57. switch (node.Alt_case()) {
  58. case TRule_keyword::kAltKeyword1:
  59. return GetKeywordId(ctx, node.GetAlt_keyword1().GetRule_keyword_restricted1());
  60. case TRule_keyword::kAltKeyword2:
  61. return GetIdentifier(ctx, node.GetAlt_keyword2().GetRule_keyword_alter_uncompat1());
  62. case TRule_keyword::kAltKeyword3:
  63. return GetIdentifier(ctx, node.GetAlt_keyword3().GetRule_keyword_table_uncompat1());
  64. default:
  65. Y_ABORT("You should change implementation according grammar changes");
  66. }
  67. }
  68. inline TString GetKeyword(TTranslation& ctx, const TRule_keyword& node) {
  69. return GetKeywordId(ctx, node).Name;
  70. }
  71. inline TString GetKeyword(TTranslation& ctx, const TRule_keyword_restricted& node) {
  72. return GetKeywordId(ctx, node).Name;
  73. }
  74. static TString Id(const TRule_id& node, TTranslation& ctx) {
  75. // id: IDENTIFIER | keyword;
  76. switch (node.Alt_case()) {
  77. case TRule_id::kAltId1:
  78. return ctx.Identifier(node.GetAlt_id1().GetToken1());
  79. case TRule_id::kAltId2:
  80. return GetKeyword(ctx, node.GetAlt_id2().GetRule_keyword1());
  81. default:
  82. Y_ABORT("You should change implementation according grammar changes");
  83. }
  84. }
  85. static TString Id(const TRule_id_schema& node, TTranslation& ctx) {
  86. switch (node.Alt_case()) {
  87. case TRule_id_schema::kAltIdSchema1:
  88. return ctx.Identifier(node.GetAlt_id_schema1().GetToken1());
  89. case TRule_id_schema::kAltIdSchema2:
  90. return GetKeyword(ctx, node.GetAlt_id_schema2().GetRule_keyword_restricted1());
  91. default:
  92. Y_ABORT("You should change implementation according grammar changes");
  93. }
  94. }
  95. static std::pair<bool, TString> Id(const TRule_id_or_at& node, TTranslation& ctx) {
  96. bool hasAt = node.HasBlock1();
  97. return std::make_pair(hasAt, Id(node.GetRule_id2(), ctx) );
  98. }
  99. static TString Id(const TRule_id_table& node, TTranslation& ctx) {
  100. // id_table: IDENTIFIER | keyword_restricted;
  101. switch (node.Alt_case()) {
  102. case TRule_id_table::kAltIdTable1:
  103. return ctx.Identifier(node.GetAlt_id_table1().GetToken1());
  104. case TRule_id_table::kAltIdTable2:
  105. return GetKeyword(ctx, node.GetAlt_id_table2().GetRule_keyword_restricted1());
  106. default:
  107. Y_ABORT("You should change implementation according grammar changes");
  108. }
  109. }
  110. static std::pair<bool, TString> Id(const TRule_id_table_or_at& node, TTranslation& ctx) {
  111. // id_table_or_at: AT? id_table;
  112. bool hasAt = node.HasBlock1();
  113. return std::make_pair(hasAt, Id(node.GetRule_id_table2(), ctx));
  114. }
  115. static TString Id(const TRule_id_expr& node, TTranslation& ctx) {
  116. switch (node.Alt_case()) {
  117. case TRule_id_expr::kAltIdExpr1:
  118. return ctx.Identifier(node.GetAlt_id_expr1().GetToken1());
  119. case TRule_id_expr::kAltIdExpr2:
  120. return ctx.Token(node.GetAlt_id_expr2().GetRule_keyword_compat1().GetToken1());
  121. case TRule_id_expr::kAltIdExpr3:
  122. return ctx.Token(node.GetAlt_id_expr3().GetRule_keyword_alter_uncompat1().GetToken1());
  123. case TRule_id_expr::kAltIdExpr4:
  124. return ctx.Token(node.GetAlt_id_expr4().GetRule_keyword_in_uncompat1().GetToken1());
  125. default:
  126. Y_ABORT("You should change implementation according grammar changes");
  127. }
  128. }
  129. static TString Id(const TRule_in_id_expr& node, TTranslation& ctx) {
  130. switch (node.Alt_case()) {
  131. case TRule_in_id_expr::kAltInIdExpr1:
  132. return ctx.Identifier(node.GetAlt_in_id_expr1().GetToken1());
  133. case TRule_in_id_expr::kAltInIdExpr2:
  134. return ctx.Token(node.GetAlt_in_id_expr2().GetRule_keyword_compat1().GetToken1());
  135. case TRule_in_id_expr::kAltInIdExpr3:
  136. return ctx.Token(node.GetAlt_in_id_expr3().GetRule_keyword_alter_uncompat1().GetToken1());
  137. default:
  138. Y_ABORT("You should change implementation according grammar changes");
  139. }
  140. }
  141. static TIdentifier IdEx(const TRule_id& node, TTranslation& ctx) {
  142. switch (node.Alt_case()) {
  143. case TRule_id::kAltId1:
  144. return GetIdentifier(ctx, node.GetAlt_id1());
  145. case TRule_id::kAltId2:
  146. return GetKeywordId(ctx, node.GetAlt_id2().GetRule_keyword1());
  147. default:
  148. Y_ABORT("You should change implementation according grammar changes");
  149. }
  150. }
  151. static TString IdOrString(const TRule_id_or_string& node, TTranslation& ctx, bool rawString = false) {
  152. switch (node.Alt_case()) {
  153. case TRule_id_or_string::kAltIdOrString1: {
  154. return ctx.Identifier(node.GetAlt_id_or_string1().GetToken1());
  155. }
  156. case TRule_id_or_string::kAltIdOrString2: {
  157. auto raw = ctx.Token(node.GetAlt_id_or_string2().GetToken1());
  158. return rawString ? raw : StringContent(ctx.Context(), raw);
  159. }
  160. case TRule_id_or_string::kAltIdOrString3:
  161. return GetKeyword(ctx, node.GetAlt_id_or_string3().GetRule_keyword1());
  162. default:
  163. break;
  164. }
  165. Y_ABORT("You should change implementation according grammar changes");
  166. }
  167. static TString IdOrStringAsCluster(const TRule_id_or_string& node, TTranslation& ctx) {
  168. TString cluster = IdOrString(node, ctx);
  169. TString normalizedClusterName;
  170. if (!ctx.Context().GetClusterProvider(cluster, normalizedClusterName)) {
  171. ctx.Error() << "Unknown cluster: " << cluster;
  172. return {};
  173. }
  174. return normalizedClusterName;
  175. }
  176. static TString OptIdPrefixAsStr(const TRule_opt_id_prefix& node, TTranslation& ctx, const TString& defaultStr = {}) {
  177. if (!node.HasBlock1()) {
  178. return defaultStr;
  179. }
  180. return IdOrString(node.GetBlock1().GetRule_id_or_string1(), ctx);
  181. }
  182. static TString OptIdPrefixAsClusterStr(const TRule_opt_id_prefix& node, TTranslation& ctx, const TString& defaultStr = {}) {
  183. if (!node.HasBlock1()) {
  184. return defaultStr;
  185. }
  186. return IdOrStringAsCluster(node.GetBlock1().GetRule_id_or_string1(), ctx);
  187. }
  188. static void PureColumnListStr(const TRule_pure_column_list& node, TTranslation& ctx, TVector<TString>& outList) {
  189. outList.push_back(IdOrString(node.GetRule_id_or_string2(), ctx));
  190. for (auto& block: node.GetBlock3()) {
  191. outList.push_back(IdOrString(block.GetRule_id_or_string2(), ctx));
  192. }
  193. }
  194. static TString NamedNodeImpl(const TRule_bind_parameter& node, TTranslation& ctx) {
  195. // bind_parameter: DOLLAR id;
  196. auto id = Id(node.GetRule_id2(), ctx);
  197. return ctx.Token(node.GetToken1()) + id;
  198. }
  199. static TDeferredAtom PureColumnOrNamed(const TRule_pure_column_or_named& node, TTranslation& ctx) {
  200. switch (node.Alt_case()) {
  201. case TRule_pure_column_or_named::kAltPureColumnOrNamed1: {
  202. auto named = NamedNodeImpl(node.GetAlt_pure_column_or_named1().GetRule_bind_parameter1(), ctx);
  203. auto namedNode = ctx.GetNamedNode(named);
  204. if (!namedNode) {
  205. return {};
  206. }
  207. return TDeferredAtom(namedNode, ctx.Context());
  208. }
  209. case TRule_pure_column_or_named::kAltPureColumnOrNamed2:
  210. return TDeferredAtom(ctx.Context().Pos(), IdOrString(node.GetAlt_pure_column_or_named2().GetRule_id_or_string1(), ctx));
  211. default:
  212. Y_ABORT("You should change implementation according grammar changes");
  213. }
  214. }
  215. static bool PureColumnOrNamedListStr(const TRule_pure_column_or_named_list& node, TTranslation& ctx, TVector<TDeferredAtom>& outList) {
  216. outList.push_back(PureColumnOrNamed(node.GetRule_pure_column_or_named2(), ctx));
  217. if (outList.back().Empty()) {
  218. return false;
  219. }
  220. for (auto& block : node.GetBlock3()) {
  221. outList.push_back(PureColumnOrNamed(block.GetRule_pure_column_or_named2(), ctx));
  222. if (outList.back().Empty()) {
  223. return false;
  224. }
  225. }
  226. return true;
  227. }
  228. namespace {
  229. bool IsDistinctOptSet(const TRule_opt_set_quantifier& node) {
  230. return node.HasBlock1() && node.GetBlock1().GetToken1().GetId() == SQLLexerTokens::TOKEN_DISTINCT;
  231. }
  232. std::pair<TString, bool> FlexType(const TRule_flex_type& node, TTranslation& ctx) {
  233. switch (node.Alt_case()) {
  234. case TRule_flex_type::kAltFlexType1:
  235. return std::make_pair(StringContent(ctx.Context(), ctx.Token(node.GetAlt_flex_type1().GetToken1())), true);
  236. case TRule_flex_type::kAltFlexType2: {
  237. const auto& typeName = node.GetAlt_flex_type2().GetRule_type_name1();
  238. const TString& paramOne = typeName.HasBlock2() ? typeName.GetBlock2().GetRule_integer2().GetToken1().GetValue() : TString();
  239. const TString& paramTwo = !paramOne.empty() && typeName.GetBlock2().HasBlock3() ? typeName.GetBlock2().GetBlock3().GetRule_integer2().GetToken1().GetValue() : TString();
  240. TString stringType = Id(typeName.GetRule_id1(), ctx);
  241. if (!paramOne.empty() && !paramTwo.empty()) {
  242. TStringStream strm;
  243. strm << '(' << paramOne << ',' << paramTwo << ')';
  244. stringType += strm.Str();
  245. }
  246. return std::make_pair(stringType, false);
  247. }
  248. default:
  249. Y_ABORT("You should change implementation according to grammar changes");
  250. }
  251. }
  252. }
  253. static TColumnSchema ColumnSchemaImpl(const TRule_column_schema& node, TTranslation& ctx) {
  254. const bool nullable = !node.HasBlock3() || !node.GetBlock3().HasBlock1();
  255. const TString name(Id(node.GetRule_id_schema1(), ctx));
  256. const TPosition pos(ctx.Context().Pos());
  257. const auto& type = FlexType(node.GetRule_flex_type2(), ctx);
  258. return TColumnSchema(pos, name, type.first, nullable, type.second);
  259. }
  260. static bool CreateTableEntry(const TRule_create_table_entry& node, TTranslation& ctx,
  261. TVector<TColumnSchema>& columns, TVector<TIdentifier>& pkColumns,
  262. TVector<TIdentifier>& partitionByColumns, TVector<std::pair<TIdentifier, bool>>& orderByColumns)
  263. {
  264. switch (node.Alt_case()) {
  265. case TRule_create_table_entry::kAltCreateTableEntry1:
  266. columns.push_back(ColumnSchemaImpl(node.GetAlt_create_table_entry1().GetRule_column_schema1(), ctx));
  267. break;
  268. case TRule_create_table_entry::kAltCreateTableEntry2:
  269. {
  270. auto& constraint = node.GetAlt_create_table_entry2().GetRule_table_constraint1();
  271. switch (constraint.Alt_case()) {
  272. case TRule_table_constraint::kAltTableConstraint1: {
  273. auto& pkConstraint = constraint.GetAlt_table_constraint1();
  274. pkColumns.push_back(IdEx(pkConstraint.GetRule_id4(), ctx));
  275. for (auto& block : pkConstraint.GetBlock5()) {
  276. pkColumns.push_back(IdEx(block.GetRule_id2(), ctx));
  277. }
  278. break;
  279. }
  280. case TRule_table_constraint::kAltTableConstraint2: {
  281. auto& pbConstraint = constraint.GetAlt_table_constraint2();
  282. partitionByColumns.push_back(IdEx(pbConstraint.GetRule_id4(), ctx));
  283. for (auto& block : pbConstraint.GetBlock5()) {
  284. partitionByColumns.push_back(IdEx(block.GetRule_id2(), ctx));
  285. }
  286. break;
  287. }
  288. case TRule_table_constraint::kAltTableConstraint3: {
  289. auto& obConstraint = constraint.GetAlt_table_constraint3();
  290. auto extractDirection = [&ctx] (const TRule_column_order_by_specification& spec, bool& desc) {
  291. desc = false;
  292. if (!spec.HasBlock2()) {
  293. return true;
  294. }
  295. auto& token = spec.GetBlock2().GetToken1();
  296. switch (token.GetId()) {
  297. case SQLLexerTokens::TOKEN_ASC:
  298. return true;
  299. case SQLLexerTokens::TOKEN_DESC:
  300. desc = true;
  301. return true;
  302. default:
  303. ctx.Error() << "Unsupported direction token: " << token.GetId();
  304. return false;
  305. }
  306. };
  307. bool desc = false;
  308. auto& obSpec = obConstraint.GetRule_column_order_by_specification4();
  309. if (!extractDirection(obSpec, desc)) {
  310. return false;
  311. }
  312. orderByColumns.push_back(std::make_pair(IdEx(obSpec.GetRule_id1(), ctx), desc));
  313. for (auto& block : obConstraint.GetBlock5()) {
  314. auto& obSpec = block.GetRule_column_order_by_specification2();
  315. if (!extractDirection(obSpec, desc)) {
  316. return false;
  317. }
  318. orderByColumns.push_back(std::make_pair(IdEx(obSpec.GetRule_id1(), ctx), desc));
  319. }
  320. break;
  321. }
  322. default:
  323. ctx.AltNotImplemented("table_constraint", constraint);
  324. return false;
  325. }
  326. break;
  327. }
  328. default:
  329. ctx.AltNotImplemented("create_table_entry", node);
  330. return false;
  331. }
  332. return true;
  333. }
  334. static std::pair<TString, TString> TableKeyImpl(const std::pair<bool, TString>& nameWithAt, TString view, TTranslation& ctx) {
  335. if (nameWithAt.first) {
  336. view = "@";
  337. ctx.Context().IncrementMonCounter("sql_features", "AnonymousTable");
  338. }
  339. return std::make_pair(nameWithAt.second, view);
  340. }
  341. static std::pair<TString, TString> TableKeyImpl(const TRule_table_key& node, TTranslation& ctx) {
  342. auto nameWithAt(Id(node.GetRule_id_table_or_at1(), ctx));
  343. TString view;
  344. if (node.HasBlock2()) {
  345. view = IdOrString(node.GetBlock2().GetRule_id_or_string2(), ctx);
  346. ctx.Context().IncrementMonCounter("sql_features", "View");
  347. }
  348. return TableKeyImpl(nameWithAt, view, ctx);
  349. }
  350. static TVector<TString> TableHintsImpl(const TRule_table_hints& node, TTranslation& ctx) {
  351. TVector<TString> hints;
  352. auto& block = node.GetBlock2();
  353. switch (block.Alt_case()) {
  354. case TRule_table_hints::TBlock2::kAlt1: {
  355. hints.push_back(IdOrString(block.GetAlt1().GetRule_id_or_string1(), ctx));
  356. break;
  357. }
  358. case TRule_table_hints::TBlock2::kAlt2: {
  359. PureColumnListStr(block.GetAlt2().GetRule_pure_column_list1(), ctx, hints);
  360. break;
  361. }
  362. default:
  363. Y_ABORT("You should change implementation according grammar changes");
  364. }
  365. return hints;
  366. }
  367. /// \return optional prefix
  368. static TString ColumnNameAsStr(TTranslation& ctx, const TRule_column_name& node, TString& id) {
  369. id = IdOrString(node.GetRule_id_or_string2(), ctx);
  370. return OptIdPrefixAsStr(node.GetRule_opt_id_prefix1(), ctx);
  371. }
  372. static TString ColumnNameAsSingleStr(TTranslation& ctx, const TRule_column_name& node) {
  373. TString body;
  374. const TString prefix = ColumnNameAsStr(ctx, node, body);
  375. return prefix ? prefix + '.' + body : body;
  376. }
  377. static void FillTargetList(TTranslation& ctx, const TRule_set_target_list& node, TVector<TString>& targetList) {
  378. targetList.push_back(ColumnNameAsSingleStr(ctx, node.GetRule_set_target2().GetRule_column_name1()));
  379. for (auto& block: node.GetBlock3()) {
  380. targetList.push_back(ColumnNameAsSingleStr(ctx, block.GetRule_set_target2().GetRule_column_name1()));
  381. }
  382. }
  383. TVector<TString> GetContextHints(TContext& ctx) {
  384. TVector<TString> hints;
  385. if (ctx.PragmaInferSchema) {
  386. hints.push_back("infer_scheme"); // TODO use yt.InferSchema instead
  387. }
  388. if (ctx.PragmaDirectRead) {
  389. hints.push_back("direct_read");
  390. }
  391. return hints;
  392. }
  393. static TVector<TString> GetTableFuncHints(TStringBuf funcName) {
  394. TCiString func(funcName);
  395. if (func.StartsWith("range") || func.StartsWith("like") || func.StartsWith("regexp") || func.StartsWith("filter")
  396. || func.StartsWith("each")) {
  397. return TVector<TString>{"ignore_non_existing"};
  398. }
  399. return {};
  400. }
  401. static TTableRef SimpleTableRefImpl(const TRule_simple_table_ref& node, NSQLTranslation::ESqlMode mode, TTranslation& ctx) {
  402. TMaybe<TTableRef> tr;
  403. TString cluster;
  404. switch (node.GetBlock1().Alt_case()) {
  405. case TRule_simple_table_ref_TBlock1::AltCase::kAlt1: {
  406. if (node.GetBlock1().GetAlt1().GetBlock1().HasRule_opt_id_prefix1()) {
  407. cluster = OptIdPrefixAsClusterStr(node.GetBlock1().GetAlt1().GetBlock1().GetRule_opt_id_prefix1(), ctx, ctx.Context().CurrCluster);
  408. if (!cluster && ctx.Context().CurrCluster) {
  409. return TTableRef(ctx.Context().MakeName("table"), ctx.Context().CurrCluster, nullptr);
  410. }
  411. }
  412. tr.ConstructInPlace(ctx.Context().MakeName("table"), cluster.empty() ? ctx.Context().CurrCluster : cluster, nullptr);
  413. auto tableOrAt = Id(node.GetBlock1().GetAlt1().GetBlock1().GetRule_id_or_at2(), ctx);
  414. auto tableAndView = TableKeyImpl(tableOrAt, "", ctx);
  415. tr->Keys = BuildTableKey(ctx.Context().Pos(), tr->Cluster, TDeferredAtom(ctx.Context().Pos(), tableAndView.first), tableAndView.second);
  416. break;
  417. }
  418. case TRule_simple_table_ref_TBlock1::AltCase::kAlt2: {
  419. auto at = node.GetBlock1().GetAlt2().HasBlock1();
  420. auto named = ctx.GetNamedNode(NamedNodeImpl(node.GetBlock1().GetAlt2().GetRule_bind_parameter2(), ctx));
  421. if (!named) {
  422. return TTableRef(ctx.Context().MakeName("table"), ctx.Context().CurrCluster, nullptr);
  423. }
  424. TDeferredAtom table;
  425. if (!TryMakeClusterAndTableFromExpression(named, cluster, table, ctx.Context())) {
  426. ctx.Error() << "Cannot infer cluster and table name";
  427. return TTableRef(ctx.Context().MakeName("table"), ctx.Context().CurrCluster, nullptr);
  428. }
  429. tr.ConstructInPlace(ctx.Context().MakeName("table"), cluster.empty() ? ctx.Context().CurrCluster : cluster, nullptr);
  430. tr->Keys = BuildTableKey(ctx.Context().Pos(), tr->Cluster, table, at ? "@" : "");
  431. break;
  432. }
  433. default:
  434. Y_ABORT("You should change implementation according grammar changes");
  435. }
  436. if (mode == NSQLTranslation::ESqlMode::LIMITED_VIEW && !cluster.empty()) {
  437. ctx.Error() << "Cluster should not be used in limited view";
  438. return TTableRef(ctx.Context().MakeName("table"), ctx.Context().CurrCluster, nullptr);
  439. }
  440. if (cluster.empty()) {
  441. cluster = ctx.Context().CurrCluster;
  442. }
  443. TVector<TString> hints = GetContextHints(ctx.Context());
  444. if (node.HasBlock2()) {
  445. hints = TableHintsImpl(node.GetBlock2().GetRule_table_hints1(), ctx);
  446. }
  447. if (!hints.empty()) {
  448. tr->Options = BuildInputOptions(ctx.Context().Pos(), hints);
  449. }
  450. return *tr;
  451. }
  452. static bool ValidateForCounters(const TString& input) {
  453. for (auto c : input) {
  454. if (!(IsAlnum(c) || c == '_')) {
  455. return false;
  456. }
  457. }
  458. return true;
  459. }
  460. static bool IsColumnsOnly(const TVector<TSortSpecificationPtr>& container) {
  461. for (const auto& elem: container) {
  462. if (!elem->OrderExpr->GetColumnName()) {
  463. return false;
  464. }
  465. }
  466. return true;
  467. }
  468. class TSqlTranslation: public TTranslation {
  469. protected:
  470. TSqlTranslation(TContext& ctx, NSQLTranslation::ESqlMode mode)
  471. : TTranslation(ctx)
  472. , Mode(mode)
  473. {
  474. /// \todo remove NSQLTranslation::ESqlMode params
  475. YQL_ENSURE(ctx.Settings.Mode == mode);
  476. }
  477. protected:
  478. enum class EExpr {
  479. Regular,
  480. GroupBy,
  481. SqlLambdaParams,
  482. };
  483. TNodePtr NamedExpr(const TRule_named_expr& node, EExpr exprMode = EExpr::Regular);
  484. bool NamedExprList(const TRule_named_expr_list& node, TVector<TNodePtr>& exprs, EExpr exprMode = EExpr::Regular);
  485. bool BindList(const TRule_bind_parameter_list& node, TVector<TString>& bindNames);
  486. bool ModulePath(const TRule_module_path& node, TVector<TString>& path);
  487. bool NamedBindList(const TRule_named_bind_parameter_list& node, TVector<TNodePtr>& bindNames);
  488. TNodePtr NamedBindParam(const TRule_named_bind_parameter& node);
  489. TNodePtr NamedNode(const TRule_named_nodes_stmt& rule, TVector<TString>& names);
  490. bool ImportStatement(const TRule_import_stmt& stmt, TVector<TString>* namesPtr = nullptr);
  491. TNodePtr DoStatement(const TRule_do_stmt& stmt, bool makeLambda, const TVector<TString>& args = {});
  492. bool DefineActionOrSubqueryStatement(const TRule_define_action_or_subquery_stmt& stmt);
  493. TNodePtr EvaluateIfStatement(const TRule_evaluate_if_stmt& stmt);
  494. TNodePtr EvaluateForStatement(const TRule_evaluate_for_stmt& stmt);
  495. TMaybe<TTableArg> TableArgImpl(const TRule_table_arg& node);
  496. TTableRef TableRefImpl(const TRule_table_ref& node);
  497. TMaybe<TSourcePtr> AsTableImpl(const TRule_table_ref& node);
  498. NSQLTranslation::ESqlMode Mode;
  499. };
  500. class TSqlExpression: public TSqlTranslation {
  501. public:
  502. enum class ESmartParenthesis {
  503. Default,
  504. GroupBy,
  505. InStatement,
  506. SqlLambdaParams,
  507. };
  508. TSqlExpression(TContext& ctx, NSQLTranslation::ESqlMode mode)
  509. : TSqlTranslation(ctx, mode)
  510. {
  511. }
  512. TNodePtr Build(const TRule_expr& node) {
  513. // expr: or_subexpr (OR or_subexpr)*;
  514. auto getNode = [](const TRule_expr::TBlock2& b) -> const TRule_or_subexpr& { return b.GetRule_or_subexpr2(); };
  515. return BinOper("Or", node.GetRule_or_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end());
  516. }
  517. TNodePtr WrapExprShortcuts(const TNodePtr& node) {
  518. return node;
  519. //if (!ExprShortcuts || !node) {
  520. //return node;
  521. //}
  522. //TIntrusivePtr<TAstListNodeImpl> prepareNode = new TAstListNodeImpl(Ctx.Pos());
  523. //for (const auto& aliasPair: ExprShortcuts) {
  524. //prepareNode->Add(prepareNode->Y("let", aliasPair.first, aliasPair.second));
  525. //}
  526. //prepareNode->Add(prepareNode->Y("return", node));
  527. //return prepareNode->Y("block", prepareNode->Q(prepareNode));
  528. }
  529. void SetSmartParenthesisMode(ESmartParenthesis mode) {
  530. SmartParenthesisMode = mode;
  531. }
  532. TNodePtr ExprShortcut(const TString& baseName, const TNodePtr& node) {
  533. return BuildShortcutNode(node, baseName);
  534. //auto alias = Ctx.MakeName(baseName);
  535. //ExprShortcuts.emplace(alias, node);
  536. //return BuildAtom(node->GetPos(), alias, TNodeFlags::Default);
  537. }
  538. TNodePtr LiteralExpr(const TRule_literal_value& node);
  539. private:
  540. template<typename TWindowFunctionRule>
  541. TNodePtr WindowFunctionRule(const TWindowFunctionRule& rule);
  542. TNodePtr BindParameterRule(const TRule_bind_parameter& rule);
  543. TNodePtr LambdaRule(const TRule_lambda& rule);
  544. TNodePtr CastRule(const TRule_cast_expr& rule);
  545. TNodePtr BitCastRule(const TRule_bitcast_expr& rule);
  546. TNodePtr ExistsRule(const TRule_exists_expr& rule);
  547. TNodePtr CaseRule(const TRule_case_expr& rule);
  548. TNodePtr AtomExpr(const TRule_atom_expr& node);
  549. TNodePtr InAtomExpr(const TRule_in_atom_expr& node);
  550. template<typename TUnarySubExprRule>
  551. TNodePtr UnaryExpr(const TUnarySubExprRule& node);
  552. bool SqlLambdaParams(const TNodePtr& node, TVector<TString>& args);
  553. bool SqlLambdaExprBody(TContext& ctx, const TRule_lambda_body& node, TVector<TNodePtr>& exprSeq);
  554. TNodePtr KeyExpr(const TRule_key_expr& node) {
  555. TSqlExpression expr(Ctx, Mode);
  556. return expr.WrapExprShortcuts(expr.Build(node.GetRule_expr2()));
  557. }
  558. TNodePtr SubExpr(const TRule_con_subexpr& node);
  559. TNodePtr SubExpr(const TRule_xor_subexpr& node);
  560. TNodePtr SubExpr(const TRule_mul_subexpr& node) {
  561. // mul_subexpr: con_subexpr (DOUBLE_PIPE con_subexpr)*;
  562. auto getNode = [](const TRule_mul_subexpr::TBlock2& b) -> const TRule_con_subexpr& { return b.GetRule_con_subexpr2(); };
  563. return BinOper("Concat", node.GetRule_con_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end());
  564. }
  565. TNodePtr SubExpr(const TRule_add_subexpr& node) {
  566. // add_subexpr: mul_subexpr ((ASTERISK | SLASH | PERCENT) mul_subexpr)*;
  567. auto getNode = [](const TRule_add_subexpr::TBlock2& b) -> const TRule_mul_subexpr& { return b.GetRule_mul_subexpr2(); };
  568. return BinOpList(node.GetRule_mul_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end());
  569. }
  570. TNodePtr SubExpr(const TRule_bit_subexpr& node) {
  571. // bit_subexpr: add_subexpr ((PLUS | MINUS) add_subexpr)*;
  572. auto getNode = [](const TRule_bit_subexpr::TBlock2& b) -> const TRule_add_subexpr& { return b.GetRule_add_subexpr2(); };
  573. return BinOpList(node.GetRule_add_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end());
  574. }
  575. TNodePtr SubExpr(const TRule_neq_subexpr& node) {
  576. // neq_subexpr: bit_subexpr ((SHIFT_LEFT | SHIFT_RIGHT | ROT_LEFT | ROT_RIGHT | AMPERSAND | PIPE | CARET) bit_subexpr)* (DOUBLE_QUESTION neq_subexpr)?;
  577. auto getNode = [](const TRule_neq_subexpr::TBlock2& b) -> const TRule_bit_subexpr& { return b.GetRule_bit_subexpr2(); };
  578. auto result = BinOpList(node.GetRule_bit_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end());
  579. if (!result) {
  580. return nullptr;
  581. }
  582. if (node.HasBlock3()) {
  583. auto block = node.GetBlock3();
  584. TSqlExpression altExpr(Ctx, Mode);
  585. auto altResult = altExpr.WrapExprShortcuts(SubExpr(block.GetRule_neq_subexpr2()));
  586. if (!altResult) {
  587. return nullptr;
  588. }
  589. const TVector<TNodePtr> args({result, altResult});
  590. Token(block.GetToken1());
  591. result = BuildBuiltinFunc(Ctx, Ctx.Pos(), "Coalesce", args);
  592. }
  593. return result;
  594. }
  595. TNodePtr SubExpr(const TRule_eq_subexpr& node) {
  596. // eq_subexpr: neq_subexpr ((LESS | LESS_OR_EQ | GREATER | GREATER_OR_EQ) neq_subexpr)*;
  597. auto getNode = [](const TRule_eq_subexpr::TBlock2& b) -> const TRule_neq_subexpr& { return b.GetRule_neq_subexpr2(); };
  598. return BinOpList(node.GetRule_neq_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end());
  599. }
  600. TNodePtr SubExpr(const TRule_or_subexpr& node) {
  601. // or_subexpr: and_subexpr (AND and_subexpr)*;
  602. auto getNode = [](const TRule_or_subexpr::TBlock2& b) -> const TRule_and_subexpr& { return b.GetRule_and_subexpr2(); };
  603. return BinOper("And", node.GetRule_and_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end());
  604. }
  605. TNodePtr SubExpr(const TRule_and_subexpr& node) {
  606. // and_subexpr: xor_subexpr (XOR xor_subexpr)*;
  607. auto getNode = [](const TRule_and_subexpr::TBlock2& b) -> const TRule_xor_subexpr& { return b.GetRule_xor_subexpr2(); };
  608. return BinOper("Xor", node.GetRule_xor_subexpr1(), getNode, node.GetBlock2().begin(), node.GetBlock2().end());
  609. }
  610. template <typename TNode, typename TGetNode, typename TIter>
  611. TNodePtr BinOpList(const TNode& node, TGetNode getNode, TIter begin, TIter end);
  612. TNodePtr BinOperList(const TString& opName, TVector<TNodePtr>::const_iterator begin, TVector<TNodePtr>::const_iterator end) const;
  613. template <typename TNode, typename TGetNode, typename TIter>
  614. TNodePtr BinOper(const TString& operName, const TNode& node, TGetNode getNode, TIter begin, TIter end);
  615. TNodePtr SqlInExpr(const TRule_in_expr& node);
  616. TNodePtr SmartParenthesis(const TRule_smart_parenthesis& node);
  617. ESmartParenthesis SmartParenthesisMode = ESmartParenthesis::Default;
  618. THashMap<TString, TNodePtr> ExprShortcuts;
  619. };
  620. class TSqlCallExpr: public TSqlTranslation {
  621. public:
  622. TSqlCallExpr(TContext& ctx, NSQLTranslation::ESqlMode mode, TSqlExpression* usedExpr = nullptr)
  623. : TSqlTranslation(ctx, mode)
  624. , UsedExpr(usedExpr)
  625. {
  626. }
  627. TSqlCallExpr(const TSqlCallExpr& call, const TVector<TNodePtr>& args)
  628. : TSqlTranslation(call.Ctx, call.Mode)
  629. , Pos(call.Pos)
  630. , Func(call.Func)
  631. , Module(call.Module)
  632. , Node(call.Node)
  633. , Args(args)
  634. , AggMode(call.AggMode)
  635. {
  636. }
  637. template<typename TCallExprRule>
  638. bool Init(const TCallExprRule& node);
  639. void IncCounters();
  640. TNodePtr BuildUdf(bool withArgsType) {
  641. auto result = Node ? Node : BuildCallable(Pos, Module, Func, withArgsType ? Args : TVector<TNodePtr>());
  642. if (to_lower(Module) == "tensorflow" && Func == "RunBatch") {
  643. Args.erase(Args.begin() + 2);
  644. }
  645. return result;
  646. }
  647. TNodePtr BuildCall() {
  648. TVector<TNodePtr> args;
  649. if (Node) {
  650. Module = "YQL";
  651. Func = NamedArgs.empty() ? "Apply" : "NamedApply";
  652. args.push_back(Node);
  653. }
  654. bool mustUseNamed = !NamedArgs.empty();
  655. if (mustUseNamed) {
  656. if (Node) {
  657. mustUseNamed = false;
  658. }
  659. args.emplace_back(BuildTuple(Pos, PositionalArgs));
  660. args.emplace_back(BuildStructure(Pos, NamedArgs));
  661. } else {
  662. args.insert(args.end(), Args.begin(), Args.end());
  663. }
  664. TFuncPrepareNameNode funcPrepareNameNode;
  665. if (UsedExpr) {
  666. funcPrepareNameNode = [this](const TString& baseName, const TNodePtr& node) {
  667. return UsedExpr->ExprShortcut(baseName, node);
  668. };
  669. }
  670. auto result = BuildBuiltinFunc(Ctx, Pos, Func, args, Module, AggMode, &mustUseNamed, funcPrepareNameNode);
  671. if (mustUseNamed) {
  672. Error() << "Named args are used for call, but unsupported by function: " << Func;
  673. return nullptr;
  674. }
  675. return result;
  676. }
  677. TPosition GetPos() const {
  678. return Pos;
  679. }
  680. const TVector<TNodePtr>& GetArgs() const {
  681. return Args;
  682. }
  683. bool EnsureNotDistinct(const TString& request) const {
  684. if (AggMode == EAggregateMode::Distinct) {
  685. Ctx.Error() << request << " does not allow DISTINCT arguments";
  686. return false;
  687. }
  688. return true;
  689. }
  690. void SetOverWindow() {
  691. YQL_ENSURE(AggMode == EAggregateMode::Normal);
  692. AggMode = EAggregateMode::OverWindow;
  693. }
  694. void SetIgnoreNulls() {
  695. Func += "_IgnoreNulls";
  696. }
  697. private:
  698. TPosition Pos;
  699. TString Func;
  700. TString Module;
  701. TNodePtr Node;
  702. TVector<TNodePtr> Args;
  703. TVector<TNodePtr> PositionalArgs;
  704. TVector<TNodePtr> NamedArgs;
  705. EAggregateMode AggMode = EAggregateMode::Normal;
  706. TSqlExpression* UsedExpr = nullptr;
  707. };
  708. TNodePtr TSqlTranslation::NamedExpr(const TRule_named_expr& node, EExpr exprMode) {
  709. TSqlExpression expr(Ctx, Mode);
  710. if (exprMode == EExpr::GroupBy) {
  711. expr.SetSmartParenthesisMode(TSqlExpression::ESmartParenthesis::GroupBy);
  712. } else if (exprMode == EExpr::SqlLambdaParams) {
  713. expr.SetSmartParenthesisMode(TSqlExpression::ESmartParenthesis::SqlLambdaParams);
  714. }
  715. TNodePtr exprNode(expr.WrapExprShortcuts(expr.Build(node.GetRule_expr1())));
  716. if (!exprNode) {
  717. Ctx.IncrementMonCounter("sql_errors", "NamedExprInvalid");
  718. return nullptr;
  719. }
  720. if (node.HasBlock2()) {
  721. exprNode = SafeClone(exprNode);
  722. exprNode->SetLabel(IdOrString(node.GetBlock2().GetRule_id_or_string2(), *this));
  723. }
  724. return exprNode;
  725. }
  726. bool TSqlTranslation::NamedExprList(const TRule_named_expr_list& node, TVector<TNodePtr>& exprs, EExpr exprMode) {
  727. exprs.emplace_back(NamedExpr(node.GetRule_named_expr1(), exprMode));
  728. if (!exprs.back()) {
  729. return false;
  730. }
  731. for (auto& b: node.GetBlock2()) {
  732. exprs.emplace_back(NamedExpr(b.GetRule_named_expr2(), exprMode));
  733. if (!exprs.back()) {
  734. return false;
  735. }
  736. }
  737. return true;
  738. }
  739. bool TSqlTranslation::BindList(const TRule_bind_parameter_list& node, TVector<TString>& bindNames) {
  740. bindNames.emplace_back(NamedNodeImpl(node.GetRule_bind_parameter1(), *this));
  741. for (auto& b: node.GetBlock2()) {
  742. bindNames.emplace_back(NamedNodeImpl(b.GetRule_bind_parameter2(), *this));
  743. }
  744. return true;
  745. }
  746. bool TSqlTranslation::ModulePath(const TRule_module_path& node, TVector<TString>& path) {
  747. if (node.HasBlock1()) {
  748. path.emplace_back(TString());
  749. }
  750. path.emplace_back(Id(node.GetRule_id2(), *this));
  751. for (auto& b: node.GetBlock3()) {
  752. path.emplace_back(Id(b.GetRule_id2(), *this));
  753. }
  754. return true;
  755. }
  756. bool TSqlTranslation::NamedBindList(const TRule_named_bind_parameter_list& node, TVector<TNodePtr>& bindNames) {
  757. bindNames.emplace_back(NamedBindParam(node.GetRule_named_bind_parameter1()));
  758. for (auto& b: node.GetBlock2()) {
  759. bindNames.emplace_back(NamedBindParam(b.GetRule_named_bind_parameter2()));
  760. }
  761. return std::find(bindNames.begin(), bindNames.end(), nullptr) == bindNames.end();
  762. }
  763. TNodePtr TSqlTranslation::NamedBindParam(const TRule_named_bind_parameter& node) {
  764. auto bindName = NamedNodeImpl(node.GetRule_bind_parameter1(), *this);
  765. auto result = BuildAtom(Ctx.Pos(), bindName, NYql::TNodeFlags::Default);
  766. if (node.HasBlock2()) {
  767. result->SetLabel(NamedNodeImpl(node.GetBlock2().GetRule_bind_parameter2(), *this));
  768. }
  769. return result;
  770. }
  771. TMaybe<TTableArg> TSqlTranslation::TableArgImpl(const TRule_table_arg& node) {
  772. TTableArg ret;
  773. ret.HasAt = node.HasBlock1();
  774. TSqlExpression expr(Ctx, Mode);
  775. ret.Expr = expr.Build(node.GetRule_expr2());
  776. if (!ret.Expr) {
  777. return Nothing();
  778. }
  779. if (node.HasBlock3()) {
  780. ret.View = IdOrString(node.GetBlock3().GetRule_id_or_string2(), *this);
  781. Context().IncrementMonCounter("sql_features", "View");
  782. }
  783. return ret;
  784. }
  785. TTableRef TSqlTranslation::TableRefImpl(const TRule_table_ref& node) {
  786. if (Mode == NSQLTranslation::ESqlMode::LIMITED_VIEW && node.GetRule_opt_id_prefix1().HasBlock1()) {
  787. Ctx.Error() << "Cluster should not be used in limited view";
  788. return TTableRef(Ctx.MakeName("table"), Ctx.CurrCluster, nullptr);
  789. }
  790. auto cluster = OptIdPrefixAsClusterStr(node.GetRule_opt_id_prefix1(), *this, Context().CurrCluster);
  791. if (!cluster) {
  792. return TTableRef(Ctx.MakeName("table"), Ctx.CurrCluster, nullptr);
  793. }
  794. TTableRef tr(Context().MakeName("table"), cluster, nullptr);
  795. TPosition pos(Context().Pos());
  796. TVector<TString> tableHints;
  797. auto& block = node.GetBlock2();
  798. switch (block.Alt_case()) {
  799. case TRule_table_ref::TBlock2::kAlt1: {
  800. auto pair = TableKeyImpl(block.GetAlt1().GetRule_table_key1(), *this);
  801. tr.Keys = BuildTableKey(pos, cluster, TDeferredAtom(pos, pair.first), pair.second);
  802. break;
  803. }
  804. case TRule_table_ref::TBlock2::kAlt2: {
  805. auto& alt = block.GetAlt2();
  806. const TString func(Id(alt.GetRule_id_expr1(), *this));
  807. auto arg = TableArgImpl(alt.GetRule_table_arg3());
  808. if (!arg) {
  809. return TTableRef(Ctx.MakeName("table"), Ctx.CurrCluster, nullptr);
  810. }
  811. TVector<TTableArg> args(1, *arg);
  812. for (auto& b : alt.GetBlock4()) {
  813. arg = TableArgImpl(b.GetRule_table_arg2());
  814. if (!arg) {
  815. return TTableRef(Ctx.MakeName("table"), Ctx.CurrCluster, nullptr);
  816. }
  817. args.push_back(*arg);
  818. }
  819. tableHints = GetTableFuncHints(func);
  820. tr.Keys = BuildTableKeys(pos, cluster, func, args);
  821. break;
  822. }
  823. default:
  824. Y_ABORT("You should change implementation according grammar changes");
  825. }
  826. TVector<TString> hints = GetContextHints(Ctx);
  827. if (node.HasBlock3()) {
  828. hints = TableHintsImpl(node.GetBlock3().GetRule_table_hints1(), *this);
  829. }
  830. hints.insert(hints.end(), tableHints.begin(), tableHints.end());
  831. if (!hints.empty()) {
  832. tr.Options = BuildInputOptions(pos, hints);
  833. }
  834. return tr;
  835. }
  836. TMaybe<TSourcePtr> TSqlTranslation::AsTableImpl(const TRule_table_ref& node) {
  837. const auto& block = node.GetBlock2();
  838. if (block.Alt_case() == TRule_table_ref::TBlock2::kAlt2) {
  839. auto& alt = block.GetAlt2();
  840. TCiString func(Id(alt.GetRule_id_expr1(), *this));
  841. if (func == "as_table") {
  842. if (node.GetRule_opt_id_prefix1().HasBlock1()) {
  843. Ctx.Error() << "Cluster shouldn't be specified for AS_TABLE source";
  844. return TMaybe<TSourcePtr>(nullptr);
  845. }
  846. if (!alt.GetBlock4().empty()) {
  847. Ctx.Error() << "Expected single argument for AS_TABLE source";
  848. return TMaybe<TSourcePtr>(nullptr);
  849. }
  850. if (node.HasBlock3()) {
  851. Ctx.Error() << "No hints expected for AS_TABLE source";
  852. return TMaybe<TSourcePtr>(nullptr);
  853. }
  854. auto arg = TableArgImpl(alt.GetRule_table_arg3());
  855. if (!arg) {
  856. return TMaybe<TSourcePtr>(nullptr);
  857. }
  858. if (arg->Expr->GetSource()) {
  859. Ctx.Error() << "AS_TABLE shouldn't be used for table sources";
  860. return TMaybe<TSourcePtr>(nullptr);
  861. }
  862. return BuildNodeSource(Ctx.Pos(), arg->Expr);
  863. }
  864. }
  865. return Nothing();
  866. }
  867. bool Expr(TSqlExpression& sqlExpr, TVector<TNodePtr>& exprNodes, const TRule_expr& node) {
  868. TNodePtr exprNode = sqlExpr.Build(node);
  869. if (!exprNode) {
  870. return false;
  871. }
  872. exprNodes.push_back(exprNode);
  873. return true;
  874. }
  875. bool ExprList(TSqlExpression& sqlExpr, TVector<TNodePtr>& exprNodes, const TRule_expr_list& node) {
  876. if (!Expr(sqlExpr, exprNodes, node.GetRule_expr1())) {
  877. return false;
  878. }
  879. for (auto b: node.GetBlock2()) {
  880. sqlExpr.Token(b.GetToken1());
  881. if (!Expr(sqlExpr, exprNodes, b.GetRule_expr2())) {
  882. return false;
  883. }
  884. }
  885. return true;
  886. }
  887. template<typename TCallExprRule>
  888. bool TSqlCallExpr::Init(const TCallExprRule& node) {
  889. // call_expr: ((id_or_string NAMESPACE id_or_string) | id_expr | bind_parameter) LPAREN (opt_set_quantifier named_expr_list COMMA? | ASTERISK)? RPAREN;
  890. // OR
  891. // in_call_expr: ((id_or_string NAMESPACE id_or_string) | in_id_expr | bind_parameter) LPAREN (opt_set_quantifier named_expr_list COMMA? | ASTERISK)? RPAREN;
  892. const auto& block = node.GetBlock1();
  893. switch (block.Alt_case()) {
  894. case TCallExprRule::TBlock1::kAlt1: {
  895. auto& subblock = block.GetAlt1().GetBlock1();
  896. Module = IdOrString(subblock.GetRule_id_or_string1(), *this);
  897. Func = IdOrString(subblock.GetRule_id_or_string3(), *this);
  898. break;
  899. }
  900. case TCallExprRule::TBlock1::kAlt2: {
  901. if constexpr (std::is_same_v<TCallExprRule, TRule_call_expr>) {
  902. Func = Id(block.GetAlt2().GetRule_id_expr1(), *this);
  903. } else {
  904. Func = Id(block.GetAlt2().GetRule_in_id_expr1(), *this);
  905. }
  906. break;
  907. }
  908. case TCallExprRule::TBlock1::kAlt3:
  909. Node = GetNamedNode(NamedNodeImpl(block.GetAlt3().GetRule_bind_parameter1(), *this));
  910. if (!Node) {
  911. return false;
  912. }
  913. break;
  914. default:
  915. Y_ABORT("You should change implementation according grammar changes");
  916. }
  917. Pos = Ctx.Pos();
  918. if (node.HasBlock3()) {
  919. switch (node.GetBlock3().Alt_case()) {
  920. case TCallExprRule::TBlock3::kAlt1: {
  921. const auto& alt = node.GetBlock3().GetAlt1();
  922. if (IsDistinctOptSet(alt.GetRule_opt_set_quantifier1())) {
  923. YQL_ENSURE(AggMode == EAggregateMode::Normal);
  924. AggMode = EAggregateMode::Distinct;
  925. Ctx.IncrementMonCounter("sql_features", "DistinctInCallExpr");
  926. }
  927. if (!NamedExprList(alt.GetRule_named_expr_list2(), Args)) {
  928. return false;
  929. }
  930. for (const auto& arg: Args) {
  931. if (arg->GetLabel()) {
  932. NamedArgs.push_back(arg);
  933. } else {
  934. PositionalArgs.push_back(arg);
  935. if (!NamedArgs.empty()) {
  936. Ctx.Error(arg->GetPos()) << "Unnamed arguments can not follow after named one";
  937. return false;
  938. }
  939. }
  940. }
  941. break;
  942. }
  943. case TCallExprRule::TBlock3::kAlt2:
  944. Args.push_back(BuildColumn(Pos, "*"));
  945. break;
  946. default:
  947. Y_ABORT("You should change implementation according grammar changes");
  948. }
  949. }
  950. return true;
  951. }
  952. void TSqlCallExpr::IncCounters() {
  953. if (Node) {
  954. Ctx.IncrementMonCounter("sql_features", "NamedNodeUseApply");
  955. } else if (!Module.empty()) {
  956. if (ValidateForCounters(Module)) {
  957. Ctx.IncrementMonCounter("udf_modules", Module);
  958. Ctx.IncrementMonCounter("sql_features", "CallUdf");
  959. if (ValidateForCounters(Func)) {
  960. auto scriptType = NKikimr::NMiniKQL::ScriptTypeFromStr(Module);
  961. if (scriptType == NKikimr::NMiniKQL::EScriptType::Unknown) {
  962. Ctx.IncrementMonCounter("udf_functions", Module + "." + Func);
  963. }
  964. }
  965. }
  966. } else if (ValidateForCounters(Func)) {
  967. Ctx.IncrementMonCounter("sql_builtins", Func);
  968. Ctx.IncrementMonCounter("sql_features", "CallBuiltin");
  969. }
  970. }
  971. class TSqlSelect: public TSqlTranslation {
  972. public:
  973. TSqlSelect(TContext& ctx, NSQLTranslation::ESqlMode mode)
  974. : TSqlTranslation(ctx, mode)
  975. {
  976. }
  977. TSourcePtr Build(const TRule_select_stmt& node, TPosition& selectPos);
  978. private:
  979. bool SelectTerm(TVector<TNodePtr>& terms, const TRule_result_column& node);
  980. bool ValidateSelectColumns(const TVector<TNodePtr>& terms);
  981. bool ColumnName(TVector<TNodePtr>& keys, const TRule_column_name& node);
  982. bool ColumnList(TVector<TNodePtr>& keys, const TRule_column_list& node);
  983. bool NamedColumn(TVector<TNodePtr>& columnList, const TRule_named_column& node);
  984. bool NamedColumnList(TVector<TNodePtr>& columnList, const TRule_named_column_list& node);
  985. bool SortSpecification(const TRule_sort_specification& node, TVector<TSortSpecificationPtr>& sortSpecs);
  986. bool SortSpecificationList(const TRule_sort_specification_list& node, TVector<TSortSpecificationPtr>& sortSpecs);
  987. TSourcePtr SingleSource(const TRule_single_source& node);
  988. TSourcePtr NamedSingleSource(const TRule_named_single_source& node);
  989. TVector<TNodePtr> OrdinaryNamedColumnList(const TRule_ordinary_named_column_list& node);
  990. TSourcePtr FlattenSource(const TRule_flatten_source& node);
  991. TSourcePtr JoinSource(const TRule_join_source& node);
  992. bool JoinOp(ISource* join, const TRule_join_source::TBlock2& block);
  993. TNodePtr JoinExpr(ISource*, const TRule_join_constraint& node);
  994. TSourcePtr ProcessCore(const TRule_process_core& node, const TWriteSettings& settings, TPosition& selectPos);
  995. TSourcePtr ReduceCore(const TRule_reduce_core& node, const TWriteSettings& settings, TPosition& selectPos);
  996. TSourcePtr SelectCore(const TRule_select_core& node, const TWriteSettings& settings, TPosition& selectPos);
  997. bool FrameStart(const TRule_window_frame_start& rule, TNodePtr& node, bool beginBound);
  998. bool FrameBound(const TRule_window_frame_bound& rule, TNodePtr& node, bool beginBound);
  999. bool FrameClause(const TRule_window_frame_clause& node, TMaybe<TFrameSpecification>& winSpecPtr);
  1000. TWindowSpecificationPtr WindowSpecification(const TRule_window_specification_details& rule);
  1001. bool WindowDefenition(const TRule_window_definition& node, TWinSpecs& winSpecs);
  1002. bool WindowClause(const TRule_window_clause& node, TWinSpecs& winSpecs);
  1003. bool OrderByClause(const TRule_order_by_clause& node, TVector<TSortSpecificationPtr>& orderBy);
  1004. TSourcePtr SelectKind(const TRule_select_kind& node, TPosition& selectPos);
  1005. TSourcePtr SelectKind(const TRule_select_kind_partial& node, TPosition& selectPos);
  1006. TSourcePtr SelectKind(const TRule_select_kind_parenthesis& node, TPosition& selectPos);
  1007. };
  1008. class TGroupByClause: public TSqlTranslation {
  1009. enum class EGroupByFeatures {
  1010. Begin,
  1011. Ordinary = Begin,
  1012. Expression,
  1013. Rollup,
  1014. Cube,
  1015. GroupingSet,
  1016. Empty,
  1017. End,
  1018. };
  1019. typedef TEnumBitSet<EGroupByFeatures, static_cast<int>(EGroupByFeatures::Begin), static_cast<int>(EGroupByFeatures::End)> TGroupingSetFeatures;
  1020. class TGroupByClauseCtx: public TSimpleRefCount<TGroupByClauseCtx> {
  1021. public:
  1022. typedef TIntrusivePtr<TGroupByClauseCtx> TPtr;
  1023. TGroupingSetFeatures GroupFeatures;
  1024. TMap<TString, TNodePtr> NodeAliases;
  1025. size_t UnnamedCount = 0;
  1026. };
  1027. public:
  1028. TGroupByClause(TContext& ctx, NSQLTranslation::ESqlMode mode, TGroupByClauseCtx::TPtr groupSetContext = {})
  1029. : TSqlTranslation(ctx, mode)
  1030. , GroupSetContext(groupSetContext ? groupSetContext : TGroupByClauseCtx::TPtr(new TGroupByClauseCtx()))
  1031. {}
  1032. bool Build(const TRule_group_by_clause& node, bool stream);
  1033. bool ParseList(const TRule_grouping_element_list& groupingListNode);
  1034. void SetFeatures(const TString& field) const;
  1035. TVector<TNodePtr>& Content();
  1036. TMap<TString, TNodePtr>& Aliases();
  1037. THoppingWindowSpecPtr GetHoppingWindow();
  1038. private:
  1039. TVector<TNodePtr> MultiplyGroupingSets(const TVector<TNodePtr>& lhs, const TVector<TNodePtr>& rhs) const;
  1040. void ResolveGroupByAndGrouping();
  1041. bool GroupingElement(const TRule_grouping_element& node);
  1042. void FeedCollection(const TNodePtr& elem, TVector<TNodePtr>& collection, bool& hasEmpty) const;
  1043. bool OrdinaryGroupingSet(const TRule_ordinary_grouping_set& node);
  1044. bool OrdinaryGroupingSetList(const TRule_ordinary_grouping_set_list& node);
  1045. bool HoppingWindow(const TRule_hopping_window_specification& node);
  1046. bool IsNodeColumnsOrNamedExpression(const TVector<TNodePtr>& content, const TString& construction) const;
  1047. TGroupingSetFeatures& Features();
  1048. const TGroupingSetFeatures& Features() const;
  1049. bool AddAlias(const TString& label, const TNodePtr& node);
  1050. TString GenerateGroupByExprName();
  1051. bool IsAutogenerated(const TString* name) const;
  1052. TVector<TNodePtr> GroupBySet;
  1053. TGroupByClauseCtx::TPtr GroupSetContext;
  1054. THoppingWindowSpecPtr HoppingWindowSpec; // stream queries
  1055. static const TString AutogenerateNamePrefix;
  1056. };
  1057. const TString TGroupByClause::AutogenerateNamePrefix = "group";
  1058. bool ParseNumbers(TContext& ctx, const TString& strOrig, ui64& value, TString& suffix) {
  1059. const auto str = to_lower(strOrig);
  1060. const auto strLen = str.size();
  1061. ui64 base = 10;
  1062. if (strLen > 2 && str[0] == '0') {
  1063. const auto formatChar = str[1];
  1064. if (formatChar == 'x') {
  1065. base = 16;
  1066. } else if (formatChar == 'o') {
  1067. base = 8;
  1068. } else if (formatChar == 'b') {
  1069. base = 2;
  1070. }
  1071. }
  1072. if (strLen > 1) {
  1073. auto iter = str.cend() - 1;
  1074. if (*iter == 'l' || *iter == 's' || *iter == 't' || /* deprecated */ *iter == 'b') {
  1075. --iter;
  1076. }
  1077. if (*iter == 'u') {
  1078. --iter;
  1079. }
  1080. suffix = TString(++iter, str.cend());
  1081. }
  1082. value = 0;
  1083. const TString digString(str.begin() + (base == 10 ? 0 : 2), str.end() - suffix.size());
  1084. for (const char& cur: digString) {
  1085. const ui64 curDigit = Char2DigitTable[static_cast<int>(cur)];
  1086. if (curDigit >= base) {
  1087. ctx.Error(ctx.Pos()) << "Failed to parse number from string: " << strOrig << ", char: '" << cur <<
  1088. "' is out of base: " << base;
  1089. return false;
  1090. }
  1091. const auto curValue = value;
  1092. value *= base;
  1093. value += curDigit;
  1094. if (curValue > value) {
  1095. ctx.Error(ctx.Pos()) << "Failed to parse number from string: " << strOrig << ", number limit overflow";
  1096. return false;
  1097. }
  1098. }
  1099. return true;
  1100. }
  1101. TNodePtr LiteralNumber(TContext& ctx, const TRule_integer& node) {
  1102. const TString intergerString = ctx.Token(node.GetToken1());
  1103. ui64 value;
  1104. TString suffix;
  1105. if (!ParseNumbers(ctx, intergerString, value, suffix)) {
  1106. return {};
  1107. }
  1108. if (suffix == "ub" || suffix == "b") {
  1109. ctx.Warning(ctx.Pos(), TIssuesIds::YQL_DEPRECATED_TINY_INT_LITERAL_SUFFIX) << "Deprecated suffix 'b' - please use 't' suffix for 8-bit integers";
  1110. }
  1111. const bool noSpaceForInt32 = value >> 31;
  1112. const bool noSpaceForInt64 = value >> 63;
  1113. if (suffix == "") {
  1114. if (noSpaceForInt64) {
  1115. return new TLiteralNumberNode<ui64>(ctx.Pos(), "Uint64", ToString(value));
  1116. } else if (noSpaceForInt32) {
  1117. return new TLiteralNumberNode<i64>(ctx.Pos(), "Int64", ToString(value));
  1118. }
  1119. return new TLiteralNumberNode<i32>(ctx.Pos(), "Int32", ToString(value));
  1120. } else if (suffix == "u") {
  1121. return new TLiteralNumberNode<ui32>(ctx.Pos(), "Uint32", ToString(value));
  1122. } else if (suffix == "ul") {
  1123. return new TLiteralNumberNode<ui64>(ctx.Pos(), "Uint64", ToString(value));
  1124. } else if (suffix == "ut" || suffix == "ub") {
  1125. return new TLiteralNumberNode<ui8>(ctx.Pos(), "Uint8", ToString(value));
  1126. } else if (suffix == "t" || suffix == "b") {
  1127. return new TLiteralNumberNode<i8>(ctx.Pos(), "Int8", ToString(value));
  1128. } else if (suffix == "l") {
  1129. return new TLiteralNumberNode<i64>(ctx.Pos(), "Int64", ToString(value));
  1130. } else if (suffix == "us") {
  1131. return new TLiteralNumberNode<ui16>(ctx.Pos(), "Uint16", ToString(value));
  1132. } else if (suffix == "s") {
  1133. return new TLiteralNumberNode<i16>(ctx.Pos(), "Int16", ToString(value));
  1134. } else {
  1135. ctx.Error(ctx.Pos()) << "Failed to parse number from string: " << intergerString << ", invalid suffix: " << suffix;
  1136. return {};
  1137. }
  1138. }
  1139. TNodePtr LiteralReal(TContext& ctx, const TRule_real& node) {
  1140. const TString value(ctx.Token(node.GetToken1()));
  1141. YQL_ENSURE(!value.empty());
  1142. const auto lastValue = value[value.size() - 1];
  1143. if (lastValue == 'f' || lastValue == 'F') {
  1144. return new TLiteralNumberNode<float>(ctx.Pos(), "Float", value.substr(0, value.size()-1));
  1145. } else {
  1146. return new TLiteralNumberNode<double>(ctx.Pos(), "Double", value);
  1147. }
  1148. }
  1149. TNodePtr Literal(TContext& ctx, const TRule_unsigned_number& rule) {
  1150. switch (rule.Alt_case()) {
  1151. case TRule_unsigned_number::kAltUnsignedNumber1:
  1152. return LiteralNumber(ctx, rule.GetAlt_unsigned_number1().GetRule_integer1());
  1153. case TRule_unsigned_number::kAltUnsignedNumber2:
  1154. return LiteralReal(ctx, rule.GetAlt_unsigned_number2().GetRule_real1());
  1155. default:
  1156. Y_ABORT("Unsigned number: you should change implementation according grammar changes");
  1157. }
  1158. }
  1159. TNodePtr TSqlExpression::LiteralExpr(const TRule_literal_value& node) {
  1160. switch (node.Alt_case()) {
  1161. case TRule_literal_value::kAltLiteralValue1: {
  1162. return LiteralNumber(Ctx, node.GetAlt_literal_value1().GetRule_integer1());
  1163. }
  1164. case TRule_literal_value::kAltLiteralValue2: {
  1165. return LiteralReal(Ctx, node.GetAlt_literal_value2().GetRule_real1());
  1166. }
  1167. case TRule_literal_value::kAltLiteralValue3: {
  1168. const TString value(Token(node.GetAlt_literal_value3().GetToken1()));
  1169. return BuildLiteralSmartString(Ctx, value);
  1170. }
  1171. case TRule_literal_value::kAltLiteralValue5: {
  1172. Token(node.GetAlt_literal_value5().GetToken1());
  1173. return BuildLiteralNull(Ctx.Pos());
  1174. }
  1175. case TRule_literal_value::kAltLiteralValue9: {
  1176. const TString value(Token(node.GetAlt_literal_value9().GetRule_bool_value1().GetToken1()));
  1177. return BuildLiteralBool(Ctx.Pos(), value);
  1178. }
  1179. case TRule_literal_value::kAltLiteralValue10: {
  1180. return BuildEmptyAction(Ctx.Pos());
  1181. }
  1182. default:
  1183. AltNotImplemented("literal_value", node);
  1184. }
  1185. return nullptr;
  1186. }
  1187. template<typename TUnarySubExprType>
  1188. TNodePtr TSqlExpression::UnaryExpr(const TUnarySubExprType& node) {
  1189. //unary_subexpr: (id_expr | atom_expr ) key_expr* (DOT (bind_parameter | DIGITS | id_or_string) key_expr*)* (COLLATE id)?;
  1190. // OR
  1191. //in_unary_subexpr: (in_id_expr | in_atom_expr) key_expr* (DOT (bind_parameter | DIGITS | id_or_string) key_expr*)* (COLLATE id)?;
  1192. TVector<INode::TIdPart> ids;
  1193. auto& block = node.GetBlock1();
  1194. switch (block.Alt_case()) {
  1195. case TUnarySubExprType::TBlock1::kAlt1: {
  1196. auto& alt = block.GetAlt1();
  1197. TString name;
  1198. if constexpr (std::is_same_v<TUnarySubExprType, TRule_unary_subexpr>) {
  1199. name = Id(alt.GetRule_id_expr1(), *this);
  1200. } else {
  1201. name = Id(alt.GetRule_in_id_expr1(), *this);
  1202. }
  1203. ids.push_back(BuildColumn(Ctx.Pos()));
  1204. ids.push_back(name);
  1205. break;
  1206. }
  1207. case TUnarySubExprType::TBlock1::kAlt2: {
  1208. TNodePtr expr;
  1209. if constexpr (std::is_same_v<TUnarySubExprType, TRule_unary_subexpr>) {
  1210. expr = AtomExpr(block.GetAlt2().GetRule_atom_expr1());
  1211. } else {
  1212. expr = InAtomExpr(block.GetAlt2().GetRule_in_atom_expr1());
  1213. }
  1214. if (!expr) {
  1215. Ctx.IncrementMonCounter("sql_errors", "BadAtomExpr");
  1216. return nullptr;
  1217. }
  1218. ids.push_back(expr);
  1219. break;
  1220. }
  1221. default:
  1222. Y_ABORT("You should change implementation according grammar changes");
  1223. }
  1224. bool isLookup = false;
  1225. for (auto& b: node.GetBlock2()) {
  1226. auto expr = KeyExpr(b.GetRule_key_expr1());
  1227. if (!expr) {
  1228. Ctx.IncrementMonCounter("sql_errors", "BadKeyExpr");
  1229. return nullptr;
  1230. }
  1231. ids.push_back(expr);
  1232. isLookup = true;
  1233. }
  1234. TPosition pos(Ctx.Pos());
  1235. for (auto& dotBlock: node.GetBlock3()) {
  1236. auto bb = dotBlock.GetBlock2();
  1237. switch (bb.Alt_case()) {
  1238. case TUnarySubExprType::TBlock3::TBlock2::kAlt1: {
  1239. auto named = NamedNodeImpl(bb.GetAlt1().GetRule_bind_parameter1(), *this);
  1240. auto namedNode = GetNamedNode(named);
  1241. if (!namedNode) {
  1242. return nullptr;
  1243. }
  1244. ids.push_back(named);
  1245. ids.back().Expr = namedNode;
  1246. break;
  1247. }
  1248. case TUnarySubExprType::TBlock3::TBlock2::kAlt2: {
  1249. const TString str(Token(bb.GetAlt2().GetToken1()));
  1250. i32 pos = -1;
  1251. if (!TryFromString<i32>(str, pos)) {
  1252. Ctx.Error() << "Failed to parse i32 from string: " << str;
  1253. Ctx.IncrementMonCounter("sql_errors", "FailedToParsePos");
  1254. return nullptr;
  1255. }
  1256. ids.push_back(pos);
  1257. break;
  1258. }
  1259. case TUnarySubExprType::TBlock3::TBlock2::kAlt3: {
  1260. ids.push_back(IdOrString(bb.GetAlt3().GetRule_id_or_string1(), *this));
  1261. break;
  1262. }
  1263. default:
  1264. Y_ABORT("You should change implementation according grammar changes");
  1265. }
  1266. for (auto& b: dotBlock.GetBlock3()) {
  1267. auto expr = KeyExpr(b.GetRule_key_expr1());
  1268. if (!expr) {
  1269. Ctx.IncrementMonCounter("sql_errors", "BadKeyExpr");
  1270. return nullptr;
  1271. }
  1272. ids.push_back(expr);
  1273. isLookup = true;
  1274. }
  1275. }
  1276. if (node.HasBlock4()) {
  1277. Ctx.IncrementMonCounter("sql_errors", "CollateUnarySubexpr");
  1278. Error() << "unary_subexpr: COLLATE is not implemented yet";
  1279. }
  1280. Y_DEBUG_ABORT_UNLESS(!ids.empty());
  1281. Y_DEBUG_ABORT_UNLESS(ids.front().Expr);
  1282. return ids.size() > 1 ? BuildAccess(pos, ids, isLookup) : ids.back().Expr;
  1283. }
  1284. TNodePtr TSqlExpression::BindParameterRule(const TRule_bind_parameter& rule) {
  1285. const auto namedArg = NamedNodeImpl(rule, *this);
  1286. if (SmartParenthesisMode == ESmartParenthesis::SqlLambdaParams) {
  1287. Ctx.IncrementMonCounter("sql_features", "LambdaArgument");
  1288. return BuildAtom(Ctx.Pos(), namedArg);
  1289. } else {
  1290. Ctx.IncrementMonCounter("sql_features", "NamedNodeUseAtom");
  1291. return GetNamedNode(namedArg);
  1292. }
  1293. }
  1294. TNodePtr TSqlExpression::LambdaRule(const TRule_lambda& rule) {
  1295. const auto& alt = rule;
  1296. const bool isSqlLambda = alt.HasBlock2();
  1297. if (!isSqlLambda) {
  1298. return SmartParenthesis(alt.GetRule_smart_parenthesis1());
  1299. }
  1300. TSqlExpression expr(Ctx, Mode);
  1301. expr.SetSmartParenthesisMode(ESmartParenthesis::SqlLambdaParams);
  1302. auto parenthesis = expr.SmartParenthesis(alt.GetRule_smart_parenthesis1());
  1303. if (!parenthesis) {
  1304. return {};
  1305. }
  1306. TVector<TString> args;
  1307. if (!SqlLambdaParams(parenthesis, args)) {
  1308. return {};
  1309. }
  1310. auto bodyBlock = alt.GetBlock2();
  1311. Token(bodyBlock.GetToken1());
  1312. TPosition pos(Ctx.Pos());
  1313. TVector<TNodePtr> exprSeq;
  1314. for (const auto& arg: args) {
  1315. PushNamedNode(arg, BuildAtom(pos, arg, NYql::TNodeFlags::Default));
  1316. }
  1317. const bool ret = SqlLambdaExprBody(Ctx, bodyBlock.GetRule_lambda_body3(), exprSeq);
  1318. for (const auto& arg : args) {
  1319. PopNamedNode(arg);
  1320. }
  1321. if (!ret) {
  1322. return {};
  1323. }
  1324. return BuildSqlLambda(pos, std::move(args), std::move(exprSeq));
  1325. }
  1326. TNodePtr TSqlExpression::CastRule(const TRule_cast_expr& rule) {
  1327. Ctx.IncrementMonCounter("sql_features", "Cast");
  1328. const auto& alt = rule;
  1329. Token(alt.GetToken1());
  1330. TPosition pos(Ctx.Pos());
  1331. TSqlExpression expr(Ctx, Mode);
  1332. const auto& paramOne = alt.GetRule_type_name5().HasBlock2() ? alt.GetRule_type_name5().GetBlock2().GetRule_integer2().GetToken1().GetValue() : TString();
  1333. const auto& paramTwo = !paramOne.empty() && alt.GetRule_type_name5().GetBlock2().HasBlock3() ? alt.GetRule_type_name5().GetBlock2().GetBlock3().GetRule_integer2().GetToken1().GetValue() : TString();
  1334. return BuildCast(Ctx, pos, expr.Build(alt.GetRule_expr3()), Id(alt.GetRule_type_name5().GetRule_id1(), *this), paramOne, paramTwo);
  1335. }
  1336. TNodePtr TSqlExpression::BitCastRule(const TRule_bitcast_expr& rule) {
  1337. Ctx.IncrementMonCounter("sql_features", "BitCast");
  1338. const auto& alt = rule;
  1339. Token(alt.GetToken1());
  1340. TPosition pos(Ctx.Pos());
  1341. TSqlExpression expr(Ctx, Mode);
  1342. const auto& paramOne = alt.GetRule_type_name5().HasBlock2() ? alt.GetRule_type_name5().GetBlock2().GetRule_integer2().GetToken1().GetValue() : TString();
  1343. const auto& paramTwo = !paramOne.empty() && alt.GetRule_type_name5().GetBlock2().HasBlock3() ? alt.GetRule_type_name5().GetBlock2().GetBlock3().GetRule_integer2().GetToken1().GetValue() : TString();
  1344. return BuildBitCast(Ctx, pos, expr.Build(alt.GetRule_expr3()), Id(alt.GetRule_type_name5().GetRule_id1(), *this), paramOne, paramTwo);
  1345. }
  1346. TNodePtr TSqlExpression::ExistsRule(const TRule_exists_expr& rule) {
  1347. Ctx.IncrementMonCounter("sql_features", "Exists");
  1348. const auto& alt = rule;
  1349. Token(alt.GetToken2());
  1350. TSqlSelect select(Ctx, Mode);
  1351. TPosition pos;
  1352. auto source = select.Build(alt.GetRule_select_stmt3(), pos);
  1353. if (!source) {
  1354. Ctx.IncrementMonCounter("sql_errors", "BadSource");
  1355. return nullptr;
  1356. }
  1357. const bool checkExist = true;
  1358. return BuildBuiltinFunc(Ctx, Ctx.Pos(), "ListHasItems", {BuildSourceNode(pos, std::move(source), checkExist)});
  1359. }
  1360. TNodePtr TSqlExpression::CaseRule(const TRule_case_expr& rule) {
  1361. Ctx.IncrementMonCounter("sql_features", "Case");
  1362. const auto& alt = rule;
  1363. Token(alt.GetToken1());
  1364. TNodePtr elseExpr;
  1365. if (alt.HasBlock4()) {
  1366. Token(alt.GetBlock4().GetToken1());
  1367. TSqlExpression expr(Ctx, Mode);
  1368. elseExpr = expr.Build(alt.GetBlock4().GetRule_expr2());
  1369. } else {
  1370. Ctx.IncrementMonCounter("sql_errors", "ElseIsRequired");
  1371. Error() << "ELSE is required";
  1372. return nullptr;
  1373. }
  1374. TVector<TNodePtr> args;
  1375. for (int i = alt.Block3Size() - 1; i >= 0; --i) {
  1376. const auto& block = alt.GetBlock3(i).GetRule_when_expr1();
  1377. args.clear();
  1378. Token(block.GetToken1());
  1379. TSqlExpression condExpr(Ctx, Mode);
  1380. args.push_back(condExpr.Build(block.GetRule_expr2()));
  1381. if (alt.HasBlock2()) {
  1382. TSqlExpression expr(Ctx, Mode);
  1383. args.back() = BuildBinaryOp(Ctx.Pos(), "==", expr.Build(alt.GetBlock2().GetRule_expr1()), args.back());
  1384. }
  1385. Token(block.GetToken3());
  1386. TSqlExpression thenExpr(Ctx, Mode);
  1387. args.push_back(thenExpr.Build(block.GetRule_expr4()));
  1388. args.push_back(elseExpr);
  1389. if (i > 0) {
  1390. elseExpr = BuildBuiltinFunc(Ctx, Ctx.Pos(), "If", args);
  1391. }
  1392. }
  1393. return BuildBuiltinFunc(Ctx, Ctx.Pos(), "If", args);
  1394. }
  1395. template<typename TWindowFunctionType>
  1396. TNodePtr TSqlExpression::WindowFunctionRule(const TWindowFunctionType& rule) {
  1397. // window_function: call_expr (null_treatment? OVER window_name_or_specification)?;
  1398. // OR
  1399. // in_window_function: in_call_expr (null_treatment? OVER window_name_or_specification)?;
  1400. const bool overWindow = rule.HasBlock2();
  1401. TSqlCallExpr call(Ctx, Mode, this);
  1402. bool initResult;
  1403. if constexpr (std::is_same_v<TWindowFunctionType, TRule_window_function>) {
  1404. initResult = call.Init(rule.GetRule_call_expr1());
  1405. } else {
  1406. initResult = call.Init(rule.GetRule_in_call_expr1());
  1407. }
  1408. if (!initResult) {
  1409. return {};
  1410. }
  1411. call.IncCounters();
  1412. if (!overWindow) {
  1413. return call.BuildCall();
  1414. }
  1415. auto funcSpec = rule.GetBlock2();
  1416. call.SetOverWindow();
  1417. auto winRule = funcSpec.GetRule_window_name_or_specification3();
  1418. if (winRule.Alt_case() != TRule_window_name_or_specification::kAltWindowNameOrSpecification1) {
  1419. Error() << "Inline window specification is not supported yet! You can define window function in WINDOW clause.";
  1420. return {};
  1421. }
  1422. if (funcSpec.HasBlock1() && funcSpec.GetBlock1().GetRule_null_treatment1().Alt_case() == TRule_null_treatment::kAltNullTreatment2) {
  1423. call.SetIgnoreNulls();
  1424. }
  1425. const TString windowName = Id(winRule.GetAlt_window_name_or_specification1().GetRule_window_name1().GetRule_id1(), *this);
  1426. Ctx.IncrementMonCounter("sql_features", "WindowFunctionOver");
  1427. return BuildCalcOverWindow(Ctx.Pos(), windowName, call.BuildCall());
  1428. }
  1429. TNodePtr TSqlExpression::AtomExpr(const TRule_atom_expr& node) {
  1430. // atom_expr:
  1431. // literal_value
  1432. // | bind_parameter
  1433. // | window_function
  1434. // | lambda
  1435. // | cast_expr
  1436. // | exists_expr
  1437. // | case_expr
  1438. // | id_or_string NAMESPACE id_or_string
  1439. // ;
  1440. switch (node.Alt_case()) {
  1441. case TRule_atom_expr::kAltAtomExpr1:
  1442. Ctx.IncrementMonCounter("sql_features", "LiteralExpr");
  1443. return LiteralExpr(node.GetAlt_atom_expr1().GetRule_literal_value1());
  1444. case TRule_atom_expr::kAltAtomExpr2:
  1445. return BindParameterRule(node.GetAlt_atom_expr2().GetRule_bind_parameter1());
  1446. case TRule_atom_expr::kAltAtomExpr3:
  1447. return WindowFunctionRule(node.GetAlt_atom_expr3().GetRule_window_function1());
  1448. case TRule_atom_expr::kAltAtomExpr4:
  1449. return LambdaRule(node.GetAlt_atom_expr4().GetRule_lambda1());
  1450. case TRule_atom_expr::kAltAtomExpr5:
  1451. return CastRule(node.GetAlt_atom_expr5().GetRule_cast_expr1());
  1452. case TRule_atom_expr::kAltAtomExpr6:
  1453. return ExistsRule(node.GetAlt_atom_expr6().GetRule_exists_expr1());
  1454. case TRule_atom_expr::kAltAtomExpr7:
  1455. return CaseRule(node.GetAlt_atom_expr7().GetRule_case_expr1());
  1456. case TRule_atom_expr::kAltAtomExpr8: {
  1457. const auto& alt = node.GetAlt_atom_expr8();
  1458. const TString module(IdOrString(alt.GetRule_id_or_string1(), *this));
  1459. TPosition pos(Ctx.Pos());
  1460. bool rawString = true;
  1461. const TString name(IdOrString(alt.GetRule_id_or_string3(), *this, rawString));
  1462. return BuildCallable(pos, module, name, {});
  1463. }
  1464. case TRule_atom_expr::kAltAtomExpr9:
  1465. return BitCastRule(node.GetAlt_atom_expr9().GetRule_bitcast_expr1());
  1466. default:
  1467. AltNotImplemented("atom_expr", node);
  1468. }
  1469. return nullptr;
  1470. }
  1471. TNodePtr TSqlExpression::InAtomExpr(const TRule_in_atom_expr& node) {
  1472. // in_atom_expr:
  1473. // literal_value
  1474. // | bind_parameter
  1475. // | in_window_function
  1476. // | smart_parenthesis
  1477. // | cast_expr
  1478. // | case_expr
  1479. // | LPAREN select_stmt RPAREN
  1480. // ;
  1481. switch (node.Alt_case()) {
  1482. case TRule_in_atom_expr::kAltInAtomExpr1:
  1483. Ctx.IncrementMonCounter("sql_features", "LiteralExpr");
  1484. return LiteralExpr(node.GetAlt_in_atom_expr1().GetRule_literal_value1());
  1485. case TRule_in_atom_expr::kAltInAtomExpr2:
  1486. return BindParameterRule(node.GetAlt_in_atom_expr2().GetRule_bind_parameter1());
  1487. case TRule_in_atom_expr::kAltInAtomExpr3:
  1488. return WindowFunctionRule(node.GetAlt_in_atom_expr3().GetRule_in_window_function1());
  1489. case TRule_in_atom_expr::kAltInAtomExpr4:
  1490. return SmartParenthesis(node.GetAlt_in_atom_expr4().GetRule_smart_parenthesis1());
  1491. case TRule_in_atom_expr::kAltInAtomExpr5:
  1492. return CastRule(node.GetAlt_in_atom_expr5().GetRule_cast_expr1());
  1493. case TRule_in_atom_expr::kAltInAtomExpr6:
  1494. return CaseRule(node.GetAlt_in_atom_expr6().GetRule_case_expr1());
  1495. case TRule_in_atom_expr::kAltInAtomExpr7: {
  1496. Token(node.GetAlt_in_atom_expr7().GetToken1());
  1497. TSqlSelect select(Ctx, Mode);
  1498. TPosition pos;
  1499. auto source = select.Build(node.GetAlt_in_atom_expr7().GetRule_select_stmt2(), pos);
  1500. if (!source) {
  1501. Ctx.IncrementMonCounter("sql_errors", "BadSource");
  1502. return {};
  1503. }
  1504. Ctx.IncrementMonCounter("sql_features", "InSubquery");
  1505. return BuildSelectResult(pos, std::move(source), false, Mode == NSQLTranslation::ESqlMode::SUBQUERY);
  1506. }
  1507. case TRule_in_atom_expr::kAltInAtomExpr8:
  1508. return BitCastRule(node.GetAlt_in_atom_expr8().GetRule_bitcast_expr1());
  1509. default:
  1510. AltNotImplemented("in_atom_expr", node);
  1511. }
  1512. return nullptr;
  1513. }
  1514. bool TSqlExpression::SqlLambdaParams(const TNodePtr& node, TVector<TString>& args) {
  1515. auto errMsg = TStringBuf("Invalid lambda arguments syntax. Lambda arguments should starts with '$' as named value.");
  1516. auto tupleNodePtr = dynamic_cast<TTupleNode*>(node.Get());
  1517. if (!tupleNodePtr) {
  1518. Ctx.Error(node->GetPos()) << errMsg;
  1519. return false;
  1520. }
  1521. THashSet<TString> dupArgsChecker;
  1522. for (const auto& argPtr: tupleNodePtr->Elements()) {
  1523. auto contentPtr = argPtr->GetAtomContent();
  1524. if (!contentPtr || !contentPtr->StartsWith("$")) {
  1525. Ctx.Error(argPtr->GetPos()) << errMsg;
  1526. return false;
  1527. }
  1528. if (!dupArgsChecker.insert(*contentPtr).second) {
  1529. Ctx.Error(argPtr->GetPos()) << "Duplicate lambda argument parametr: '" << *contentPtr << "'.";
  1530. return false;
  1531. }
  1532. args.push_back(*contentPtr);
  1533. }
  1534. return true;
  1535. }
  1536. bool TSqlExpression::SqlLambdaExprBody(TContext& ctx, const TRule_lambda_body& node, TVector<TNodePtr>& exprSeq) {
  1537. TSqlExpression expr(ctx, ctx.Settings.Mode);
  1538. TVector<TString> localNames;
  1539. bool hasError = false;
  1540. for (auto& block: node.GetBlock1()) {
  1541. const auto& rule = block.GetRule_lambda_stmt1();
  1542. switch (rule.Alt_case()) {
  1543. case TRule_lambda_stmt::kAltLambdaStmt1: {
  1544. TVector<TString> names;
  1545. auto nodeExpr = NamedNode(rule.GetAlt_lambda_stmt1().GetRule_named_nodes_stmt1(), names);
  1546. if (!nodeExpr) {
  1547. hasError = true;
  1548. continue;
  1549. } else if (nodeExpr->GetSource()) {
  1550. ctx.Error() << "SELECT is not supported inside lambda body";
  1551. hasError = true;
  1552. continue;
  1553. }
  1554. if (names.size() > 1) {
  1555. auto ref = ctx.MakeName("tie");
  1556. exprSeq.push_back(nodeExpr->Y("EnsureTupleSize", nodeExpr, nodeExpr->Q(ToString(names.size()))));
  1557. exprSeq.back()->SetLabel(ref);
  1558. for (size_t i = 0; i < names.size(); ++i) {
  1559. TNodePtr nthExpr = nodeExpr->Y("Nth", ref, nodeExpr->Q(ToString(i)));
  1560. nthExpr->SetLabel(names[i]);
  1561. localNames.push_back(names[i]);
  1562. PushNamedNode(names[i], BuildAtom(nodeExpr->GetPos(), names[i], NYql::TNodeFlags::Default));
  1563. exprSeq.push_back(nthExpr);
  1564. }
  1565. } else {
  1566. nodeExpr->SetLabel(names.front());
  1567. localNames.push_back(names.front());
  1568. PushNamedNode(names.front(), BuildAtom(nodeExpr->GetPos(), names.front(), NYql::TNodeFlags::Default));
  1569. exprSeq.push_back(nodeExpr);
  1570. }
  1571. break;
  1572. }
  1573. case TRule_lambda_stmt::kAltLambdaStmt2: {
  1574. if (!ImportStatement(rule.GetAlt_lambda_stmt2().GetRule_import_stmt1(), &localNames)) {
  1575. hasError = true;
  1576. }
  1577. break;
  1578. }
  1579. default:
  1580. Y_ABORT("SampleClause: does not correspond to grammar changes");
  1581. }
  1582. }
  1583. TNodePtr nodeExpr;
  1584. if (!hasError) {
  1585. nodeExpr = expr.Build(node.GetRule_expr3());
  1586. }
  1587. for (const auto& name : localNames) {
  1588. PopNamedNode(name);
  1589. }
  1590. if (!nodeExpr) {
  1591. return false;
  1592. }
  1593. exprSeq.push_back(nodeExpr);
  1594. return true;
  1595. }
  1596. TNodePtr TSqlExpression::SubExpr(const TRule_con_subexpr& node) {
  1597. // con_subexpr: unary_subexpr | unary_op unary_subexpr;
  1598. switch (node.Alt_case()) {
  1599. case TRule_con_subexpr::kAltConSubexpr1:
  1600. return UnaryExpr(node.GetAlt_con_subexpr1().GetRule_unary_subexpr1());
  1601. case TRule_con_subexpr::kAltConSubexpr2: {
  1602. Ctx.IncrementMonCounter("sql_features", "UnaryOperation");
  1603. TString opName;
  1604. auto token = node.GetAlt_con_subexpr2().GetRule_unary_op1().GetToken1();
  1605. Token(token);
  1606. TPosition pos(Ctx.Pos());
  1607. switch (token.GetId()) {
  1608. case SQLLexerTokens::TOKEN_NOT: opName = "Not"; break;
  1609. case SQLLexerTokens::TOKEN_PLUS: opName = "Plus"; break;
  1610. case SQLLexerTokens::TOKEN_MINUS: opName = "Minus"; break;
  1611. case SQLLexerTokens::TOKEN_TILDA: opName = "BitNot"; break;
  1612. default:
  1613. Ctx.IncrementMonCounter("sql_errors", "UnsupportedUnaryOperation");
  1614. Error() << "Unsupported unary operation: " << token.GetValue();
  1615. return nullptr;
  1616. }
  1617. Ctx.IncrementMonCounter("sql_unary_operations", opName);
  1618. return BuildUnaryOp(pos, opName, UnaryExpr(node.GetAlt_con_subexpr2().GetRule_unary_subexpr2()));
  1619. }
  1620. default:
  1621. Y_ABORT("You should change implementation according grammar changes");
  1622. }
  1623. return nullptr;
  1624. }
  1625. TNodePtr TSqlExpression::SubExpr(const TRule_xor_subexpr& node) {
  1626. // xor_subexpr: eq_subexpr cond_expr?;
  1627. TNodePtr res(SubExpr(node.GetRule_eq_subexpr1()));
  1628. if (!res) {
  1629. return {};
  1630. }
  1631. TPosition pos(Ctx.Pos());
  1632. if (node.HasBlock2()) {
  1633. auto cond = node.GetBlock2().GetRule_cond_expr1();
  1634. switch (cond.Alt_case()) {
  1635. case TRule_cond_expr::kAltCondExpr1: {
  1636. const auto& matchOp = cond.GetAlt_cond_expr1();
  1637. const bool notMatch = matchOp.HasBlock1();
  1638. const TCiString& opName = Token(matchOp.GetRule_match_op2().GetToken1());
  1639. const auto& pattern = SubExpr(cond.GetAlt_cond_expr1().GetRule_eq_subexpr3());
  1640. if (!pattern) {
  1641. return {};
  1642. }
  1643. TNodePtr isMatch;
  1644. if (opName == "like" || opName == "ilike") {
  1645. const TString* escapeLiteral = nullptr;
  1646. TNodePtr escapeNode;
  1647. const auto& escaper = BuildUdf(Ctx, pos, "Re2", "PatternFromLike", {});
  1648. TVector<TNodePtr> escaperArgs({ escaper, pattern });
  1649. if (matchOp.HasBlock4()) {
  1650. const auto& escapeBlock = matchOp.GetBlock4();
  1651. TNodePtr escapeExpr = SubExpr(escapeBlock.GetRule_eq_subexpr2());
  1652. if (!escapeExpr) {
  1653. return {};
  1654. }
  1655. escapeLiteral = escapeExpr->GetLiteral("String");
  1656. escapeNode = escapeExpr;
  1657. if (escapeLiteral) {
  1658. Ctx.IncrementMonCounter("sql_features", "LikeEscape");
  1659. if (escapeLiteral->size() != 1) {
  1660. Ctx.IncrementMonCounter("sql_errors", "LikeMultiCharEscape");
  1661. Error() << "ESCAPE clause requires single character argument";
  1662. return nullptr;
  1663. }
  1664. if (escapeLiteral[0] == "%" || escapeLiteral[0] == "_" || escapeLiteral[0] == "\\") {
  1665. Ctx.IncrementMonCounter("sql_errors", "LikeUnsupportedEscapeChar");
  1666. Error() << "'%', '_' and '\\' are currently not supported in ESCAPE clause, ";
  1667. Error() << "please choose any other character";
  1668. return nullptr;
  1669. }
  1670. escaperArgs.push_back(BuildLiteralRawString(pos, *escapeLiteral));
  1671. } else {
  1672. Ctx.IncrementMonCounter("sql_errors", "LikeNotLiteralEscape");
  1673. Error() << "ESCAPE clause requires String literal argument";
  1674. return nullptr;
  1675. }
  1676. }
  1677. auto re2options = BuildUdf(Ctx, pos, "Re2", "Options", {});
  1678. TString csMode;
  1679. if (opName == "ilike") {
  1680. Ctx.IncrementMonCounter("sql_features", "CaseInsensitiveLike");
  1681. csMode = "false";
  1682. } else {
  1683. csMode = "true";
  1684. }
  1685. auto csModeLiteral = BuildLiteralBool(pos, csMode);
  1686. csModeLiteral->SetLabel("CaseSensitive");
  1687. auto csOption = BuildStructure(pos, { csModeLiteral });
  1688. auto optionsApply = new TCallNodeImpl(pos, "NamedApply", { re2options, BuildTuple(pos, {}), csOption });
  1689. const TNodePtr escapedPattern = new TCallNodeImpl(pos, "Apply", { escaperArgs });
  1690. auto list = new TAstListNodeImpl(pos, { escapedPattern, optionsApply });
  1691. auto runConfig = new TAstListNodeImpl(pos, { new TAstAtomNodeImpl(pos, "quote", 0), list });
  1692. const auto& matcher = BuildUdf(Ctx, pos, "Re2", "Match", { runConfig });
  1693. isMatch = new TCallNodeImpl(pos, "Apply", { matcher, res });
  1694. const TString* literalPattern = pattern->GetLiteral("String");
  1695. if (literalPattern) {
  1696. TStringBuilder lowerBound;
  1697. bool inEscape = false;
  1698. bool hasPattern = false;
  1699. for (const char c : *literalPattern) {
  1700. if (escapeLiteral && c == escapeLiteral->at(0)) {
  1701. if (inEscape) {
  1702. lowerBound.append(c);
  1703. inEscape = false;
  1704. } else {
  1705. inEscape = true;
  1706. }
  1707. } else {
  1708. if (c == '%' || c == '_') {
  1709. if (inEscape) {
  1710. lowerBound.append(c);
  1711. inEscape = false;
  1712. } else {
  1713. hasPattern = true;
  1714. break;
  1715. }
  1716. } else {
  1717. if (inEscape) {
  1718. Ctx.IncrementMonCounter("sql_errors", "LikeEscapeNormalSymbol");
  1719. Error() << "Escape symbol should be used twice consecutively in LIKE pattern to be considered literal";
  1720. return nullptr;
  1721. } else {
  1722. lowerBound.append(c);
  1723. }
  1724. }
  1725. }
  1726. }
  1727. if (inEscape) {
  1728. Ctx.IncrementMonCounter("sql_errors", "LikeEscapeSymbolEnd");
  1729. Error() << "LIKE pattern should not end with escape symbol";
  1730. return nullptr;
  1731. }
  1732. if (opName != "ilike") {
  1733. if (!hasPattern) {
  1734. isMatch = BuildBinaryOp(pos, "==", res, BuildLiteralSmartString(Ctx,
  1735. TStringBuilder() << "@@" << lowerBound << "@@"));
  1736. } else if (!lowerBound.empty()) {
  1737. const auto& lowerBoundOp = BuildBinaryOp(pos, ">=", res, BuildLiteralSmartString(Ctx,
  1738. TStringBuilder() << "@@" << lowerBound << "@@"));
  1739. auto& isMatchCopy = isMatch;
  1740. TStringBuilder upperBound;
  1741. bool madeIncrement = false;
  1742. for (i64 i = lowerBound.size() - 1; i >=0 ; --i) {
  1743. if (!madeIncrement) {
  1744. upperBound.append(lowerBound[i] + 1);
  1745. madeIncrement = true;
  1746. } else {
  1747. upperBound.append(lowerBound[i]);
  1748. }
  1749. }
  1750. if (madeIncrement) {
  1751. ReverseInPlace(upperBound);
  1752. const auto& between = BuildBinaryOp(
  1753. pos,
  1754. "And",
  1755. lowerBoundOp,
  1756. BuildBinaryOp(pos, "<", res, BuildLiteralSmartString(Ctx,
  1757. TStringBuilder() << "@@" << upperBound << "@@"))
  1758. );
  1759. isMatch = BuildBinaryOp(pos, "And", between, isMatchCopy);
  1760. } else {
  1761. isMatch = BuildBinaryOp(pos, "And", lowerBoundOp, isMatchCopy);
  1762. }
  1763. }
  1764. }
  1765. }
  1766. Ctx.IncrementMonCounter("sql_features", notMatch ? "NotLike" : "Like");
  1767. } else if (opName == "regexp" || opName == "rlike" || opName == "match") {
  1768. if (matchOp.HasBlock4()) {
  1769. Ctx.IncrementMonCounter("sql_errors", "RegexpEscape");
  1770. TString opNameUpper(opName);
  1771. opNameUpper.to_upper();
  1772. Error() << opName << " and ESCAPE clauses should not be used together";
  1773. return nullptr;
  1774. }
  1775. const auto& matcher = BuildUdf(Ctx, pos, "Pcre", opName == "match" ? "BacktrackingMatch" : "BacktrackingGrep", { pattern });
  1776. isMatch = new TCallNodeImpl(pos, "Apply", { matcher, res });
  1777. if (opName != "match") {
  1778. Ctx.IncrementMonCounter("sql_features", notMatch ? "NotRegexp" : "Regexp");
  1779. } else {
  1780. Ctx.IncrementMonCounter("sql_features", notMatch ? "NotMatch" : "Match");
  1781. }
  1782. } else {
  1783. Ctx.IncrementMonCounter("sql_errors", "UnknownMatchOp");
  1784. AltNotImplemented("match_op", cond);
  1785. return nullptr;
  1786. }
  1787. return notMatch ? BuildUnaryOp(pos, "Not", isMatch) : isMatch;
  1788. }
  1789. case TRule_cond_expr::kAltCondExpr2: {
  1790. auto altInExpr = cond.GetAlt_cond_expr2();
  1791. const bool notIn = altInExpr.HasBlock1();
  1792. auto hints = BuildTuple(pos, {});
  1793. if (altInExpr.HasBlock3()) {
  1794. Ctx.IncrementMonCounter("sql_features", "IsCompactHint");
  1795. auto sizeHint = BuildTuple(pos, { BuildQuotedAtom(pos, "isCompact", NYql::TNodeFlags::Default) });
  1796. hints = BuildTuple(pos, { sizeHint });
  1797. }
  1798. TSqlExpression inSubexpr(Ctx, Mode);
  1799. auto inRight = inSubexpr.SqlInExpr(altInExpr.GetRule_in_expr4());
  1800. auto isIn = BuildBuiltinFunc(Ctx, pos, "In", {res, inRight, hints});
  1801. Ctx.IncrementMonCounter("sql_features", notIn ? "NotIn" : "In");
  1802. return notIn ? BuildUnaryOp(pos, "Not", isIn) : isIn;
  1803. }
  1804. case TRule_cond_expr::kAltCondExpr3: {
  1805. auto altCase = cond.GetAlt_cond_expr3().GetBlock1().Alt_case();
  1806. const bool notNoll =
  1807. altCase == TRule_cond_expr::TAlt3::TBlock1::kAlt2 ||
  1808. altCase == TRule_cond_expr::TAlt3::TBlock1::kAlt4
  1809. ;
  1810. if (altCase == TRule_cond_expr::TAlt3::TBlock1::kAlt4 &&
  1811. !cond.GetAlt_cond_expr3().GetBlock1().GetAlt4().HasBlock1())
  1812. {
  1813. Ctx.Warning(Ctx.Pos(), TIssuesIds::YQL_MISSING_IS_BEFORE_NOT_NULL) << "Missing IS keyword before NOT NULL";
  1814. }
  1815. auto isNull = BuildIsNullOp(pos, res);
  1816. Ctx.IncrementMonCounter("sql_features", notNoll ? "NotNull" : "Null");
  1817. return notNoll ? BuildUnaryOp(pos, "Not", isNull) : isNull;
  1818. }
  1819. case TRule_cond_expr::kAltCondExpr4: {
  1820. auto alt = cond.GetAlt_cond_expr4();
  1821. if (alt.HasBlock1()) {
  1822. Ctx.IncrementMonCounter("sql_features", "NotBetween");
  1823. return BuildBinaryOp(
  1824. pos,
  1825. "Or",
  1826. BuildBinaryOp(pos, "<", res, SubExpr(alt.GetRule_eq_subexpr3())),
  1827. BuildBinaryOp(pos, ">", res, SubExpr(alt.GetRule_eq_subexpr5()))
  1828. );
  1829. } else {
  1830. Ctx.IncrementMonCounter("sql_features", "Between");
  1831. return BuildBinaryOp(
  1832. pos,
  1833. "And",
  1834. BuildBinaryOp(pos, ">=", res, SubExpr(alt.GetRule_eq_subexpr3())),
  1835. BuildBinaryOp(pos, "<=", res, SubExpr(alt.GetRule_eq_subexpr5()))
  1836. );
  1837. }
  1838. }
  1839. case TRule_cond_expr::kAltCondExpr5: {
  1840. auto alt = cond.GetAlt_cond_expr5();
  1841. auto getNode = [](const TRule_cond_expr::TAlt5::TBlock1& b) -> const TRule_eq_subexpr& { return b.GetRule_eq_subexpr2(); };
  1842. return BinOpList(node.GetRule_eq_subexpr1(), getNode, alt.GetBlock1().begin(), alt.GetBlock1().end());
  1843. }
  1844. default:
  1845. Ctx.IncrementMonCounter("sql_errors", "UnknownConditionExpr");
  1846. AltNotImplemented("cond_expr", cond);
  1847. return nullptr;
  1848. }
  1849. }
  1850. return res;
  1851. }
  1852. TNodePtr TSqlExpression::BinOperList(const TString& opName, TVector<TNodePtr>::const_iterator begin, TVector<TNodePtr>::const_iterator end) const {
  1853. TPosition pos(Ctx.Pos());
  1854. const size_t opCount = end - begin;
  1855. Y_DEBUG_ABORT_UNLESS(opCount >= 2);
  1856. if (opCount == 2) {
  1857. return BuildBinaryOp(pos, opName, *begin, *(begin+1));
  1858. } if (opCount == 3) {
  1859. return BuildBinaryOp(pos, opName, BuildBinaryOp(pos, opName, *begin, *(begin+1)), *(begin+2));
  1860. } else {
  1861. auto mid = begin + opCount / 2;
  1862. return BuildBinaryOp(pos, opName, BinOperList(opName, begin, mid), BinOperList(opName, mid, end));
  1863. }
  1864. }
  1865. template <typename TNode, typename TGetNode, typename TIter>
  1866. TNodePtr TSqlExpression::BinOper(const TString& opName, const TNode& node, TGetNode getNode, TIter begin, TIter end) {
  1867. if (begin == end) {
  1868. return SubExpr(node);
  1869. }
  1870. Ctx.IncrementMonCounter("sql_binary_operations", opName);
  1871. const size_t listSize = end - begin;
  1872. TVector<TNodePtr> nodes;
  1873. nodes.reserve(1 + listSize);
  1874. nodes.push_back(SubExpr(node));
  1875. for (; begin != end; ++begin) {
  1876. nodes.push_back(SubExpr(getNode(*begin)));
  1877. }
  1878. return BinOperList(opName, nodes.begin(), nodes.end());
  1879. }
  1880. template <typename TNode, typename TGetNode, typename TIter>
  1881. TNodePtr TSqlExpression::BinOpList(const TNode& node, TGetNode getNode, TIter begin, TIter end) {
  1882. TNodePtr partialResult = SubExpr(node);
  1883. while (begin != end) {
  1884. Ctx.IncrementMonCounter("sql_features", "BinaryOperation");
  1885. Token(begin->GetToken1());
  1886. TPosition pos(Ctx.Pos());
  1887. TString opName;
  1888. auto tokenId = begin->GetToken1().GetId();
  1889. switch (tokenId) {
  1890. case SQLLexerTokens::TOKEN_LESS:
  1891. Ctx.IncrementMonCounter("sql_binary_operations", "Less");
  1892. opName = "<";
  1893. break;
  1894. case SQLLexerTokens::TOKEN_LESS_OR_EQ:
  1895. opName = "<=";
  1896. Ctx.IncrementMonCounter("sql_binary_operations", "LessOrEq");
  1897. break;
  1898. case SQLLexerTokens::TOKEN_GREATER:
  1899. opName = ">";
  1900. Ctx.IncrementMonCounter("sql_binary_operations", "Greater");
  1901. break;
  1902. case SQLLexerTokens::TOKEN_GREATER_OR_EQ:
  1903. opName = ">=";
  1904. Ctx.IncrementMonCounter("sql_binary_operations", "GreaterOrEq");
  1905. break;
  1906. case SQLLexerTokens::TOKEN_PLUS:
  1907. opName = "+";
  1908. Ctx.IncrementMonCounter("sql_binary_operations", "Plus");
  1909. break;
  1910. case SQLLexerTokens::TOKEN_MINUS:
  1911. opName = "-";
  1912. Ctx.IncrementMonCounter("sql_binary_operations", "Minus");
  1913. break;
  1914. case SQLLexerTokens::TOKEN_ASTERISK:
  1915. opName = "*";
  1916. Ctx.IncrementMonCounter("sql_binary_operations", "Multiply");
  1917. break;
  1918. case SQLLexerTokens::TOKEN_SLASH:
  1919. opName = "/";
  1920. Ctx.IncrementMonCounter("sql_binary_operations", "Divide");
  1921. if (!Ctx.PragmaClassicDivision) {
  1922. partialResult = BuildCast(Ctx, pos, partialResult, "Double");
  1923. }
  1924. break;
  1925. case SQLLexerTokens::TOKEN_PERCENT:
  1926. opName = "%";
  1927. Ctx.IncrementMonCounter("sql_binary_operations", "Mod");
  1928. break;
  1929. case SQLLexerTokens::TOKEN_EQUALS:
  1930. Ctx.IncrementMonCounter("sql_binary_operations", "Equals");
  1931. [[fallthrough]];
  1932. case SQLLexerTokens::TOKEN_EQUALS2:
  1933. Ctx.IncrementMonCounter("sql_binary_operations", "Equals2");
  1934. opName = "==";
  1935. break;
  1936. case SQLLexerTokens::TOKEN_NOT_EQUALS:
  1937. Ctx.IncrementMonCounter("sql_binary_operations", "NotEquals");
  1938. [[fallthrough]];
  1939. case SQLLexerTokens::TOKEN_NOT_EQUALS2:
  1940. Ctx.IncrementMonCounter("sql_binary_operations", "NotEquals2");
  1941. opName = "!=";
  1942. break;
  1943. case SQLLexerTokens::TOKEN_AMPERSAND:
  1944. opName = "BitAnd";
  1945. Ctx.IncrementMonCounter("sql_binary_operations", "BitAnd");
  1946. break;
  1947. case SQLLexerTokens::TOKEN_PIPE:
  1948. opName = "BitOr";
  1949. Ctx.IncrementMonCounter("sql_binary_operations", "BitOr");
  1950. break;
  1951. case SQLLexerTokens::TOKEN_CARET:
  1952. opName = "BitXor";
  1953. Ctx.IncrementMonCounter("sql_binary_operations", "BitXor");
  1954. break;
  1955. case SQLLexerTokens::TOKEN_SHIFT_LEFT:
  1956. opName = "ShiftLeft";
  1957. Ctx.IncrementMonCounter("sql_binary_operations", "ShiftLeft");
  1958. break;
  1959. case SQLLexerTokens::TOKEN_SHIFT_RIGHT:
  1960. opName = "ShiftRight";
  1961. Ctx.IncrementMonCounter("sql_binary_operations", "ShiftRight");
  1962. break;
  1963. case SQLLexerTokens::TOKEN_ROT_LEFT:
  1964. opName = "RotLeft";
  1965. Ctx.IncrementMonCounter("sql_binary_operations", "RotLeft");
  1966. break;
  1967. case SQLLexerTokens::TOKEN_ROT_RIGHT:
  1968. opName = "RotRight";
  1969. Ctx.IncrementMonCounter("sql_binary_operations", "RotRight");
  1970. break;
  1971. default:
  1972. Ctx.IncrementMonCounter("sql_errors", "UnsupportedBinaryOperation");
  1973. Error() << "Unsupported binary operation token: " << tokenId;
  1974. return nullptr;
  1975. }
  1976. partialResult = BuildBinaryOp(pos, opName, partialResult, SubExpr(getNode(*begin)));
  1977. ++begin;
  1978. }
  1979. return partialResult;
  1980. }
  1981. TNodePtr TSqlExpression::SqlInExpr(const TRule_in_expr& node) {
  1982. TSqlExpression expr(Ctx, Mode);
  1983. expr.SetSmartParenthesisMode(TSqlExpression::ESmartParenthesis::InStatement);
  1984. auto result = expr.WrapExprShortcuts(expr.UnaryExpr(node.GetRule_in_unary_subexpr1()));
  1985. return result;
  1986. }
  1987. TNodePtr TSqlExpression::SmartParenthesis(const TRule_smart_parenthesis& node) {
  1988. TVector<TNodePtr> exprs;
  1989. Token(node.GetToken1());
  1990. const TPosition pos(Ctx.Pos());
  1991. const bool isTuple = node.HasBlock3();
  1992. bool expectTuple = SmartParenthesisMode == ESmartParenthesis::InStatement;
  1993. EExpr mode = EExpr::Regular;
  1994. if (SmartParenthesisMode == ESmartParenthesis::GroupBy) {
  1995. mode = EExpr::GroupBy;
  1996. } else if (SmartParenthesisMode == ESmartParenthesis::SqlLambdaParams) {
  1997. mode = EExpr::SqlLambdaParams;
  1998. expectTuple = true;
  1999. }
  2000. if (node.HasBlock2() && !NamedExprList(node.GetBlock2().GetRule_named_expr_list1(), exprs, mode)) {
  2001. return {};
  2002. }
  2003. bool hasAliases = false;
  2004. bool hasUnnamed = false;
  2005. for (const auto& expr: exprs) {
  2006. if (expr->GetLabel()) {
  2007. hasAliases = true;
  2008. } else {
  2009. hasUnnamed = true;
  2010. }
  2011. if (hasAliases && hasUnnamed && SmartParenthesisMode != ESmartParenthesis::GroupBy) {
  2012. Ctx.IncrementMonCounter("sql_errors", "AnonymousStructMembers");
  2013. Ctx.Error(pos) << "Structure does not allow anonymous members";
  2014. return nullptr;
  2015. }
  2016. }
  2017. if (exprs.size() == 1 && hasUnnamed && !isTuple && !expectTuple) {
  2018. return exprs.back();
  2019. }
  2020. if (SmartParenthesisMode == ESmartParenthesis::GroupBy) {
  2021. /// \todo support nested tuple\struct
  2022. if (isTuple) {
  2023. Ctx.IncrementMonCounter("sql_errors", "SimpleTupleInGroupBy");
  2024. Ctx.Error(pos) << "Unable to use tuple in group by clause";
  2025. return nullptr;
  2026. }
  2027. Ctx.IncrementMonCounter("sql_features", "ListOfNamedNode");
  2028. return BuildListOfNamedNodes(pos, std::move(exprs));
  2029. }
  2030. Ctx.IncrementMonCounter("sql_features", hasUnnamed ? "SimpleTuple" : "SimpleStruct");
  2031. return hasUnnamed || expectTuple ? BuildTuple(pos, exprs) : BuildStructure(pos, exprs);
  2032. }
  2033. TNodePtr TSqlTranslation::NamedNode(const TRule_named_nodes_stmt& rule, TVector<TString>& names) {
  2034. // named_nodes_stmt: bind_parameter_list EQUALS (expr | LPAREN select_stmt RPAREN);
  2035. BindList(rule.GetRule_bind_parameter_list1(), names);
  2036. TNodePtr nodeExpr = nullptr;
  2037. switch (rule.GetBlock3().Alt_case()) {
  2038. case TRule_named_nodes_stmt::TBlock3::kAlt1: {
  2039. TSqlExpression expr(Ctx, Mode);
  2040. return expr.Build(rule.GetBlock3().GetAlt1().GetRule_expr1());
  2041. }
  2042. case TRule_named_nodes_stmt::TBlock3::kAlt2: {
  2043. TSqlSelect expr(Ctx, Mode);
  2044. TPosition pos;
  2045. auto source = expr.Build(rule.GetBlock3().GetAlt2().GetRule_select_stmt2(), pos);
  2046. if (!source) {
  2047. return {};
  2048. }
  2049. return BuildSourceNode(pos, std::move(source));
  2050. }
  2051. default:
  2052. AltNotImplemented("named_node", rule.GetBlock3());
  2053. Ctx.IncrementMonCounter("sql_errors", "UnknownNamedNode");
  2054. return nullptr;
  2055. }
  2056. }
  2057. bool TSqlTranslation::ImportStatement(const TRule_import_stmt& stmt, TVector<TString>* namesPtr) {
  2058. TVector<TString> modulePath;
  2059. if (!ModulePath(stmt.GetRule_module_path2(), modulePath)) {
  2060. return false;
  2061. }
  2062. TVector<TNodePtr> bindNames;
  2063. if (!NamedBindList(stmt.GetRule_named_bind_parameter_list4(), bindNames)) {
  2064. return false;
  2065. }
  2066. const TString moduleAlias = Ctx.AddImport(std::move(modulePath));
  2067. if (!moduleAlias) {
  2068. return false;
  2069. }
  2070. for (const TNodePtr& name: bindNames) {
  2071. const TString* contentPtr = name->GetAtomContent();
  2072. YQL_ENSURE(contentPtr);
  2073. const TString& nameAlias = name->GetLabel();
  2074. const auto varName = nameAlias ? nameAlias : *contentPtr;
  2075. PushNamedNode(varName, name->Y("bind", moduleAlias, name->Q(*contentPtr)));
  2076. if (namesPtr) {
  2077. namesPtr->push_back(varName);
  2078. }
  2079. }
  2080. return true;
  2081. }
  2082. TNodePtr TSqlTranslation::DoStatement(const TRule_do_stmt& stmt, bool makeLambda, const TVector<TString>& args) {
  2083. TNodePtr action;
  2084. switch (stmt.GetBlock2().GetAltCase()) {
  2085. case TRule_do_stmt_TBlock2::kAlt1: {
  2086. auto bindName = NamedNodeImpl(stmt.GetBlock2().GetAlt1().GetRule_bind_parameter1(), *this);
  2087. action = GetNamedNode(bindName);
  2088. if (!action) {
  2089. return nullptr;
  2090. }
  2091. break;
  2092. }
  2093. case TRule_do_stmt_TBlock2::kAlt2:
  2094. action = BuildEmptyAction(Ctx.Pos());
  2095. break;
  2096. default:
  2097. Ctx.IncrementMonCounter("sql_errors", "UnknownDoStmt");
  2098. AltNotImplemented("do_stmt", stmt.GetBlock2());
  2099. return nullptr;
  2100. }
  2101. TVector<TNodePtr> values;
  2102. values.push_back(new TAstAtomNodeImpl(Ctx.Pos(), "Apply", TNodeFlags::Default));
  2103. values.push_back(action);
  2104. values.push_back(new TAstAtomNodeImpl(Ctx.Pos(), "world", TNodeFlags::Default));
  2105. TSqlExpression sqlExpr(Ctx, Mode);
  2106. if (stmt.HasBlock4() && !ExprList(sqlExpr, values, stmt.GetBlock4().GetRule_expr_list1())) {
  2107. return nullptr;
  2108. }
  2109. TNodePtr apply = new TAstListNodeImpl(Ctx.Pos(), std::move(values));
  2110. if (!makeLambda) {
  2111. return BuildDoCall(Ctx.Pos(), apply);
  2112. }
  2113. TNodePtr params = new TAstListNodeImpl(Ctx.Pos());
  2114. params->Add("world");
  2115. for (const auto& arg : args) {
  2116. params->Add(new TAstAtomNodeImpl(Ctx.Pos(), arg, TNodeFlags::ArbitraryContent));
  2117. }
  2118. return BuildDoCall(Ctx.Pos(), BuildLambda(Ctx.Pos(), params, apply));
  2119. }
  2120. bool TSqlSelect::JoinOp(ISource* join, const TRule_join_source::TBlock2& block) {
  2121. const auto& node = block.GetRule_join_op1();
  2122. switch (node.Alt_case()) {
  2123. case TRule_join_op::kAltJoinOp1:
  2124. Ctx.IncrementMonCounter("sql_join_operations", "CartesianProduct");
  2125. Error() << "Cartesian product of tables is forbidden";
  2126. return false;
  2127. case TRule_join_op::kAltJoinOp2: {
  2128. auto alt = node.GetAlt_join_op2();
  2129. if (alt.HasBlock1()) {
  2130. Ctx.IncrementMonCounter("sql_join_operations", "Natural");
  2131. Error() << "Natural join is not implemented yet";
  2132. return false;
  2133. }
  2134. TString joinOp("Inner");
  2135. switch (alt.GetBlock2().Alt_case()) {
  2136. case TRule_join_op::TAlt2::TBlock2::kAlt1:
  2137. if (alt.GetBlock2().GetAlt1().HasBlock1()) {
  2138. auto block = alt.GetBlock2().GetAlt1().GetBlock1();
  2139. switch (block.Alt_case()) {
  2140. case TRule_join_op_TAlt2_TBlock2_TAlt1_TBlock1::kAlt1:
  2141. // left
  2142. joinOp = Token(block.GetAlt1().GetToken1());
  2143. if (block.GetAlt1().HasBlock2()) {
  2144. joinOp += " " + Token(block.GetAlt1().GetBlock2().GetToken1());
  2145. }
  2146. break;
  2147. case TRule_join_op_TAlt2_TBlock2_TAlt1_TBlock1::kAlt2:
  2148. // right
  2149. joinOp = Token(block.GetAlt2().GetToken1());
  2150. if (block.GetAlt2().HasBlock2()) {
  2151. joinOp += " " + Token(block.GetAlt2().GetBlock2().GetToken1());
  2152. }
  2153. break;
  2154. case TRule_join_op_TAlt2_TBlock2_TAlt1_TBlock1::kAlt3:
  2155. // exclusion
  2156. joinOp = Token(block.GetAlt3().GetToken1());
  2157. break;
  2158. case TRule_join_op_TAlt2_TBlock2_TAlt1_TBlock1::kAlt4:
  2159. // full
  2160. joinOp = Token(block.GetAlt4().GetToken1());
  2161. break;
  2162. default:
  2163. Ctx.IncrementMonCounter("sql_errors", "UnknownJoinOperation");
  2164. AltNotImplemented("join_op", node);
  2165. return false;
  2166. }
  2167. }
  2168. break;
  2169. case TRule_join_op::TAlt2::TBlock2::kAlt2:
  2170. joinOp = Token(alt.GetBlock2().GetAlt2().GetToken1());
  2171. break;
  2172. case TRule_join_op::TAlt2::TBlock2::kAlt3:
  2173. joinOp = Token(alt.GetBlock2().GetAlt3().GetToken1());
  2174. break;
  2175. default:
  2176. Ctx.IncrementMonCounter("sql_errors", "UnknownJoinOperation");
  2177. AltNotImplemented("join_op", node);
  2178. return false;
  2179. }
  2180. joinOp = NormalizeJoinOp(joinOp);
  2181. Ctx.IncrementMonCounter("sql_features", "Join");
  2182. Ctx.IncrementMonCounter("sql_join_operations", joinOp);
  2183. TNodePtr joinKeyExpr;
  2184. if (block.HasBlock3()) {
  2185. if (joinOp == "Cross") {
  2186. Error() << "Cross join should not have ON or USING expression";
  2187. Ctx.IncrementMonCounter("sql_errors", "BadJoinExpr");
  2188. return false;
  2189. }
  2190. joinKeyExpr = JoinExpr(join, block.GetBlock3().GetRule_join_constraint1());
  2191. if (!joinKeyExpr) {
  2192. Ctx.IncrementMonCounter("sql_errors", "BadJoinExpr");
  2193. return false;
  2194. }
  2195. }
  2196. else {
  2197. if (joinOp != "Cross") {
  2198. Error() << "Expected ON or USING expression";
  2199. Ctx.IncrementMonCounter("sql_errors", "BadJoinExpr");
  2200. return false;
  2201. }
  2202. }
  2203. Y_DEBUG_ABORT_UNLESS(join->GetJoin());
  2204. join->GetJoin()->SetupJoin(joinOp, joinKeyExpr);
  2205. break;
  2206. }
  2207. default:
  2208. Ctx.IncrementMonCounter("sql_errors", "UnknownJoinOperation2");
  2209. AltNotImplemented("join_op", node);
  2210. return false;
  2211. }
  2212. return true;
  2213. }
  2214. TNodePtr TSqlSelect::JoinExpr(ISource* join, const TRule_join_constraint& node) {
  2215. switch (node.Alt_case()) {
  2216. case TRule_join_constraint::kAltJoinConstraint1: {
  2217. auto& alt = node.GetAlt_join_constraint1();
  2218. Token(alt.GetToken1());
  2219. TSqlExpression expr(Ctx, Mode);
  2220. return expr.Build(alt.GetRule_expr2());
  2221. }
  2222. case TRule_join_constraint::kAltJoinConstraint2: {
  2223. auto& alt = node.GetAlt_join_constraint2();
  2224. Token(alt.GetToken1());
  2225. TPosition pos(Ctx.Pos());
  2226. TVector<TDeferredAtom> names;
  2227. if (!PureColumnOrNamedListStr(alt.GetRule_pure_column_or_named_list2(), *this, names)) {
  2228. return nullptr;
  2229. }
  2230. Y_DEBUG_ABORT_UNLESS(join->GetJoin());
  2231. return join->GetJoin()->BuildJoinKeys(Ctx, names);
  2232. }
  2233. default:
  2234. Ctx.IncrementMonCounter("sql_errors", "UnknownJoinConstraint");
  2235. AltNotImplemented("join_constraint", node);
  2236. break;
  2237. }
  2238. return nullptr;
  2239. }
  2240. TVector<TNodePtr> TSqlSelect::OrdinaryNamedColumnList(const TRule_ordinary_named_column_list& node) {
  2241. TVector<TNodePtr> result;
  2242. switch (node.Alt_case()) {
  2243. case TRule_ordinary_named_column_list::kAltOrdinaryNamedColumnList1:
  2244. if (!NamedColumn(result, node.GetAlt_ordinary_named_column_list1().GetRule_named_column1())) {
  2245. return {};
  2246. }
  2247. break;
  2248. case TRule_ordinary_named_column_list::kAltOrdinaryNamedColumnList2:
  2249. if (!NamedColumnList(result, node.GetAlt_ordinary_named_column_list2().GetRule_named_column_list2())) {
  2250. return {};
  2251. }
  2252. break;
  2253. default:
  2254. Ctx.IncrementMonCounter("sql_errors", "UnknownOrdinaryNamedColumn");
  2255. AltNotImplemented("ordinary_named_column_list", node);
  2256. }
  2257. return result;
  2258. }
  2259. TSourcePtr TSqlSelect::FlattenSource(const TRule_flatten_source& node) {
  2260. auto source = NamedSingleSource(node.GetRule_named_single_source1());
  2261. if (!source) {
  2262. return nullptr;
  2263. }
  2264. if (node.HasBlock2()) {
  2265. auto flatten = node.GetBlock2();
  2266. auto flatten2 = flatten.GetBlock2();
  2267. switch (flatten2.Alt_case()) {
  2268. case TRule_flatten_source::TBlock2::TBlock2::kAlt1: {
  2269. TString mode = "auto";
  2270. if (flatten2.GetAlt1().HasBlock1()) {
  2271. mode = to_lower(Token(flatten2.GetAlt1().GetBlock1().GetToken1()));
  2272. }
  2273. auto flattenColumns = OrdinaryNamedColumnList(flatten2.GetAlt1().GetRule_ordinary_named_column_list3());
  2274. if (flattenColumns.empty()) {
  2275. return nullptr;
  2276. }
  2277. Ctx.IncrementMonCounter("sql_features", "FlattenByColumns");
  2278. if (!source->AddExpressions(Ctx, flattenColumns, EExprSeat::FlattenBy)) {
  2279. return nullptr;
  2280. }
  2281. source->SetFlattenByMode(mode);
  2282. break;
  2283. }
  2284. case TRule_flatten_source::TBlock2::TBlock2::kAlt2: {
  2285. Ctx.IncrementMonCounter("sql_features", "FlattenColumns");
  2286. source->MarkFlattenColumns();
  2287. break;
  2288. }
  2289. default:
  2290. Ctx.IncrementMonCounter("sql_errors", "UnknownOrdinaryNamedColumn");
  2291. AltNotImplemented("flatten_source", flatten2);
  2292. }
  2293. }
  2294. return source;
  2295. }
  2296. TSourcePtr TSqlSelect::JoinSource(const TRule_join_source& node) {
  2297. TSourcePtr source(FlattenSource(node.GetRule_flatten_source1()));
  2298. if (!source) {
  2299. return nullptr;
  2300. }
  2301. if (node.Block2Size()) {
  2302. TPosition pos(Ctx.Pos());
  2303. TVector<TSourcePtr> sources;
  2304. sources.emplace_back(std::move(source));
  2305. for (auto& block: node.GetBlock2()) {
  2306. sources.emplace_back(FlattenSource(block.GetRule_flatten_source2()));
  2307. if (!sources.back()) {
  2308. Ctx.IncrementMonCounter("sql_errors", "NoJoinWith");
  2309. return nullptr;
  2310. }
  2311. }
  2312. source = BuildEquiJoin(pos, std::move(sources));
  2313. for (auto& block: node.GetBlock2()) {
  2314. if (!JoinOp(source.Get(), block)) {
  2315. Ctx.IncrementMonCounter("sql_errors", "NoJoinOp");
  2316. return nullptr;
  2317. }
  2318. }
  2319. }
  2320. return source;
  2321. }
  2322. bool TSqlSelect::SelectTerm(TVector<TNodePtr>& terms, const TRule_result_column& node) {
  2323. // result_column:
  2324. // opt_id_prefix ASTERISK
  2325. // | expr (AS id_or_string)?
  2326. // ;
  2327. switch (node.Alt_case()) {
  2328. case TRule_result_column::kAltResultColumn1: {
  2329. auto alt = node.GetAlt_result_column1();
  2330. Token(alt.GetToken2());
  2331. auto idAsteriskQualify = OptIdPrefixAsStr(alt.GetRule_opt_id_prefix1(), *this);
  2332. Ctx.IncrementMonCounter("sql_features", idAsteriskQualify ? "QualifyAsterisk" : "Asterisk");
  2333. terms.push_back(BuildColumn(Ctx.Pos(), "*", idAsteriskQualify));
  2334. break;
  2335. }
  2336. case TRule_result_column::kAltResultColumn2: {
  2337. auto alt = node.GetAlt_result_column2();
  2338. TSqlExpression expr(Ctx, Mode);
  2339. TNodePtr term(expr.Build(alt.GetRule_expr1()));
  2340. if (!term) {
  2341. Ctx.IncrementMonCounter("sql_errors", "NoTerm");
  2342. return false;
  2343. }
  2344. if (alt.HasBlock2()) {
  2345. term->SetLabel(IdOrString(alt.GetBlock2().GetRule_id_or_string2(), *this));
  2346. }
  2347. terms.push_back(term);
  2348. break;
  2349. }
  2350. default:
  2351. Ctx.IncrementMonCounter("sql_errors", "UnknownResultColumn");
  2352. AltNotImplemented("result_column", node);
  2353. return false;
  2354. }
  2355. return true;
  2356. }
  2357. bool TSqlSelect::ValidateSelectColumns(const TVector<TNodePtr>& terms) {
  2358. TSet<TString> labels;
  2359. TSet<TString> asteriskSources;
  2360. for (const auto& term: terms) {
  2361. const auto& label = term->GetLabel();
  2362. if (!Ctx.PragmaAllowDotInAlias && label.find('.') != TString::npos) {
  2363. Ctx.Error(term->GetPos()) << "Unable to use '.' in column name. Invalid column name: " << label;
  2364. return false;
  2365. }
  2366. if (!label.empty()) {
  2367. if (!labels.insert(label).second) {
  2368. Ctx.Error(term->GetPos()) << "Unable to use duplicate column names. Collision in name: " << label;
  2369. return false;
  2370. }
  2371. }
  2372. if (term->IsAsterisk()) {
  2373. const auto& source = *term->GetSourceName();
  2374. if (source.empty() && terms.ysize() > 1) {
  2375. Ctx.Error(term->GetPos()) << "Unable to use general '*' with other columns, either specify concrete table like '<table>.*', either specify concrete columns.";
  2376. return false;
  2377. } else if (!asteriskSources.insert(source).second) {
  2378. Ctx.Error(term->GetPos()) << "Unable to use twice same quialified asterisk. Invalid source: " << source;
  2379. return false;
  2380. }
  2381. } else if (label.empty()) {
  2382. const auto* column = term->GetColumnName();
  2383. if (column && !column->empty()) {
  2384. const auto& source = *term->GetSourceName();
  2385. const auto usedName = source.empty() ? *column : source + '.' + *column;
  2386. if (!labels.insert(usedName).second) {
  2387. Ctx.Error(term->GetPos()) << "Unable to use duplicate column names. Collision in name: " << usedName;
  2388. return false;
  2389. }
  2390. }
  2391. }
  2392. }
  2393. return true;
  2394. }
  2395. TSourcePtr TSqlSelect::SingleSource(const TRule_single_source& node) {
  2396. switch (node.Alt_case()) {
  2397. case TRule_single_source::kAltSingleSource1: {
  2398. const auto& alt = node.GetAlt_single_source1();
  2399. const auto& table_ref = alt.GetRule_table_ref1();
  2400. if (auto maybeSource = AsTableImpl(table_ref)) {
  2401. auto source = *maybeSource;
  2402. if (!source) {
  2403. return nullptr;
  2404. }
  2405. if (!source->Init(Ctx, source.Get())) {
  2406. return nullptr;
  2407. }
  2408. return source;
  2409. } else {
  2410. TTableRef table(TableRefImpl(alt.GetRule_table_ref1()));
  2411. TPosition pos(Ctx.Pos());
  2412. Ctx.IncrementMonCounter("sql_select_clusters", table.Cluster);
  2413. if (!table.Check(Ctx)) {
  2414. return nullptr;
  2415. }
  2416. const auto serviceName = to_lower(table.ServiceName(Ctx));
  2417. const bool stream = serviceName == RtmrProviderName;
  2418. return BuildTableSource(pos, table, stream);
  2419. }
  2420. }
  2421. case TRule_single_source::kAltSingleSource2: {
  2422. const auto& alt = node.GetAlt_single_source2();
  2423. Token(alt.GetToken1());
  2424. TSqlSelect innerSelect(Ctx, Mode);
  2425. TPosition pos;
  2426. auto source = innerSelect.Build(alt.GetRule_select_stmt2(), pos);
  2427. if (!source) {
  2428. return nullptr;
  2429. }
  2430. return BuildInnerSource(pos, BuildSourceNode(pos, std::move(source)));
  2431. }
  2432. case TRule_single_source::kAltSingleSource3: {
  2433. const auto& alt = node.GetAlt_single_source3();
  2434. Ctx.IncrementMonCounter("sql_features", "NamedNodeUseSource");
  2435. auto named = NamedNodeImpl(alt.GetRule_bind_parameter2(), *this);
  2436. auto at = alt.HasBlock1();
  2437. if (at) {
  2438. if (alt.HasBlock3()) {
  2439. Ctx.Error() << "Subquery must not be used as anonymous table name";
  2440. return nullptr;
  2441. }
  2442. auto namedNode = GetNamedNode(named);
  2443. if (!namedNode) {
  2444. return nullptr;
  2445. }
  2446. auto source = TryMakeSourceFromExpression(Ctx, namedNode, "@");
  2447. if (!source) {
  2448. Ctx.Error() << "Cannot infer cluster and table name";
  2449. return nullptr;
  2450. }
  2451. return source;
  2452. }
  2453. auto node = GetNamedNode(named);
  2454. if (!node) {
  2455. Ctx.IncrementMonCounter("sql_errors", "NamedNodeSourceError");
  2456. return nullptr;
  2457. }
  2458. if (alt.HasBlock3()) {
  2459. TVector<TNodePtr> values;
  2460. values.push_back(new TAstAtomNodeImpl(Ctx.Pos(), "Apply", TNodeFlags::Default));
  2461. values.push_back(node);
  2462. values.push_back(new TAstAtomNodeImpl(Ctx.Pos(), "world", TNodeFlags::Default));
  2463. TSqlExpression sqlExpr(Ctx, Mode);
  2464. if (alt.GetBlock3().HasBlock2() && !ExprList(sqlExpr, values, alt.GetBlock3().GetBlock2().GetRule_expr_list1())) {
  2465. return nullptr;
  2466. }
  2467. TNodePtr apply = new TAstListNodeImpl(Ctx.Pos(), std::move(values));
  2468. return BuildNodeSource(Ctx.Pos(), apply);
  2469. }
  2470. return BuildInnerSource(Ctx.Pos(), node);
  2471. }
  2472. default:
  2473. AltNotImplemented("single_source", node);
  2474. Ctx.IncrementMonCounter("sql_errors", "UnknownSingleSource");
  2475. return nullptr;
  2476. }
  2477. }
  2478. TSourcePtr TSqlSelect::NamedSingleSource(const TRule_named_single_source& node) {
  2479. auto singleSource = SingleSource(node.GetRule_single_source1());
  2480. if (!singleSource) {
  2481. return nullptr;
  2482. }
  2483. if (node.HasBlock2()) {
  2484. const auto label = IdOrString(node.GetBlock2().GetRule_id_or_string2(), *this);
  2485. singleSource->SetLabel(label);
  2486. }
  2487. if (node.HasBlock3()) {
  2488. ESampleMode mode = ESampleMode::Auto;
  2489. TSqlExpression expr(Ctx, Mode);
  2490. TNodePtr samplingRateNode;
  2491. TNodePtr samplingSeedNode;
  2492. const auto& sampleBlock = node.GetBlock3();
  2493. TPosition pos;
  2494. switch (sampleBlock.Alt_case()) {
  2495. case TRule_named_single_source::TBlock3::kAlt1:
  2496. {
  2497. const auto& sampleExpr = sampleBlock.GetAlt1().GetRule_sample_clause1().GetRule_expr2();
  2498. samplingRateNode = expr.Build(sampleExpr);
  2499. if (!samplingRateNode) {
  2500. return nullptr;
  2501. }
  2502. pos = GetPos(sampleBlock.GetAlt1().GetRule_sample_clause1().GetToken1());
  2503. Ctx.IncrementMonCounter("sql_features", "SampleClause");
  2504. }
  2505. break;
  2506. case TRule_named_single_source::TBlock3::kAlt2:
  2507. {
  2508. const auto& tableSampleClause = sampleBlock.GetAlt2().GetRule_tablesample_clause1();
  2509. const auto& modeToken = tableSampleClause.GetRule_sampling_mode2().GetToken1();
  2510. const TCiString& token = Token(modeToken);
  2511. if (token == "system") {
  2512. mode = ESampleMode::System;
  2513. } else if (token == "bernoulli") {
  2514. mode = ESampleMode::Bernoulli;
  2515. } else {
  2516. Ctx.Error(GetPos(modeToken)) << "Unsupported sampling mode: " << token;
  2517. Ctx.IncrementMonCounter("sql_errors", "UnsupportedSamplingMode");
  2518. return nullptr;
  2519. }
  2520. const auto& tableSampleExpr = tableSampleClause.GetRule_expr4();
  2521. samplingRateNode = expr.Build(tableSampleExpr);
  2522. if (!samplingRateNode) {
  2523. return nullptr;
  2524. }
  2525. if (tableSampleClause.HasBlock6()) {
  2526. const auto& repeatableExpr = tableSampleClause.GetBlock6().GetRule_repeatable_clause1().GetRule_expr3();
  2527. samplingSeedNode = expr.Build(repeatableExpr);
  2528. if (!samplingSeedNode) {
  2529. return nullptr;
  2530. }
  2531. }
  2532. pos = GetPos(sampleBlock.GetAlt2().GetRule_tablesample_clause1().GetToken1());
  2533. Ctx.IncrementMonCounter("sql_features", "SampleClause");
  2534. }
  2535. break;
  2536. default:
  2537. Y_ABORT("SampleClause: does not corresond to grammar changes");
  2538. }
  2539. if (!singleSource->SetSamplingOptions(Ctx, pos, mode, samplingRateNode, samplingSeedNode)) {
  2540. Ctx.IncrementMonCounter("sql_errors", "IncorrectSampleClause");
  2541. return nullptr;
  2542. }
  2543. }
  2544. return singleSource;
  2545. }
  2546. bool TSqlSelect::ColumnName(TVector<TNodePtr>& keys, const TRule_column_name& node) {
  2547. const auto sourceName = OptIdPrefixAsStr(node.GetRule_opt_id_prefix1(), *this);
  2548. const auto columnName = IdOrString(node.GetRule_id_or_string2(), *this);
  2549. YQL_ENSURE(!columnName.empty());
  2550. keys.push_back(BuildColumn(Ctx.Pos(), columnName, sourceName));
  2551. return true;
  2552. }
  2553. bool TSqlSelect::ColumnList(TVector<TNodePtr>& keys, const TRule_column_list& node) {
  2554. if (!ColumnName(keys, node.GetRule_column_name1())) {
  2555. return false;
  2556. }
  2557. for (auto b: node.GetBlock2()) {
  2558. Token(b.GetToken1());
  2559. if (!ColumnName(keys, b.GetRule_column_name2())) {
  2560. return false;
  2561. }
  2562. }
  2563. return true;
  2564. }
  2565. bool TSqlSelect::NamedColumn(TVector<TNodePtr>& columnList, const TRule_named_column& node) {
  2566. if (!ColumnName(columnList, node.GetRule_column_name1())) {
  2567. return false;
  2568. }
  2569. if (node.HasBlock2()) {
  2570. const auto label = IdOrString(node.GetBlock2().GetRule_id_or_string2(), *this);
  2571. columnList.back()->SetLabel(label);
  2572. }
  2573. return true;
  2574. }
  2575. bool TSqlSelect::NamedColumnList(TVector<TNodePtr>& columnList, const TRule_named_column_list& node) {
  2576. if (!NamedColumn(columnList, node.GetRule_named_column1())) {
  2577. return false;
  2578. }
  2579. for (auto b: node.GetBlock2()) {
  2580. if (!NamedColumn(columnList, b.GetRule_named_column2())) {
  2581. return false;
  2582. }
  2583. }
  2584. return true;
  2585. }
  2586. bool TSqlSelect::SortSpecification(const TRule_sort_specification& node, TVector<TSortSpecificationPtr>& sortSpecs) {
  2587. bool asc = true;
  2588. TSqlExpression expr(Ctx, Mode);
  2589. TNodePtr exprNode = expr.Build(node.GetRule_expr1());
  2590. if (!exprNode) {
  2591. return false;
  2592. }
  2593. if (node.HasBlock2()) {
  2594. const auto& token = node.GetBlock2().GetToken1();
  2595. Token(token);
  2596. switch (token.GetId()) {
  2597. case SQLLexerTokens::TOKEN_ASC:
  2598. Ctx.IncrementMonCounter("sql_features", "OrderByAsc");
  2599. break;
  2600. case SQLLexerTokens::TOKEN_DESC:
  2601. asc = false;
  2602. Ctx.IncrementMonCounter("sql_features", "OrderByDesc");
  2603. break;
  2604. default:
  2605. Ctx.IncrementMonCounter("sql_errors", "UnknownOrderBy");
  2606. Error() << "Unsupported direction token: " << token.GetId();
  2607. return false;
  2608. }
  2609. } else {
  2610. Ctx.IncrementMonCounter("sql_features", "OrderByDefault");
  2611. }
  2612. auto sortSpecPtr = MakeIntrusive<TSortSpecification>();
  2613. sortSpecPtr->OrderExpr = exprNode;
  2614. sortSpecPtr->Ascending = asc;
  2615. sortSpecs.emplace_back(sortSpecPtr);
  2616. return true;
  2617. }
  2618. bool TSqlSelect::SortSpecificationList(const TRule_sort_specification_list& node, TVector<TSortSpecificationPtr>& sortSpecs) {
  2619. if (!SortSpecification(node.GetRule_sort_specification1(), sortSpecs)) {
  2620. return false;
  2621. }
  2622. for (auto sortSpec: node.GetBlock2()) {
  2623. Token(sortSpec.GetToken1());
  2624. if (!SortSpecification(sortSpec.GetRule_sort_specification2(), sortSpecs)) {
  2625. return false;
  2626. }
  2627. }
  2628. return true;
  2629. }
  2630. TSourcePtr TSqlSelect::ProcessCore(const TRule_process_core& node, const TWriteSettings& settings, TPosition& selectPos) {
  2631. // PROCESS STREAM? named_single_source (COMMA named_single_source)* (USING call_expr (AS id_or_string)?
  2632. // (WHERE expr)? (HAVING expr)?)?
  2633. Token(node.GetToken1());
  2634. TPosition startPos(Ctx.Pos());
  2635. const bool stream = node.HasBlock2();
  2636. if (!selectPos) {
  2637. selectPos = startPos;
  2638. }
  2639. TSourcePtr source(NamedSingleSource(node.GetRule_named_single_source3()));
  2640. if (!source) {
  2641. return nullptr;
  2642. }
  2643. if (node.GetBlock4().size()) {
  2644. TVector<TSourcePtr> sources(1, source);
  2645. for (auto& s: node.GetBlock4()) {
  2646. sources.push_back(NamedSingleSource(s.GetRule_named_single_source2()));
  2647. if (!sources.back()) {
  2648. return nullptr;
  2649. }
  2650. }
  2651. auto pos = source->GetPos();
  2652. source = BuildMuxSource(pos, std::move(sources));
  2653. }
  2654. bool hasUsing = node.HasBlock5();
  2655. if (!hasUsing) {
  2656. return BuildProcess(startPos, std::move(source), nullptr, {}, true, stream, settings);
  2657. }
  2658. const auto& block5 = node.GetBlock5();
  2659. if (block5.HasBlock4()) {
  2660. TSqlExpression expr(Ctx, Mode);
  2661. TNodePtr where = expr.Build(block5.GetBlock4().GetRule_expr2());
  2662. if (!where || !source->AddFilter(Ctx, where)) {
  2663. return nullptr;
  2664. }
  2665. Ctx.IncrementMonCounter("sql_features", "ProcessWhere");
  2666. } else {
  2667. Ctx.IncrementMonCounter("sql_features", stream ? "ProcessStream" : "Process");
  2668. }
  2669. if (block5.HasBlock5()) {
  2670. Ctx.Error() << "PROCESS does not allow HAVING yet! You may request it on yql@ maillist.";
  2671. return nullptr;
  2672. }
  2673. /// \todo other solution
  2674. PushNamedNode(TArgPlaceholderNode::ProcessRows, BuildArgPlaceholder(Ctx.Pos(), TArgPlaceholderNode::ProcessRows));
  2675. PushNamedNode(TArgPlaceholderNode::ProcessRow, BuildArgPlaceholder(Ctx.Pos(), TArgPlaceholderNode::ProcessRow));
  2676. bool listCall = false;
  2677. TSqlCallExpr call(Ctx, Mode);
  2678. bool initRet = call.Init(block5.GetRule_call_expr2());
  2679. if (initRet) {
  2680. call.IncCounters();
  2681. }
  2682. PopNamedNode(TArgPlaceholderNode::ProcessRows);
  2683. PopNamedNode(TArgPlaceholderNode::ProcessRow);
  2684. if (!initRet) {
  2685. return nullptr;
  2686. }
  2687. auto args = call.GetArgs();
  2688. /// SIN: special processing of binds
  2689. for (auto& arg: args) {
  2690. auto placeholder = dynamic_cast<TArgPlaceholderNode*>(arg.Get());
  2691. if (placeholder) {
  2692. auto name = placeholder->GetName();
  2693. if (name == TArgPlaceholderNode::ProcessRows) {
  2694. if (listCall) {
  2695. Ctx.Error(arg->GetPos()) << "Only single instance of " << name << " is allowed.";
  2696. return nullptr;
  2697. }
  2698. listCall = true;
  2699. arg = new TAstAtomNodeImpl(arg->GetPos(), "inputRowsList", 0);
  2700. } else if (name == TArgPlaceholderNode::ProcessRow) {
  2701. arg = BuildColumn(arg->GetPos(), "*");
  2702. }
  2703. }
  2704. }
  2705. TSqlCallExpr finalCall(call, args);
  2706. TNodePtr with(finalCall.BuildUdf(true));
  2707. if (!with || !finalCall.EnsureNotDistinct("PROCESS")) {
  2708. return {};
  2709. }
  2710. args = finalCall.GetArgs();
  2711. if (block5.HasBlock3()) {
  2712. with->SetLabel(IdOrString(block5.GetBlock3().GetRule_id_or_string2(), *this));
  2713. }
  2714. return BuildProcess(startPos, std::move(source), with, std::move(args), listCall, stream, settings);
  2715. }
  2716. TSourcePtr TSqlSelect::ReduceCore(const TRule_reduce_core& node, const TWriteSettings& settings, TPosition& selectPos) {
  2717. // REDUCE named_single_source (COMMA named_single_source)* (PRESORT sort_specification_list)?
  2718. // ON column_list USING ALL? call_expr (AS id_or_string)?
  2719. // (WHERE expr)? (HAVING expr)?
  2720. Token(node.GetToken1());
  2721. TPosition startPos(Ctx.Pos());
  2722. if (!selectPos) {
  2723. selectPos = startPos;
  2724. }
  2725. TSourcePtr source(NamedSingleSource(node.GetRule_named_single_source2()));
  2726. if (!source) {
  2727. return {};
  2728. }
  2729. if (node.GetBlock3().size()) {
  2730. TVector<TSourcePtr> sources(1, source);
  2731. for (auto& s: node.GetBlock3()) {
  2732. sources.push_back(NamedSingleSource(s.GetRule_named_single_source2()));
  2733. if (!sources.back()) {
  2734. return nullptr;
  2735. }
  2736. }
  2737. auto pos = source->GetPos();
  2738. source = BuildMuxSource(pos, std::move(sources));
  2739. }
  2740. TVector<TSortSpecificationPtr> orderBy;
  2741. if (node.HasBlock4()) {
  2742. if (!SortSpecificationList(node.GetBlock4().GetRule_sort_specification_list2(), orderBy)) {
  2743. return {};
  2744. }
  2745. }
  2746. TVector<TNodePtr> keys;
  2747. if (!ColumnList(keys, node.GetRule_column_list6())) {
  2748. return nullptr;
  2749. }
  2750. if (node.HasBlock11()) {
  2751. TSqlExpression expr(Ctx, Mode);
  2752. TNodePtr where = expr.Build(node.GetBlock11().GetRule_expr2());
  2753. if (!where || !source->AddFilter(Ctx, where)) {
  2754. return nullptr;
  2755. }
  2756. Ctx.IncrementMonCounter("sql_features", "ReduceWhere");
  2757. } else {
  2758. Ctx.IncrementMonCounter("sql_features", "Reduce");
  2759. }
  2760. TNodePtr having;
  2761. if (node.HasBlock12()) {
  2762. TSqlExpression expr(Ctx, Mode);
  2763. having = expr.Build(node.GetBlock12().GetRule_expr2());
  2764. if (!having) {
  2765. return nullptr;
  2766. }
  2767. }
  2768. PushNamedNode(TArgPlaceholderNode::ProcessRow, BuildColumn(Ctx.Pos(), "*"));
  2769. TSqlCallExpr call(Ctx, Mode);
  2770. bool initRet = call.Init(node.GetRule_call_expr9());
  2771. if (initRet) {
  2772. call.IncCounters();
  2773. }
  2774. PopNamedNode(TArgPlaceholderNode::ProcessRow);
  2775. if (!initRet) {
  2776. return nullptr;
  2777. }
  2778. auto args = call.GetArgs();
  2779. TSqlCallExpr finalCall(call, args);
  2780. TNodePtr udf(finalCall.BuildUdf(false));
  2781. if (!udf || !finalCall.EnsureNotDistinct("REDUCE")) {
  2782. return {};
  2783. }
  2784. if (node.HasBlock10()) {
  2785. udf->SetLabel(IdOrString(node.GetBlock10().GetRule_id_or_string2(), *this));
  2786. }
  2787. const auto reduceMode = node.HasBlock8() ? ReduceMode::ByAll : ReduceMode::ByPartition;
  2788. return BuildReduce(startPos, reduceMode, std::move(source), std::move(orderBy), std::move(keys), std::move(args), udf, having, settings);
  2789. }
  2790. TSourcePtr TSqlSelect::SelectCore(const TRule_select_core& node, const TWriteSettings& settings, TPosition& selectPos) {
  2791. // (FROM join_source)? SELECT STREAM? opt_set_quantifier result_column (COMMA result_column)* (WITHOUT column_list)? (FROM join_source)? (WHERE expr)?
  2792. // group_by_clause? (HAVING expr)? window_clause? order_by_clause?
  2793. if (node.HasBlock1()) {
  2794. Token(node.GetBlock1().GetToken1());
  2795. } else {
  2796. Token(node.GetToken2());
  2797. }
  2798. TPosition startPos(Ctx.Pos());
  2799. if (!selectPos) {
  2800. selectPos = Ctx.Pos();
  2801. }
  2802. const bool stream = node.HasBlock3();
  2803. const bool distinct = IsDistinctOptSet(node.GetRule_opt_set_quantifier4());
  2804. if (distinct) {
  2805. Ctx.IncrementMonCounter("sql_features", "DistinctInSelect");
  2806. }
  2807. TSourcePtr source(BuildFakeSource(selectPos));
  2808. if (node.HasBlock1() && node.HasBlock8()) {
  2809. Token(node.GetBlock8().GetToken1());
  2810. Ctx.IncrementMonCounter("sql_errors", "DoubleFrom");
  2811. Ctx.Error() << "Only one FROM clause is allowed";
  2812. return nullptr;
  2813. }
  2814. if (node.HasBlock1()) {
  2815. source = JoinSource(node.GetBlock1().GetRule_join_source2());
  2816. Ctx.IncrementMonCounter("sql_features", "FromInFront");
  2817. } else if (node.HasBlock8()) {
  2818. source = JoinSource(node.GetBlock8().GetRule_join_source2());
  2819. }
  2820. if (!source) {
  2821. return nullptr;
  2822. }
  2823. TVector<TNodePtr> without;
  2824. if (node.HasBlock7()) {
  2825. if (!ColumnList(without, node.GetBlock7().GetRule_column_list2())) {
  2826. return nullptr;
  2827. }
  2828. }
  2829. if (node.HasBlock9()) {
  2830. auto block = node.GetBlock9();
  2831. Token(block.GetToken1());
  2832. TPosition pos(Ctx.Pos());
  2833. TSqlExpression expr(Ctx, Mode);
  2834. TNodePtr where = expr.WrapExprShortcuts(expr.Build(block.GetRule_expr2()));
  2835. if (!where) {
  2836. Ctx.IncrementMonCounter("sql_errors", "WhereInvalid");
  2837. return nullptr;
  2838. }
  2839. if (!source->AddFilter(Ctx, where)) {
  2840. Ctx.IncrementMonCounter("sql_errors", "WhereNotSupportedBySource");
  2841. return nullptr;
  2842. }
  2843. Ctx.IncrementMonCounter("sql_features", "Where");
  2844. }
  2845. /// \todo merge gtoupByExpr and groupBy in one
  2846. TVector<TNodePtr> groupByExpr, groupBy;
  2847. THoppingWindowSpecPtr hoppingWindowSpec;
  2848. if (node.HasBlock10()) {
  2849. TGroupByClause clause(Ctx, Mode);
  2850. if (!clause.Build(node.GetBlock10().GetRule_group_by_clause1(), stream)) {
  2851. return nullptr;
  2852. }
  2853. for (const auto& exprAlias: clause.Aliases()) {
  2854. YQL_ENSURE(exprAlias.first == exprAlias.second->GetLabel());
  2855. groupByExpr.emplace_back(exprAlias.second);
  2856. }
  2857. groupBy = std::move(clause.Content());
  2858. clause.SetFeatures("sql_features");
  2859. hoppingWindowSpec = clause.GetHoppingWindow();
  2860. }
  2861. TNodePtr having;
  2862. if (node.HasBlock11()) {
  2863. TSqlExpression expr(Ctx, Mode);
  2864. having = expr.Build(node.GetBlock11().GetRule_expr2());
  2865. if (!having) {
  2866. return nullptr;
  2867. }
  2868. Ctx.IncrementMonCounter("sql_features", "Having");
  2869. }
  2870. TWinSpecs windowSpec;
  2871. if (node.HasBlock12()) {
  2872. if (stream) {
  2873. Ctx.Error() << "WINDOW is not allowed in streaming queries";
  2874. return nullptr;
  2875. }
  2876. if (!WindowClause(node.GetBlock12().GetRule_window_clause1(), windowSpec)) {
  2877. return nullptr;
  2878. }
  2879. Ctx.IncrementMonCounter("sql_features", "WindowClause");
  2880. }
  2881. TVector<TSortSpecificationPtr> orderBy;
  2882. if (node.HasBlock13()) {
  2883. if (stream) {
  2884. Ctx.Error() << "ORDER BY is not allowed in streaming queries";
  2885. return nullptr;
  2886. }
  2887. if (!OrderByClause(node.GetBlock13().GetRule_order_by_clause1(), orderBy)) {
  2888. return nullptr;
  2889. }
  2890. Ctx.IncrementMonCounter("sql_features", IsColumnsOnly(orderBy) ? "OrderBy" : "OrderByExpr");
  2891. }
  2892. TVector<TNodePtr> terms;
  2893. if (!SelectTerm(terms, node.GetRule_result_column5())) {
  2894. return nullptr;
  2895. }
  2896. for (auto block: node.GetBlock6()) {
  2897. if (!SelectTerm(terms, block.GetRule_result_column2())) {
  2898. return nullptr;
  2899. }
  2900. }
  2901. if (!ValidateSelectColumns(terms)) {
  2902. return nullptr;
  2903. }
  2904. return BuildSelectCore(Ctx, startPos, std::move(source), groupByExpr, groupBy, orderBy, having,
  2905. std::move(windowSpec), hoppingWindowSpec, std::move(terms), distinct, std::move(without), stream, settings);
  2906. }
  2907. bool TSqlSelect::FrameStart(const TRule_window_frame_start& rule, TNodePtr& node, bool beginBound) {
  2908. switch (rule.Alt_case()) {
  2909. case TRule_window_frame_start::kAltWindowFrameStart1:
  2910. if (!beginBound) {
  2911. Ctx.Error() << "Unable to use UNBOUNDED PRECEDING after BETWEEN ... AND";
  2912. return false;
  2913. }
  2914. node = BuildLiteralVoid(Ctx.Pos());
  2915. return true;
  2916. case TRule_window_frame_start::kAltWindowFrameStart2:
  2917. if (beginBound) {
  2918. Ctx.Error() << "Unable to use FOLLOWING before AND in BETWEEN ... AND syntax";
  2919. return false;
  2920. }
  2921. {
  2922. auto precedingRule = rule.GetAlt_window_frame_start2().GetRule_window_frame_preceding1();
  2923. node = Literal(Ctx, precedingRule.GetRule_unsigned_number1());
  2924. return true;
  2925. }
  2926. case TRule_window_frame_start::kAltWindowFrameStart3:
  2927. return new TLiteralNumberNode<i32>(Ctx.Pos(), "Int32", ToString("0"));
  2928. return true;
  2929. default:
  2930. Y_ABORT("FrameClause: frame start not corresond to grammar changes");
  2931. }
  2932. }
  2933. bool TSqlSelect::FrameBound(const TRule_window_frame_bound& rule, TNodePtr& node, bool beginBound) {
  2934. switch (rule.Alt_case()) {
  2935. case TRule_window_frame_bound::kAltWindowFrameBound1:
  2936. return FrameStart(rule.GetAlt_window_frame_bound1().GetRule_window_frame_start1(), node, beginBound);
  2937. case TRule_window_frame_bound::kAltWindowFrameBound2:
  2938. if (beginBound) {
  2939. Ctx.Error() << "Unable to use UNBOUNDED FOLLOWING before AND";
  2940. return false;
  2941. }
  2942. node = BuildLiteralVoid(Ctx.Pos());
  2943. return true;
  2944. case TRule_window_frame_bound::kAltWindowFrameBound3:
  2945. if (beginBound) {
  2946. Ctx.Error() << "Unable to use FOLLOWING before AND";
  2947. return false;
  2948. }
  2949. {
  2950. auto followRule = rule.GetAlt_window_frame_bound3().GetRule_window_frame_following1();
  2951. node = Literal(Ctx, followRule.GetRule_unsigned_number1());
  2952. return true;
  2953. }
  2954. default:
  2955. Y_ABORT("FrameClause: frame bound not corresond to grammar changes");
  2956. }
  2957. }
  2958. bool TSqlSelect::FrameClause(const TRule_window_frame_clause& rule, TMaybe<TFrameSpecification>& frameSpecLink) {
  2959. TFrameSpecification frameSpec;
  2960. const TString frameUnitStr = to_lower(Token(rule.GetRule_window_frame_units1().GetToken1()));
  2961. if (frameUnitStr == "rows") {
  2962. frameSpec.FrameType = EFrameType::FrameByRows;
  2963. } else if (frameUnitStr == "range") {
  2964. frameSpec.FrameType = EFrameType::FrameByRange;
  2965. } else {
  2966. Ctx.Error() << "Unknown frame type in window specification: " << frameUnitStr;
  2967. return false;
  2968. }
  2969. auto frameExtent = rule.GetRule_window_frame_extent2();
  2970. switch (frameExtent.Alt_case()) {
  2971. case TRule_window_frame_extent::kAltWindowFrameExtent1:
  2972. if (!FrameStart(frameExtent.GetAlt_window_frame_extent1().GetRule_window_frame_start1(), frameSpec.FrameBegin, true)) {
  2973. return false;
  2974. }
  2975. break;
  2976. case TRule_window_frame_extent::kAltWindowFrameExtent2: {
  2977. auto between = frameExtent.GetAlt_window_frame_extent2().GetRule_window_frame_between1();
  2978. if (!FrameBound(between.GetRule_window_frame_bound2(), frameSpec.FrameBegin, true)) {
  2979. return false;
  2980. }
  2981. if (!FrameBound(between.GetRule_window_frame_bound4(), frameSpec.FrameEnd, false)) {
  2982. return false;
  2983. }
  2984. break;
  2985. }
  2986. default:
  2987. Y_ABORT("FrameClause: frame extent not corresond to grammar changes");
  2988. }
  2989. if (rule.HasBlock3()) {
  2990. switch (rule.GetBlock3().GetRule_window_frame_exclusion1().Alt_case()) {
  2991. case TRule_window_frame_exclusion::kAltWindowFrameExclusion1:
  2992. frameSpec.FrameExclusion = FrameExclCurRow;
  2993. break;
  2994. case TRule_window_frame_exclusion::kAltWindowFrameExclusion2:
  2995. frameSpec.FrameExclusion = FrameExclGroup;
  2996. break;
  2997. case TRule_window_frame_exclusion::kAltWindowFrameExclusion3:
  2998. frameSpec.FrameExclusion = FrameExclTies;
  2999. break;
  3000. case TRule_window_frame_exclusion::kAltWindowFrameExclusion4:
  3001. frameSpec.FrameExclusion = FrameExclNoOthers;
  3002. break;
  3003. default:
  3004. Y_ABORT("FrameClause: frame exclusion not corresond to grammar changes");
  3005. }
  3006. }
  3007. frameSpecLink = frameSpec;
  3008. return true;
  3009. }
  3010. TWindowSpecificationPtr TSqlSelect::WindowSpecification(const TRule_window_specification_details& rule) {
  3011. TWindowSpecificationPtr winSpecPtr = new TWindowSpecification;
  3012. if (rule.HasBlock1()) {
  3013. Ctx.Error() << "Existing window name is not supported in window specification yet!";
  3014. return {};
  3015. }
  3016. if (rule.HasBlock2()) {
  3017. if (!NamedExprList(rule.GetBlock2().GetRule_window_partition_clause1().GetRule_named_expr_list3(), winSpecPtr->Partitions)) {
  3018. return {};
  3019. }
  3020. }
  3021. if (rule.HasBlock3()) {
  3022. if (!OrderByClause(rule.GetBlock3().GetRule_window_order_clause1().GetRule_order_by_clause1(), winSpecPtr->OrderBy)) {
  3023. return {};
  3024. }
  3025. }
  3026. if (rule.HasBlock4()) {
  3027. if (!FrameClause(rule.GetBlock4().GetRule_window_frame_clause1(), winSpecPtr->Frame)) {
  3028. return {};
  3029. }
  3030. }
  3031. return winSpecPtr;
  3032. }
  3033. bool TSqlSelect::WindowDefenition(const TRule_window_definition& rule, TWinSpecs& winSpecs) {
  3034. const TString windowName = Id(rule.GetRule_new_window_name1().GetRule_window_name1().GetRule_id1(), *this);
  3035. if (winSpecs.contains(windowName)) {
  3036. Ctx.Error() << "Unable to declare window with same name: " << windowName;
  3037. return false;
  3038. }
  3039. auto windowSpec = WindowSpecification(rule.GetRule_window_specification3().GetRule_window_specification_details2());
  3040. if (!windowSpec) {
  3041. return false;
  3042. }
  3043. winSpecs.emplace(windowName, std::move(windowSpec));
  3044. return true;
  3045. }
  3046. bool TSqlSelect::WindowClause(const TRule_window_clause& rule, TWinSpecs& winSpecs) {
  3047. auto windowList = rule.GetRule_window_definition_list2();
  3048. if (!WindowDefenition(windowList.GetRule_window_definition1(), winSpecs)) {
  3049. return false;
  3050. }
  3051. for (auto& block: windowList.GetBlock2()) {
  3052. if (!WindowDefenition(block.GetRule_window_definition2(), winSpecs)) {
  3053. return false;
  3054. }
  3055. }
  3056. return true;
  3057. }
  3058. bool TSqlSelect::OrderByClause(const TRule_order_by_clause& node, TVector<TSortSpecificationPtr>& orderBy) {
  3059. return SortSpecificationList(node.GetRule_sort_specification_list3(), orderBy);
  3060. }
  3061. bool TGroupByClause::Build(const TRule_group_by_clause& node, bool stream) {
  3062. const bool distinct = IsDistinctOptSet(node.GetRule_opt_set_quantifier3());
  3063. if (distinct) {
  3064. Ctx.Error() << "DISTINCT is not supported in GROUP BY clause yet!";
  3065. Ctx.IncrementMonCounter("sql_errors", "DistinctInGroupByNotSupported");
  3066. return false;
  3067. }
  3068. if (!ParseList(node.GetRule_grouping_element_list4())) {
  3069. return false;
  3070. }
  3071. ResolveGroupByAndGrouping();
  3072. if (stream && !HoppingWindowSpec) {
  3073. Ctx.Error() << "Streaming group by query must have a hopping window specification.";
  3074. return false;
  3075. }
  3076. if (!stream && HoppingWindowSpec) {
  3077. Ctx.Error() << "Hopping window specification is not supported in a non-streaming query.";
  3078. return false;
  3079. }
  3080. return true;
  3081. }
  3082. bool TGroupByClause::ParseList(const TRule_grouping_element_list& groupingListNode) {
  3083. if (!GroupingElement(groupingListNode.GetRule_grouping_element1())) {
  3084. return false;
  3085. }
  3086. for (auto b: groupingListNode.GetBlock2()) {
  3087. if (!GroupingElement(b.GetRule_grouping_element2())) {
  3088. return false;
  3089. }
  3090. }
  3091. return true;
  3092. }
  3093. void TGroupByClause::SetFeatures(const TString& field) const {
  3094. Ctx.IncrementMonCounter(field, "GroupBy");
  3095. const auto& features = Features();
  3096. if (features.Test(EGroupByFeatures::Ordinary)) {
  3097. Ctx.IncrementMonCounter(field, "GroupByOrdinary");
  3098. }
  3099. if (features.Test(EGroupByFeatures::Expression)) {
  3100. Ctx.IncrementMonCounter(field, "GroupByExpression");
  3101. }
  3102. if (features.Test(EGroupByFeatures::Rollup)) {
  3103. Ctx.IncrementMonCounter(field, "GroupByRollup");
  3104. }
  3105. if (features.Test(EGroupByFeatures::Cube)) {
  3106. Ctx.IncrementMonCounter(field, "GroupByCube");
  3107. }
  3108. if (features.Test(EGroupByFeatures::GroupingSet)) {
  3109. Ctx.IncrementMonCounter(field, "GroupByGroupingSet");
  3110. }
  3111. if (features.Test(EGroupByFeatures::Empty)) {
  3112. Ctx.IncrementMonCounter(field, "GroupByEmpty");
  3113. }
  3114. }
  3115. TVector<TNodePtr>& TGroupByClause::Content() {
  3116. return GroupBySet;
  3117. }
  3118. TMap<TString, TNodePtr>& TGroupByClause::Aliases() {
  3119. return GroupSetContext->NodeAliases;
  3120. }
  3121. THoppingWindowSpecPtr TGroupByClause::GetHoppingWindow() {
  3122. return HoppingWindowSpec;
  3123. }
  3124. TVector<TNodePtr> TGroupByClause::MultiplyGroupingSets(const TVector<TNodePtr>& lhs, const TVector<TNodePtr>& rhs) const {
  3125. TVector<TNodePtr> content;
  3126. for (const auto& leftNode: lhs) {
  3127. auto leftPtr = leftNode->ContentListPtr();
  3128. YQL_ENSURE(leftPtr, "Unable to multiply grouping sets");
  3129. for (const auto& rightNode: rhs) {
  3130. TVector<TNodePtr> mulItem(leftPtr->begin(), leftPtr->end());
  3131. auto rightPtr = rightNode->ContentListPtr();
  3132. YQL_ENSURE(rightPtr, "Unable to multiply grouping sets");
  3133. mulItem.insert(mulItem.end(), rightPtr->begin(), rightPtr->end());
  3134. content.push_back(BuildListOfNamedNodes(Ctx.Pos(), std::move(mulItem)));
  3135. }
  3136. }
  3137. return content;
  3138. }
  3139. void TGroupByClause::ResolveGroupByAndGrouping() {
  3140. auto listPos = std::find_if(GroupBySet.begin(), GroupBySet.end(), [](const TNodePtr& node) {
  3141. return node->ContentListPtr();
  3142. });
  3143. if (listPos == GroupBySet.end()) {
  3144. return;
  3145. }
  3146. auto curContent = *(*listPos)->ContentListPtr();
  3147. if (listPos != GroupBySet.begin()) {
  3148. TVector<TNodePtr> emulate(GroupBySet.begin(), listPos);
  3149. TVector<TNodePtr> emulateContent(1, BuildListOfNamedNodes(Ctx.Pos(), std::move(emulate)));
  3150. curContent = MultiplyGroupingSets(emulateContent, curContent);
  3151. }
  3152. for (++listPos; listPos != GroupBySet.end(); ++listPos) {
  3153. auto newElem = (*listPos)->ContentListPtr();
  3154. if (newElem) {
  3155. curContent = MultiplyGroupingSets(curContent, *newElem);
  3156. } else {
  3157. TVector<TNodePtr> emulate(1, *listPos);
  3158. TVector<TNodePtr> emulateContent(1, BuildListOfNamedNodes(Ctx.Pos(), std::move(emulate)));
  3159. curContent = MultiplyGroupingSets(curContent, emulateContent);
  3160. }
  3161. }
  3162. TVector<TNodePtr> result(1, BuildListOfNamedNodes(Ctx.Pos(), std::move(curContent)));
  3163. std::swap(result, GroupBySet);
  3164. }
  3165. bool TGroupByClause::GroupingElement(const TRule_grouping_element& node) {
  3166. TSourcePtr res;
  3167. TVector<TNodePtr> emptyContent;
  3168. switch (node.Alt_case()) {
  3169. case TRule_grouping_element::kAltGroupingElement1:
  3170. if (!OrdinaryGroupingSet(node.GetAlt_grouping_element1().GetRule_ordinary_grouping_set1())) {
  3171. return false;
  3172. }
  3173. Features().Set(EGroupByFeatures::Ordinary);
  3174. break;
  3175. case TRule_grouping_element::kAltGroupingElement2: {
  3176. TGroupByClause subClause(Ctx, Mode, GroupSetContext);
  3177. if (!subClause.OrdinaryGroupingSetList(node.GetAlt_grouping_element2().GetRule_rollup_list1().GetRule_ordinary_grouping_set_list3())) {
  3178. return false;
  3179. }
  3180. auto& content = subClause.Content();
  3181. if (!IsNodeColumnsOrNamedExpression(content, "ROLLUP")) {
  3182. return false;
  3183. }
  3184. TVector<TNodePtr> collection;
  3185. for (auto limit = content.end(), begin = content.begin(); limit != begin; --limit) {
  3186. TVector<TNodePtr> grouping(begin, limit);
  3187. collection.push_back(BuildListOfNamedNodes(Ctx.Pos(), std::move(grouping)));
  3188. }
  3189. collection.push_back(BuildListOfNamedNodes(Ctx.Pos(), std::move(emptyContent)));
  3190. GroupBySet.push_back(BuildListOfNamedNodes(Ctx.Pos(), std::move(collection)));
  3191. Ctx.IncrementMonCounter("sql_features", TStringBuilder() << "GroupByRollup" << content.size());
  3192. Features().Set(EGroupByFeatures::Rollup);
  3193. break;
  3194. }
  3195. case TRule_grouping_element::kAltGroupingElement3: {
  3196. TGroupByClause subClause(Ctx, Mode, GroupSetContext);
  3197. if (!subClause.OrdinaryGroupingSetList(node.GetAlt_grouping_element3().GetRule_cube_list1().GetRule_ordinary_grouping_set_list3())) {
  3198. return false;
  3199. }
  3200. auto& content = subClause.Content();
  3201. if (!IsNodeColumnsOrNamedExpression(content, "CUBE")) {
  3202. return false;
  3203. }
  3204. if (content.size() > Ctx.PragmaGroupByCubeLimit) {
  3205. Ctx.Error() << "GROUP BY CUBE is allowed only for " << Ctx.PragmaGroupByCubeLimit << " columns, but you use " << content.size();
  3206. return false;
  3207. }
  3208. TVector<TNodePtr> collection;
  3209. for (unsigned mask = (1 << content.size()) - 1; mask > 0; --mask) {
  3210. TVector<TNodePtr> grouping;
  3211. for (unsigned index = 0; index < content.size(); ++index) {
  3212. if (mask & (1 << index)) {
  3213. grouping.push_back(content[content.size() - index - 1]);
  3214. }
  3215. }
  3216. collection.push_back(BuildListOfNamedNodes(Ctx.Pos(), std::move(grouping)));
  3217. }
  3218. collection.push_back(BuildListOfNamedNodes(Ctx.Pos(), std::move(emptyContent)));
  3219. GroupBySet.push_back(BuildListOfNamedNodes(Ctx.Pos(), std::move(collection)));
  3220. Ctx.IncrementMonCounter("sql_features", TStringBuilder() << "GroupByCube" << content.size());
  3221. Features().Set(EGroupByFeatures::Cube);
  3222. break;
  3223. }
  3224. case TRule_grouping_element::kAltGroupingElement4: {
  3225. auto listNode = node.GetAlt_grouping_element4().GetRule_grouping_sets_specification1().GetRule_grouping_element_list4();
  3226. TGroupByClause subClause(Ctx, Mode, GroupSetContext);
  3227. if (!subClause.ParseList(listNode)) {
  3228. return false;
  3229. }
  3230. auto& content = subClause.Content();
  3231. if (!IsNodeColumnsOrNamedExpression(content, "GROUPING SETS")) {
  3232. return false;
  3233. }
  3234. TVector<TNodePtr> collection;
  3235. bool hasEmpty = false;
  3236. for (auto& elem: content) {
  3237. auto elemContent = elem->ContentListPtr();
  3238. if (elemContent) {
  3239. if (!elemContent->empty() && elemContent->front()->ContentListPtr()) {
  3240. for (auto& sub: *elemContent) {
  3241. FeedCollection(sub, collection, hasEmpty);
  3242. }
  3243. } else {
  3244. FeedCollection(elem, collection, hasEmpty);
  3245. }
  3246. } else {
  3247. TVector<TNodePtr> elemList(1, std::move(elem));
  3248. collection.push_back(BuildListOfNamedNodes(Ctx.Pos(), std::move(elemList)));
  3249. }
  3250. }
  3251. GroupBySet.push_back(BuildListOfNamedNodes(Ctx.Pos(), std::move(collection)));
  3252. Features().Set(EGroupByFeatures::GroupingSet);
  3253. break;
  3254. }
  3255. case TRule_grouping_element::kAltGroupingElement5: {
  3256. if (!HoppingWindow(node.GetAlt_grouping_element5().GetRule_hopping_window_specification1())) {
  3257. return false;
  3258. }
  3259. break;
  3260. }
  3261. default:
  3262. Y_ABORT("You should change implementation according grammar changes");
  3263. }
  3264. return true;
  3265. }
  3266. void TGroupByClause::FeedCollection(const TNodePtr& elem, TVector<TNodePtr>& collection, bool& hasEmpty) const {
  3267. auto elemContentPtr = elem->ContentListPtr();
  3268. if (elemContentPtr && elemContentPtr->empty()) {
  3269. if (hasEmpty) {
  3270. return;
  3271. }
  3272. hasEmpty = true;
  3273. }
  3274. collection.push_back(elem);
  3275. }
  3276. bool TGroupByClause::OrdinaryGroupingSet(const TRule_ordinary_grouping_set& node) {
  3277. auto namedExprNode = NamedExpr(node.GetRule_named_expr1(), EExpr::GroupBy);
  3278. if (!namedExprNode) {
  3279. return false;
  3280. }
  3281. auto nodeLabel = namedExprNode->GetLabel();
  3282. auto contentPtr = namedExprNode->ContentListPtr();
  3283. if (contentPtr) {
  3284. if (nodeLabel && (contentPtr->size() != 1 || contentPtr->front()->GetLabel())) {
  3285. Ctx.Error() << "Unable to use aliases for list of named expressions";
  3286. Ctx.IncrementMonCounter("sql_errors", "GroupByAliasForListOfExpressions");
  3287. return false;
  3288. }
  3289. for (auto& content: *contentPtr) {
  3290. auto label = content->GetLabel();
  3291. if (!label) {
  3292. if (content->GetColumnName()) {
  3293. namedExprNode->AssumeColumn();
  3294. continue;
  3295. }
  3296. content->SetLabel(label = GenerateGroupByExprName());
  3297. }
  3298. if (!AddAlias(label, content)) {
  3299. return false;
  3300. }
  3301. content = BuildColumn(content->GetPos(), label);
  3302. }
  3303. } else {
  3304. if (!nodeLabel && namedExprNode->GetColumnName()) {
  3305. namedExprNode->AssumeColumn();
  3306. }
  3307. if (!nodeLabel && !namedExprNode->GetColumnName()) {
  3308. namedExprNode->SetLabel(nodeLabel = GenerateGroupByExprName());
  3309. }
  3310. if (nodeLabel) {
  3311. if (!AddAlias(nodeLabel, namedExprNode)) {
  3312. return false;
  3313. }
  3314. namedExprNode = BuildColumn(namedExprNode->GetPos(), nodeLabel);
  3315. }
  3316. }
  3317. GroupBySet.emplace_back(std::move(namedExprNode));
  3318. return true;
  3319. }
  3320. bool TGroupByClause::OrdinaryGroupingSetList(const TRule_ordinary_grouping_set_list& node) {
  3321. if (!OrdinaryGroupingSet(node.GetRule_ordinary_grouping_set1())) {
  3322. return false;
  3323. }
  3324. for (auto& block: node.GetBlock2()) {
  3325. if (!OrdinaryGroupingSet(block.GetRule_ordinary_grouping_set2())) {
  3326. return false;
  3327. }
  3328. }
  3329. return true;
  3330. }
  3331. bool TGroupByClause::HoppingWindow(const TRule_hopping_window_specification& node) {
  3332. if (HoppingWindowSpec) {
  3333. Ctx.Error() << "Duplicate hopping window specification.";
  3334. return false;
  3335. }
  3336. HoppingWindowSpec = new THoppingWindowSpec;
  3337. {
  3338. TSqlExpression expr(Ctx, Mode);
  3339. HoppingWindowSpec->TimeExtractor = expr.Build(node.GetRule_expr3());
  3340. if (!HoppingWindowSpec->TimeExtractor) {
  3341. return false;
  3342. }
  3343. }
  3344. auto processIntervalParam = [&] (const TRule_expr& rule) -> TNodePtr {
  3345. TSqlExpression expr(Ctx, Mode);
  3346. auto node = expr.Build(rule);
  3347. if (!node) {
  3348. return nullptr;
  3349. }
  3350. auto literal = node->GetLiteral("String");
  3351. if (!literal) {
  3352. return new TAstListNodeImpl(Ctx.Pos(), {
  3353. new TAstAtomNodeImpl(Ctx.Pos(), "EvaluateExpr", TNodeFlags::Default),
  3354. node
  3355. });
  3356. }
  3357. const auto out = NKikimr::NMiniKQL::ValueFromString(NKikimr::NUdf::EDataSlot::Interval, *literal);
  3358. if (!out) {
  3359. Ctx.Error(node->GetPos()) << "Expected interval in ISO 8601 format";
  3360. return nullptr;
  3361. }
  3362. if ('T' == literal->back()) {
  3363. Ctx.Warning(node->GetPos(), TIssuesIds::YQL_DEPRECATED_INTERVAL_CONSTANT) << "Time prefix 'T' at end of interval contant";
  3364. }
  3365. return new TAstListNodeImpl(Ctx.Pos(), {
  3366. new TAstAtomNodeImpl(Ctx.Pos(), "Interval", TNodeFlags::Default),
  3367. new TAstListNodeImpl(Ctx.Pos(), {
  3368. new TAstAtomNodeImpl(Ctx.Pos(), "quote", TNodeFlags::Default),
  3369. new TAstAtomNodeImpl(Ctx.Pos(), ToString(out.Get<i64>()), TNodeFlags::Default)
  3370. })
  3371. });
  3372. };
  3373. HoppingWindowSpec->Hop = processIntervalParam(node.GetRule_expr5());
  3374. if (!HoppingWindowSpec->Hop) {
  3375. return false;
  3376. }
  3377. HoppingWindowSpec->Interval = processIntervalParam(node.GetRule_expr7());
  3378. if (!HoppingWindowSpec->Interval) {
  3379. return false;
  3380. }
  3381. HoppingWindowSpec->Delay = processIntervalParam(node.GetRule_expr9());
  3382. if (!HoppingWindowSpec->Delay) {
  3383. return false;
  3384. }
  3385. return true;
  3386. }
  3387. bool TGroupByClause::IsNodeColumnsOrNamedExpression(const TVector<TNodePtr>& content, const TString& construction) const {
  3388. for (const auto& node: content) {
  3389. if (IsAutogenerated(node->GetColumnName())) {
  3390. Ctx.Error() << "You should use in " << construction << " either expression with required alias either column name or used alias.";
  3391. Ctx.IncrementMonCounter("sql_errors", "GroupBySetNoAliasOrColumn");
  3392. return false;
  3393. }
  3394. }
  3395. return true;
  3396. }
  3397. TGroupByClause::TGroupingSetFeatures& TGroupByClause::Features() {
  3398. return GroupSetContext->GroupFeatures;
  3399. }
  3400. const TGroupByClause::TGroupingSetFeatures& TGroupByClause::Features() const {
  3401. return GroupSetContext->GroupFeatures;
  3402. }
  3403. bool TGroupByClause::AddAlias(const TString& label, const TNodePtr& node) {
  3404. if (Aliases().contains(label)) {
  3405. Ctx.Error() << "Duplicated aliases not allowed";
  3406. Ctx.IncrementMonCounter("sql_errors", "GroupByDuplicateAliases");
  3407. return false;
  3408. }
  3409. Aliases().emplace(label, node);
  3410. return true;
  3411. }
  3412. TString TGroupByClause::GenerateGroupByExprName() {
  3413. return TStringBuilder() << AutogenerateNamePrefix << GroupSetContext->UnnamedCount++;
  3414. }
  3415. bool TGroupByClause::IsAutogenerated(const TString* name) const {
  3416. return name && name->StartsWith(AutogenerateNamePrefix);
  3417. }
  3418. TSourcePtr TSqlSelect::SelectKind(const TRule_select_kind_partial& node, TPosition& selectPos) {
  3419. auto source = SelectKind(node.GetRule_select_kind1(), selectPos);
  3420. if (!source) {
  3421. return {};
  3422. }
  3423. TPosition startPos(Ctx.Pos());
  3424. /// LIMIT INTEGER block
  3425. TNodePtr skipTake;
  3426. if (node.HasBlock2()) {
  3427. auto block = node.GetBlock2();
  3428. Token(block.GetToken1());
  3429. TPosition pos(Ctx.Pos());
  3430. TSqlExpression takeExpr(Ctx, Mode);
  3431. auto take = takeExpr.Build(block.GetRule_expr2());
  3432. if (!take) {
  3433. return{};
  3434. }
  3435. TNodePtr skip;
  3436. if (block.HasBlock3()) {
  3437. TSqlExpression skipExpr(Ctx, Mode);
  3438. skip = skipExpr.Build(block.GetBlock3().GetRule_expr2());
  3439. if (!skip) {
  3440. return {};
  3441. }
  3442. if (Token(block.GetBlock3().GetToken1()) == ",") {
  3443. // LIMIT skip, take
  3444. skip.Swap(take);
  3445. Ctx.IncrementMonCounter("sql_features", "LimitSkipTake");
  3446. } else {
  3447. Ctx.IncrementMonCounter("sql_features", "LimitOffset");
  3448. }
  3449. }
  3450. skipTake = BuildSkipTake(pos, skip, take);
  3451. Ctx.IncrementMonCounter("sql_features", "Limit");
  3452. }
  3453. return BuildSelect(startPos, std::move(source), skipTake);
  3454. }
  3455. TSourcePtr TSqlSelect::SelectKind(const TRule_select_kind& node, TPosition& selectPos) {
  3456. const bool discard = node.HasBlock1();
  3457. const bool hasLabel = node.HasBlock3();
  3458. if ((discard || hasLabel) && (Mode == NSQLTranslation::ESqlMode::LIMITED_VIEW || Mode == NSQLTranslation::ESqlMode::SUBQUERY)) {
  3459. Ctx.Error() << "DISCARD and INTO RESULT are not allowed in current mode";
  3460. return {};
  3461. }
  3462. if (discard && hasLabel) {
  3463. Ctx.Error() << "DISCARD and INTO RESULT cannot be used at the same time";
  3464. return {};
  3465. }
  3466. if (discard && !selectPos) {
  3467. selectPos = Ctx.TokenPosition(node.GetBlock1().GetToken1());
  3468. }
  3469. TWriteSettings settings;
  3470. settings.Discard = discard;
  3471. if (hasLabel) {
  3472. settings.Label = PureColumnOrNamed(node.GetBlock3().GetRule_pure_column_or_named3(), *this);
  3473. }
  3474. TSourcePtr res;
  3475. switch (node.GetBlock2().Alt_case()) {
  3476. case TRule_select_kind_TBlock2::kAlt1:
  3477. res = ProcessCore(node.GetBlock2().GetAlt1().GetRule_process_core1(), settings, selectPos);
  3478. break;
  3479. case TRule_select_kind_TBlock2::kAlt2:
  3480. res = ReduceCore(node.GetBlock2().GetAlt2().GetRule_reduce_core1(), settings, selectPos);
  3481. break;
  3482. case TRule_select_kind_TBlock2::kAlt3:
  3483. res = SelectCore(node.GetBlock2().GetAlt3().GetRule_select_core1(), settings, selectPos);
  3484. break;
  3485. default:
  3486. Y_ABORT("You should change implementation according grammar changes");
  3487. }
  3488. return res;
  3489. }
  3490. TSourcePtr TSqlSelect::SelectKind(const TRule_select_kind_parenthesis& node, TPosition& selectPos) {
  3491. if (node.Alt_case() == TRule_select_kind_parenthesis::kAltSelectKindParenthesis1) {
  3492. return SelectKind(node.GetAlt_select_kind_parenthesis1().GetRule_select_kind_partial1(), selectPos);
  3493. } else {
  3494. return SelectKind(node.GetAlt_select_kind_parenthesis2().GetRule_select_kind_partial2(), selectPos);
  3495. }
  3496. }
  3497. TSourcePtr TSqlSelect::Build(const TRule_select_stmt& node, TPosition& selectPos) {
  3498. auto res = SelectKind(node.GetRule_select_kind_parenthesis1(), selectPos);
  3499. if (!res) {
  3500. return nullptr;
  3501. }
  3502. TPosition unionPos = selectPos; // Position of first select
  3503. TVector<TSourcePtr> sources;
  3504. sources.emplace_back(std::move(res));
  3505. for (auto& b: node.GetBlock2()) {
  3506. auto next = SelectKind(b.GetRule_select_kind_parenthesis2(), selectPos);
  3507. if (!next) {
  3508. return nullptr;
  3509. }
  3510. switch (b.GetRule_select_op1().Alt_case()) {
  3511. case TRule_select_op::kAltSelectOp1: {
  3512. const bool isUnionAll = b.GetRule_select_op1().GetAlt_select_op1().HasBlock2();
  3513. if (!isUnionAll) {
  3514. Token(b.GetRule_select_op1().GetAlt_select_op1().GetToken1());
  3515. Ctx.Error() << "UNION without quantifier ALL is not supported yet. Did you mean UNION ALL?";
  3516. return nullptr;
  3517. } else {
  3518. sources.emplace_back(std::move(next));
  3519. }
  3520. break;
  3521. }
  3522. default:
  3523. Ctx.Error() << "INTERSECT and EXCEPT are not implemented yet";
  3524. return nullptr;
  3525. }
  3526. }
  3527. if (sources.size() == 1) {
  3528. return std::move(sources[0]);
  3529. }
  3530. res = BuildUnionAll(unionPos, std::move(sources));
  3531. return res;
  3532. }
  3533. class TSqlIntoValues: public TSqlTranslation {
  3534. public:
  3535. TSqlIntoValues(TContext& ctx, NSQLTranslation::ESqlMode mode)
  3536. : TSqlTranslation(ctx, mode)
  3537. {
  3538. }
  3539. TSourcePtr Build(const TRule_into_values_source& node, const TString& operationName);
  3540. private:
  3541. bool BuildValuesRow(const TRule_values_source_row& inRow, TVector<TNodePtr>& outRow);
  3542. TSourcePtr ValuesSource(const TRule_values_source& node, TVector<TString>& columnsHint,
  3543. const TString& operationName);
  3544. };
  3545. TSourcePtr TSqlIntoValues::Build(const TRule_into_values_source& node, const TString& operationName) {
  3546. switch (node.Alt_case()) {
  3547. case TRule_into_values_source::kAltIntoValuesSource1: {
  3548. auto alt = node.GetAlt_into_values_source1();
  3549. TVector<TString> columnsHint;
  3550. if (alt.HasBlock1()) {
  3551. PureColumnListStr(alt.GetBlock1().GetRule_pure_column_list1(), *this, columnsHint);
  3552. }
  3553. return ValuesSource(alt.GetRule_values_source2(), columnsHint, operationName);
  3554. }
  3555. default:
  3556. Ctx.IncrementMonCounter("sql_errors", "DefaultValuesOrOther");
  3557. AltNotImplemented("into_values_source", node);
  3558. return nullptr;
  3559. }
  3560. }
  3561. bool TSqlIntoValues::BuildValuesRow(const TRule_values_source_row& inRow, TVector<TNodePtr>& outRow){
  3562. TSqlExpression sqlExpr(Ctx, Mode);
  3563. return ExprList(sqlExpr, outRow, inRow.GetRule_expr_list2());
  3564. }
  3565. TSourcePtr TSqlIntoValues::ValuesSource(const TRule_values_source& node, TVector<TString>& columnsHint,
  3566. const TString& operationName)
  3567. {
  3568. Ctx.IncrementMonCounter("sql_features", "ValuesSource");
  3569. TPosition pos(Ctx.Pos());
  3570. switch (node.Alt_case()) {
  3571. case TRule_values_source::kAltValuesSource1: {
  3572. TVector<TVector<TNodePtr>> rows {{}};
  3573. const auto& rowList = node.GetAlt_values_source1().GetRule_values_source_row_list2();
  3574. if (!BuildValuesRow(rowList.GetRule_values_source_row1(), rows.back())) {
  3575. return nullptr;
  3576. }
  3577. for (const auto& valuesSourceRow: rowList.GetBlock2()) {
  3578. rows.push_back({});
  3579. if (!BuildValuesRow(valuesSourceRow.GetRule_values_source_row2(), rows.back())) {
  3580. return nullptr;
  3581. }
  3582. }
  3583. return BuildWriteValues(pos, operationName, columnsHint, rows);
  3584. }
  3585. case TRule_values_source::kAltValuesSource2: {
  3586. TSqlSelect select(Ctx, Mode);
  3587. TPosition selectPos;
  3588. auto source = select.Build(node.GetAlt_values_source2().GetRule_select_stmt1(), selectPos);
  3589. if (!source) {
  3590. return nullptr;
  3591. }
  3592. return BuildWriteValues(pos, "UPDATE", columnsHint, std::move(source));
  3593. }
  3594. default:
  3595. Ctx.IncrementMonCounter("sql_errors", "UnknownValuesSource");
  3596. AltNotImplemented("values_source", node);
  3597. return nullptr;
  3598. }
  3599. }
  3600. class TSqlIntoTable: public TSqlTranslation {
  3601. public:
  3602. TSqlIntoTable(TContext& ctx, NSQLTranslation::ESqlMode mode)
  3603. : TSqlTranslation(ctx, mode)
  3604. {
  3605. }
  3606. TNodePtr Build(const TRule_into_table_stmt& node);
  3607. private:
  3608. //bool BuildValuesRow(const TRule_values_source_row& inRow, TVector<TNodePtr>& outRow);
  3609. //TSourcePtr ValuesSource(const TRule_values_source& node, TVector<TString>& columnsHint);
  3610. //TSourcePtr IntoValuesSource(const TRule_into_values_source& node);
  3611. bool ValidateServiceName(const TRule_into_table_stmt& node, const TTableRef& table, ESQLWriteColumnMode mode,
  3612. const TPosition& pos);
  3613. TString SqlIntoModeStr;
  3614. TString SqlIntoUserModeStr;
  3615. };
  3616. TNodePtr TSqlIntoTable::Build(const TRule_into_table_stmt& node) {
  3617. static const TMap<TString, ESQLWriteColumnMode> str2Mode = {
  3618. {"InsertInto", ESQLWriteColumnMode::InsertInto},
  3619. {"InsertOrAbortInto", ESQLWriteColumnMode::InsertOrAbortInto},
  3620. {"InsertOrIgnoreInto", ESQLWriteColumnMode::InsertOrIgnoreInto},
  3621. {"InsertOrRevertInto", ESQLWriteColumnMode::InsertOrRevertInto},
  3622. {"UpsertInto", ESQLWriteColumnMode::UpsertInto},
  3623. {"ReplaceInto", ESQLWriteColumnMode::ReplaceInto},
  3624. {"InsertIntoWithTruncate", ESQLWriteColumnMode::InsertIntoWithTruncate}
  3625. };
  3626. auto& modeBlock = node.GetBlock1();
  3627. TVector<TToken> modeTokens;
  3628. switch (modeBlock.Alt_case()) {
  3629. case TRule_into_table_stmt_TBlock1::AltCase::kAlt1:
  3630. modeTokens = {modeBlock.GetAlt1().GetToken1()};
  3631. break;
  3632. case TRule_into_table_stmt_TBlock1::AltCase::kAlt2:
  3633. modeTokens = {
  3634. modeBlock.GetAlt2().GetToken1(),
  3635. modeBlock.GetAlt2().GetToken2(),
  3636. modeBlock.GetAlt2().GetToken3()
  3637. };
  3638. break;
  3639. case TRule_into_table_stmt_TBlock1::AltCase::kAlt3:
  3640. modeTokens = {
  3641. modeBlock.GetAlt3().GetToken1(),
  3642. modeBlock.GetAlt3().GetToken2(),
  3643. modeBlock.GetAlt3().GetToken3()
  3644. };
  3645. break;
  3646. case TRule_into_table_stmt_TBlock1::AltCase::kAlt4:
  3647. modeTokens = {
  3648. modeBlock.GetAlt4().GetToken1(),
  3649. modeBlock.GetAlt4().GetToken2(),
  3650. modeBlock.GetAlt4().GetToken3()
  3651. };
  3652. break;
  3653. case TRule_into_table_stmt_TBlock1::AltCase::kAlt5:
  3654. modeTokens = {modeBlock.GetAlt5().GetToken1()};
  3655. break;
  3656. case TRule_into_table_stmt_TBlock1::AltCase::kAlt6:
  3657. modeTokens = {modeBlock.GetAlt6().GetToken1()};
  3658. break;
  3659. default:
  3660. Y_ABORT("You should change implementation according grammar changes");
  3661. }
  3662. TVector<TString> modeStrings;
  3663. modeStrings.reserve(modeTokens.size());
  3664. TVector<TString> userModeStrings;
  3665. userModeStrings.reserve(modeTokens.size());
  3666. for (auto& token : modeTokens) {
  3667. auto tokenStr = Token(token);
  3668. auto modeStr = tokenStr;
  3669. modeStr.to_lower();
  3670. modeStr.to_upper(0, 1);
  3671. modeStrings.push_back(modeStr);
  3672. auto userModeStr = tokenStr;
  3673. userModeStr.to_upper();
  3674. userModeStrings.push_back(userModeStr);
  3675. }
  3676. modeStrings.push_back("Into");
  3677. userModeStrings.push_back("INTO");
  3678. SqlIntoModeStr = JoinRange("", modeStrings.begin(), modeStrings.end());
  3679. SqlIntoUserModeStr = JoinRange(" ", userModeStrings.begin(), userModeStrings.end());
  3680. auto intoTableRef = node.GetRule_into_simple_table_ref3();
  3681. auto tableRef = intoTableRef.GetRule_simple_table_ref1();
  3682. auto cluster = Ctx.CurrCluster;
  3683. std::pair<bool, TDeferredAtom> nameOrAt;
  3684. if (tableRef.HasBlock1()) {
  3685. switch (tableRef.GetBlock1().Alt_case()) {
  3686. case TRule_simple_table_ref_TBlock1::AltCase::kAlt1: {
  3687. cluster = OptIdPrefixAsClusterStr(tableRef.GetBlock1().GetAlt1().GetBlock1().GetRule_opt_id_prefix1(), *this, Ctx.CurrCluster);
  3688. if (!cluster && Ctx.CurrCluster) {
  3689. return nullptr;
  3690. }
  3691. auto id = Id(tableRef.GetBlock1().GetAlt1().GetBlock1().GetRule_id_or_at2(), *this);
  3692. nameOrAt = std::make_pair(id.first, TDeferredAtom(Ctx.Pos(), id.second));
  3693. break;
  3694. }
  3695. case TRule_simple_table_ref_TBlock1::AltCase::kAlt2: {
  3696. auto at = tableRef.GetBlock1().GetAlt2().HasBlock1();
  3697. auto named = GetNamedNode(NamedNodeImpl(tableRef.GetBlock1().GetAlt2().GetRule_bind_parameter2(), *this));
  3698. if (!named) {
  3699. return nullptr;
  3700. }
  3701. TDeferredAtom table;
  3702. if (!TryMakeClusterAndTableFromExpression(named, cluster, table, Ctx)) {
  3703. Ctx.Error() << "Cannot infer cluster and table name";
  3704. return nullptr;
  3705. }
  3706. cluster = cluster.empty() ? Ctx.CurrCluster : cluster;
  3707. nameOrAt = std::make_pair(at, table);
  3708. break;
  3709. }
  3710. default:
  3711. Y_ABORT("You should change implementation according grammar changes");
  3712. }
  3713. }
  3714. bool withTruncate = false;
  3715. if (tableRef.HasBlock2()) {
  3716. auto hints = TableHintsImpl(tableRef.GetBlock2().GetRule_table_hints1(), *this);
  3717. for (const auto& hint : hints) {
  3718. if (to_upper(hint) == "TRUNCATE") {
  3719. withTruncate = true;
  3720. } else {
  3721. Ctx.Error() << "Unsupported hint: " << hint;
  3722. return nullptr;
  3723. }
  3724. }
  3725. }
  3726. TVector<TString> eraseColumns;
  3727. if (intoTableRef.HasBlock2()) {
  3728. auto service = Ctx.GetClusterProvider(cluster);
  3729. if (!service) {
  3730. Ctx.Error() << "Unknown cluster name: " << cluster;
  3731. return nullptr;
  3732. }
  3733. if (*service != StatProviderName) {
  3734. Ctx.Error() << "ERASE BY is unsupported for " << *service;
  3735. return nullptr;
  3736. }
  3737. PureColumnListStr(
  3738. intoTableRef.GetBlock2().GetRule_pure_column_list3(), *this, eraseColumns
  3739. );
  3740. }
  3741. if (withTruncate) {
  3742. if (SqlIntoModeStr != "InsertInto") {
  3743. Error() << "Unable " << SqlIntoUserModeStr << " with truncate mode";
  3744. return nullptr;
  3745. }
  3746. SqlIntoModeStr += "WithTruncate";
  3747. SqlIntoUserModeStr += " ... WITH TRUNCATE";
  3748. }
  3749. const auto iterMode = str2Mode.find(SqlIntoModeStr);
  3750. YQL_ENSURE(iterMode != str2Mode.end(), "Invalid sql write mode string: " << SqlIntoModeStr);
  3751. const auto SqlIntoMode = iterMode->second;
  3752. TPosition pos(Ctx.Pos());
  3753. TNodePtr tableKey = BuildTableKey(pos, cluster, nameOrAt.second, nameOrAt.first ? "@" : "");
  3754. TTableRef table(Ctx.MakeName("table"), cluster, tableKey);
  3755. Ctx.IncrementMonCounter("sql_insert_clusters", table.Cluster);
  3756. auto values = TSqlIntoValues(Ctx, Mode).Build(node.GetRule_into_values_source4(), SqlIntoUserModeStr);
  3757. if (!values) {
  3758. return nullptr;
  3759. }
  3760. if (!ValidateServiceName(node, table, SqlIntoMode, GetPos(modeTokens[0]))) {
  3761. return nullptr;
  3762. }
  3763. Ctx.IncrementMonCounter("sql_features", SqlIntoModeStr);
  3764. TNodePtr options;
  3765. if (eraseColumns) {
  3766. options = BuildEraseColumns(pos, std::move(eraseColumns));
  3767. }
  3768. return BuildWriteColumns(pos, table, ToWriteColumnsMode(SqlIntoMode), std::move(values), std::move(options));
  3769. }
  3770. bool TSqlIntoTable::ValidateServiceName(const TRule_into_table_stmt& node, const TTableRef& table,
  3771. ESQLWriteColumnMode mode, const TPosition& pos) {
  3772. Y_UNUSED(node);
  3773. if (!table.Check(Ctx)) {
  3774. return false;
  3775. }
  3776. auto serviceName = to_lower(table.ServiceName(Ctx));
  3777. const bool isMapReduce = serviceName == YtProviderName;
  3778. const bool isKikimr = serviceName == KikimrProviderName;
  3779. const bool isRtmr = serviceName == RtmrProviderName;
  3780. const bool isStat = serviceName == StatProviderName;
  3781. if (!isKikimr) {
  3782. if (mode == ESQLWriteColumnMode::InsertOrAbortInto ||
  3783. mode == ESQLWriteColumnMode::InsertOrIgnoreInto ||
  3784. mode == ESQLWriteColumnMode::InsertOrRevertInto ||
  3785. mode == ESQLWriteColumnMode::UpsertInto && !isStat)
  3786. {
  3787. Ctx.Error(pos) << SqlIntoUserModeStr << " is not supported for " << serviceName << " tables";
  3788. Ctx.IncrementMonCounter("sql_errors", TStringBuilder() << SqlIntoUserModeStr << "UnsupportedFor" << serviceName);
  3789. return false;
  3790. }
  3791. }
  3792. if (isMapReduce) {
  3793. if (mode == ESQLWriteColumnMode::ReplaceInto) {
  3794. Ctx.Error(pos) << "Meaning of REPLACE INTO has been changed, now you should use INSERT INTO <table> WITH TRUNCATE ... for " << serviceName;
  3795. Ctx.IncrementMonCounter("sql_errors", "ReplaceIntoConflictUsage");
  3796. return false;
  3797. }
  3798. } else if (isKikimr) {
  3799. if (mode == ESQLWriteColumnMode::InsertIntoWithTruncate) {
  3800. Ctx.Error(pos) << "INSERT INTO WITH TRUNCATE is not supported for " << serviceName << " tables";
  3801. Ctx.IncrementMonCounter("sql_errors", TStringBuilder() << SqlIntoUserModeStr << "UnsupportedFor" << serviceName);
  3802. return false;
  3803. }
  3804. } else if (isRtmr) {
  3805. if (mode != ESQLWriteColumnMode::InsertInto) {
  3806. Ctx.Error(pos) << SqlIntoUserModeStr << " is unsupported for " << serviceName;
  3807. Ctx.IncrementMonCounter("sql_errors", TStringBuilder() << SqlIntoUserModeStr << "UnsupportedFor" << serviceName);
  3808. return false;
  3809. }
  3810. } else if (isStat) {
  3811. if (mode != ESQLWriteColumnMode::UpsertInto) {
  3812. Ctx.Error(pos) << SqlIntoUserModeStr << " is unsupported for " << serviceName;
  3813. Ctx.IncrementMonCounter("sql_errors", TStringBuilder() << SqlIntoUserModeStr << "UnsupportedFor" << serviceName);
  3814. return false;
  3815. }
  3816. }
  3817. return true;
  3818. }
  3819. class TSqlQuery: public TSqlTranslation {
  3820. public:
  3821. TSqlQuery(TContext& ctx, NSQLTranslation::ESqlMode mode, bool topLevel)
  3822. : TSqlTranslation(ctx, mode)
  3823. , TopLevel(topLevel)
  3824. {
  3825. }
  3826. TNodePtr Build(const TSQLParserAST& ast);
  3827. bool Statement(TVector<TNodePtr>& blocks, const TRule_sql_stmt_core& core);
  3828. private:
  3829. bool DeclareStatement(const TRule_declare_stmt& stmt);
  3830. bool ExportStatement(const TRule_export_stmt& stmt);
  3831. bool AlterTableAddColumns(TVector<TNodePtr>& blocks, const TRule_alter_table_add_column& node, const TTableRef& tr);
  3832. bool AlterTableDropColumn(TVector<TNodePtr>& blocks, const TRule_alter_table_drop_column& node, const TTableRef& tr);
  3833. TNodePtr PragmaStatement(const TRule_pragma_stmt& stmt, bool& success);
  3834. void AddStatementToBlocks(TVector<TNodePtr>& blocks, TNodePtr node);
  3835. TNodePtr Build(const TRule_delete_stmt& stmt);
  3836. TNodePtr Build(const TRule_update_stmt& stmt);
  3837. TSourcePtr Build(const TRule_set_clause_choice& stmt);
  3838. bool FillSetClause(const TRule_set_clause& node, TVector<TString>& targetList, TVector<TNodePtr>& values);
  3839. TSourcePtr Build(const TRule_set_clause_list& stmt);
  3840. TSourcePtr Build(const TRule_multiple_column_assignment& stmt);
  3841. TNodePtr FlexType(TTranslation& ctx, const TRule_flex_type& node);
  3842. template<class TNode>
  3843. void ParseStatementName(const TNode& node, TString& internalStatementName, TString& humanStatementName) {
  3844. internalStatementName.clear();
  3845. humanStatementName.clear();
  3846. const auto& descr = AltDescription(node);
  3847. TVector<TString> parts;
  3848. const auto pos = descr.find(": ");
  3849. Y_DEBUG_ABORT_UNLESS(pos != TString::npos);
  3850. Split(TString(descr.begin() + pos + 2, descr.end()), "_", parts);
  3851. Y_DEBUG_ABORT_UNLESS(parts.size() > 1);
  3852. parts.pop_back();
  3853. for (auto& part: parts) {
  3854. part.to_upper(0, 1);
  3855. internalStatementName += part;
  3856. if (!humanStatementName.empty()) {
  3857. humanStatementName += ' ';
  3858. }
  3859. humanStatementName += to_upper(part);
  3860. }
  3861. }
  3862. const bool TopLevel;
  3863. };
  3864. void TSqlQuery::AddStatementToBlocks(TVector<TNodePtr>& blocks, TNodePtr node) {
  3865. blocks.emplace_back(node);
  3866. }
  3867. bool TSqlQuery::Statement(TVector<TNodePtr>& blocks, const TRule_sql_stmt_core& core) {
  3868. TString internalStatementName;
  3869. TString humanStatementName;
  3870. ParseStatementName(core, internalStatementName, humanStatementName);
  3871. const auto& altCase = core.Alt_case();
  3872. if (Mode == NSQLTranslation::ESqlMode::LIMITED_VIEW && (altCase >= TRule_sql_stmt_core::kAltSqlStmtCore4 &&
  3873. altCase != TRule_sql_stmt_core::kAltSqlStmtCore13)) {
  3874. Error() << humanStatementName << " statement is not supported in limited views";
  3875. return false;
  3876. }
  3877. if (Mode == NSQLTranslation::ESqlMode::SUBQUERY && (altCase >= TRule_sql_stmt_core::kAltSqlStmtCore4 &&
  3878. altCase != TRule_sql_stmt_core::kAltSqlStmtCore13 && altCase != TRule_sql_stmt_core::kAltSqlStmtCore6 &&
  3879. altCase != TRule_sql_stmt_core::kAltSqlStmtCore17)) {
  3880. Error() << humanStatementName << " statement is not supported in subqueries";
  3881. return false;
  3882. }
  3883. switch (altCase) {
  3884. case TRule_sql_stmt_core::kAltSqlStmtCore1: {
  3885. bool success = false;
  3886. TNodePtr nodeExpr = PragmaStatement(core.GetAlt_sql_stmt_core1().GetRule_pragma_stmt1(), success);
  3887. if (!success) {
  3888. return false;
  3889. }
  3890. if (nodeExpr) {
  3891. AddStatementToBlocks(blocks, nodeExpr);
  3892. }
  3893. break;
  3894. }
  3895. case TRule_sql_stmt_core::kAltSqlStmtCore2: {
  3896. Ctx.BodyPart();
  3897. TSqlSelect select(Ctx, Mode);
  3898. TPosition pos;
  3899. auto source = select.Build(core.GetAlt_sql_stmt_core2().GetRule_select_stmt1(), pos);
  3900. if (!source) {
  3901. return false;
  3902. }
  3903. blocks.emplace_back(BuildSelectResult(pos, std::move(source),
  3904. Mode != NSQLTranslation::ESqlMode::LIMITED_VIEW && Mode != NSQLTranslation::ESqlMode::SUBQUERY, Mode == NSQLTranslation::ESqlMode::SUBQUERY));
  3905. break;
  3906. }
  3907. case TRule_sql_stmt_core::kAltSqlStmtCore3: {
  3908. Ctx.BodyPart();
  3909. TVector<TString> names;
  3910. auto nodeExpr = NamedNode(core.GetAlt_sql_stmt_core3().GetRule_named_nodes_stmt1(), names);
  3911. if (!nodeExpr) {
  3912. return false;
  3913. }
  3914. TVector<TNodePtr> nodes;
  3915. auto subquery = nodeExpr->GetSource();
  3916. if (subquery) {
  3917. const auto alias = Ctx.MakeName("subquerynode");
  3918. const auto ref = Ctx.MakeName("subquery");
  3919. blocks.push_back(BuildSubquery(subquery, alias, Mode == NSQLTranslation::ESqlMode::SUBQUERY, names.size() == 1 ? -1 : names.size()));
  3920. blocks.back()->SetLabel(ref);
  3921. for (size_t i = 0; i < names.size(); ++i) {
  3922. nodes.push_back(BuildSubqueryRef(blocks.back(), ref, names.size() == 1 ? -1 : i));
  3923. }
  3924. } else {
  3925. if (names.size() > 1) {
  3926. const auto ref = Ctx.MakeName("tie");
  3927. blocks.push_back(BuildTupleResult(nodeExpr, names.size()));
  3928. blocks.back()->SetLabel(ref);
  3929. for (size_t i = 0; i < names.size(); ++i) {
  3930. nodes.push_back(nodeExpr->Y("Nth", ref, nodeExpr->Q(ToString(i))));
  3931. }
  3932. } else {
  3933. nodes.push_back(std::move(nodeExpr));
  3934. }
  3935. }
  3936. for (size_t i = 0; i < names.size(); ++i) {
  3937. PushNamedNode(names[i], nodes[i]);
  3938. }
  3939. break;
  3940. }
  3941. case TRule_sql_stmt_core::kAltSqlStmtCore4: {
  3942. Ctx.BodyPart();
  3943. const auto& rule = core.GetAlt_sql_stmt_core4().GetRule_create_table_stmt1();
  3944. TTableRef tr(SimpleTableRefImpl(rule.GetRule_simple_table_ref3(), Mode, *this));
  3945. TVector<TColumnSchema> columns;
  3946. TVector<TIdentifier> pkColumns;
  3947. TVector<TIdentifier> partitionByColumns;
  3948. TVector<std::pair<TIdentifier, bool>> orderByColumns;
  3949. if (!CreateTableEntry(rule.GetRule_create_table_entry5(), *this, columns, pkColumns, partitionByColumns, orderByColumns)) {
  3950. return false;
  3951. }
  3952. for (auto& block: rule.GetBlock6()) {
  3953. if (!CreateTableEntry(block.GetRule_create_table_entry2(), *this, columns, pkColumns, partitionByColumns, orderByColumns)) {
  3954. return false;
  3955. }
  3956. }
  3957. AddStatementToBlocks(blocks, BuildCreateTable(Ctx.Pos(), tr, columns, pkColumns, partitionByColumns, orderByColumns));
  3958. break;
  3959. }
  3960. case TRule_sql_stmt_core::kAltSqlStmtCore5: {
  3961. Ctx.BodyPart();
  3962. const auto& rule = core.GetAlt_sql_stmt_core5().GetRule_drop_table_stmt1();
  3963. if (rule.HasBlock3()) {
  3964. Context().Error(GetPos(rule.GetToken1())) << "IF EXISTS in " << humanStatementName
  3965. << " is not supported.";
  3966. return false;
  3967. }
  3968. TTableRef tr(SimpleTableRefImpl(rule.GetRule_simple_table_ref4(), Mode, *this));
  3969. AddStatementToBlocks(blocks, BuildDropTable(Ctx.Pos(), tr));
  3970. break;
  3971. }
  3972. case TRule_sql_stmt_core::kAltSqlStmtCore6: {
  3973. const auto& rule = core.GetAlt_sql_stmt_core6().GetRule_use_stmt1();
  3974. Token(rule.GetToken1());
  3975. Ctx.CurrCluster = IdOrStringAsCluster(rule.GetRule_id_or_string2(), *this);
  3976. if (!Ctx.CurrCluster) {
  3977. return false;
  3978. }
  3979. break;
  3980. }
  3981. case TRule_sql_stmt_core::kAltSqlStmtCore7: {
  3982. Ctx.BodyPart();
  3983. TSqlIntoTable intoTable(Ctx, Mode);
  3984. TNodePtr block(intoTable.Build(core.GetAlt_sql_stmt_core7().GetRule_into_table_stmt1()));
  3985. if (!block) {
  3986. return false;
  3987. }
  3988. blocks.emplace_back(block);
  3989. break;
  3990. }
  3991. case TRule_sql_stmt_core::kAltSqlStmtCore8: {
  3992. Ctx.BodyPart();
  3993. const auto& rule = core.GetAlt_sql_stmt_core8().GetRule_commit_stmt1();
  3994. Token(rule.GetToken1());
  3995. blocks.emplace_back(BuildCommitClusters(Ctx.Pos()));
  3996. break;
  3997. }
  3998. case TRule_sql_stmt_core::kAltSqlStmtCore9: {
  3999. Ctx.BodyPart();
  4000. auto updateNode = Build(core.GetAlt_sql_stmt_core9().GetRule_update_stmt1());
  4001. if (!updateNode) {
  4002. return false;
  4003. }
  4004. AddStatementToBlocks(blocks, updateNode);
  4005. break;
  4006. }
  4007. case TRule_sql_stmt_core::kAltSqlStmtCore10: {
  4008. Ctx.BodyPart();
  4009. auto deleteNode = Build(core.GetAlt_sql_stmt_core10().GetRule_delete_stmt1());
  4010. if (!deleteNode) {
  4011. return false;
  4012. }
  4013. blocks.emplace_back(deleteNode);
  4014. break;
  4015. }
  4016. case TRule_sql_stmt_core::kAltSqlStmtCore11: {
  4017. Ctx.BodyPart();
  4018. const auto& rule = core.GetAlt_sql_stmt_core11().GetRule_rollback_stmt1();
  4019. Token(rule.GetToken1());
  4020. blocks.emplace_back(BuildRollbackClusters(Ctx.Pos()));
  4021. break;
  4022. }
  4023. case TRule_sql_stmt_core::kAltSqlStmtCore12:
  4024. if (!DeclareStatement(core.GetAlt_sql_stmt_core12().GetRule_declare_stmt1())) {
  4025. return false;
  4026. }
  4027. break;
  4028. case TRule_sql_stmt_core::kAltSqlStmtCore13:
  4029. if (!ImportStatement(core.GetAlt_sql_stmt_core13().GetRule_import_stmt1())) {
  4030. return false;
  4031. }
  4032. break;
  4033. case TRule_sql_stmt_core::kAltSqlStmtCore14:
  4034. if (!ExportStatement(core.GetAlt_sql_stmt_core14().GetRule_export_stmt1())) {
  4035. return false;
  4036. }
  4037. break;
  4038. case TRule_sql_stmt_core::kAltSqlStmtCore15: {
  4039. Ctx.BodyPart();
  4040. const auto& rule = core.GetAlt_sql_stmt_core15().GetRule_alter_table_stmt1();
  4041. TTableRef tr(SimpleTableRefImpl(rule.GetRule_simple_table_ref3(), Mode, *this));
  4042. const auto& ruleAction = rule.GetRule_alter_table_action4();
  4043. switch (ruleAction.Alt_case()) {
  4044. case TRule_alter_table_action::kAltAlterTableAction1: {
  4045. const auto& addRule = ruleAction.GetAlt_alter_table_action1().GetRule_alter_table_add_column1();
  4046. if (!AlterTableAddColumns(blocks, addRule, tr)) {
  4047. return false;
  4048. }
  4049. break;
  4050. }
  4051. case TRule_alter_table_action::kAltAlterTableAction2: {
  4052. const auto& dropRule = ruleAction.GetAlt_alter_table_action2().GetRule_alter_table_drop_column1();
  4053. if (!AlterTableDropColumn(blocks, dropRule, tr)) {
  4054. return false;
  4055. }
  4056. break;
  4057. }
  4058. default:
  4059. AltNotImplemented("alter_table_action", core);
  4060. return false;
  4061. }
  4062. break;
  4063. }
  4064. case TRule_sql_stmt_core::kAltSqlStmtCore16: {
  4065. Ctx.BodyPart();
  4066. auto node = DoStatement(core.GetAlt_sql_stmt_core16().GetRule_do_stmt1(), false);
  4067. if (!node) {
  4068. return false;
  4069. }
  4070. blocks.push_back(node);
  4071. break;
  4072. }
  4073. case TRule_sql_stmt_core::kAltSqlStmtCore17: {
  4074. Ctx.BodyPart();
  4075. if (!DefineActionOrSubqueryStatement(core.GetAlt_sql_stmt_core17().GetRule_define_action_or_subquery_stmt1())) {
  4076. return false;
  4077. }
  4078. break;
  4079. }
  4080. case TRule_sql_stmt_core::kAltSqlStmtCore18: {
  4081. Ctx.BodyPart();
  4082. auto node = EvaluateIfStatement(core.GetAlt_sql_stmt_core18().GetRule_evaluate_if_stmt1());
  4083. if (!node) {
  4084. return false;
  4085. }
  4086. blocks.push_back(node);
  4087. break;
  4088. }
  4089. case TRule_sql_stmt_core::kAltSqlStmtCore19: {
  4090. Ctx.BodyPart();
  4091. auto node = EvaluateForStatement(core.GetAlt_sql_stmt_core19().GetRule_evaluate_for_stmt1());
  4092. if (!node) {
  4093. return false;
  4094. }
  4095. blocks.push_back(node);
  4096. break;
  4097. }
  4098. default:
  4099. Ctx.IncrementMonCounter("sql_errors", "UnknownStatement" + internalStatementName);
  4100. AltNotImplemented("sql_stmt_core", core);
  4101. return false;
  4102. }
  4103. Ctx.IncrementMonCounter("sql_features", internalStatementName);
  4104. return !Ctx.HasPendingErrors;
  4105. }
  4106. bool TSqlQuery::DeclareStatement(const TRule_declare_stmt& stmt) {
  4107. TNodePtr defaultValue;
  4108. if (stmt.HasBlock5()) {
  4109. TSqlExpression sqlExpr(Ctx, Mode);
  4110. if (!(defaultValue = sqlExpr.LiteralExpr(stmt.GetBlock5().GetRule_literal_value2()))) {
  4111. return false;
  4112. }
  4113. }
  4114. if (defaultValue) {
  4115. Error() << "DEFAULT value not supported yet";
  4116. return false;
  4117. }
  4118. if (!Ctx.IsParseHeading()) {
  4119. Error() << "DECLARE statement should be in beginning of query, but it's possible to use PRAGMA or USE before it";
  4120. return false;
  4121. }
  4122. const auto varName = NamedNodeImpl(stmt.GetRule_bind_parameter2(), *this);
  4123. const auto varPos = Ctx.Pos();
  4124. const auto typeNode = FlexType(*this, stmt.GetRule_flex_type4());
  4125. if (!typeNode) {
  4126. return false;
  4127. }
  4128. if (!Ctx.DeclareVariable(varName, typeNode)) {
  4129. return false;
  4130. }
  4131. PushNamedNode(varName, BuildAtom(varPos, varName));
  4132. return true;
  4133. }
  4134. bool TSqlQuery::ExportStatement(const TRule_export_stmt& stmt) {
  4135. if (Mode != NSQLTranslation::ESqlMode::LIBRARY || !TopLevel) {
  4136. Error() << "EXPORT statement should be used only in a library on the top level";
  4137. return false;
  4138. }
  4139. TVector<TString> bindNames;
  4140. if (!BindList(stmt.GetRule_bind_parameter_list2(), bindNames)) {
  4141. return false;
  4142. }
  4143. return Ctx.AddExports(bindNames);
  4144. }
  4145. bool TSqlQuery::AlterTableAddColumns(TVector<TNodePtr>& blocks, const TRule_alter_table_add_column& rule, const TTableRef& tr) {
  4146. TVector<TColumnSchema> columns;
  4147. columns.push_back(ColumnSchemaImpl(rule.GetRule_column_schema3(), *this));
  4148. for (const auto& block: rule.GetBlock4()) {
  4149. columns.push_back(ColumnSchemaImpl(block.GetRule_column_schema4(), *this));
  4150. }
  4151. AddStatementToBlocks(blocks, BuildAlterTable(Ctx.Pos(), tr, columns, EAlterTableIntentnt::AddColumn));
  4152. return true;
  4153. }
  4154. bool TSqlQuery::AlterTableDropColumn(TVector<TNodePtr>& blocks, const TRule_alter_table_drop_column& node, const TTableRef& tr) {
  4155. TString name = Id(node.GetRule_id3(), *this);
  4156. TColumnSchema column(Ctx.Pos(), name, "", false, false);
  4157. AddStatementToBlocks(blocks, BuildAlterTable(Ctx.Pos(), tr, TVector<TColumnSchema>{column}, EAlterTableIntentnt::DropColumn));
  4158. return true;
  4159. }
  4160. TNodePtr TSqlQuery::PragmaStatement(const TRule_pragma_stmt& stmt, bool& success) {
  4161. success = false;
  4162. const TString& prefix = OptIdPrefixAsStr(stmt.GetRule_opt_id_prefix2(), *this);
  4163. const TString& lowerPrefix = to_lower(prefix);
  4164. const TString pragma(IdOrString(stmt.GetRule_id_or_string3(), *this));
  4165. TString normalizedPragma(pragma);
  4166. TMaybe<TIssue> normalizeError = NormalizeName(Ctx.Pos(), normalizedPragma);
  4167. if (!normalizeError.Empty()) {
  4168. Error() << normalizeError->GetMessage();
  4169. Ctx.IncrementMonCounter("sql_errors", "NormalizePragmaError");
  4170. return {};
  4171. }
  4172. TVector<TDeferredAtom> values;
  4173. TVector<const TRule_pragma_value*> pragmaValues;
  4174. bool pragmaValueDefault = false;
  4175. if (stmt.GetBlock4().HasAlt1()) {
  4176. pragmaValues.push_back(&stmt.GetBlock4().GetAlt1().GetRule_pragma_value2());
  4177. }
  4178. else if (stmt.GetBlock4().HasAlt2()) {
  4179. pragmaValues.push_back(&stmt.GetBlock4().GetAlt2().GetRule_pragma_value2());
  4180. for (auto& additionalValue : stmt.GetBlock4().GetAlt2().GetBlock3()) {
  4181. pragmaValues.push_back(&additionalValue.GetRule_pragma_value2());
  4182. }
  4183. }
  4184. const bool withConfigure = prefix || normalizedPragma == "file" || normalizedPragma == "folder" || normalizedPragma == "udf";
  4185. const bool hasLexicalScope = withConfigure || normalizedPragma == "classicdivision";
  4186. for (auto pragmaValue : pragmaValues) {
  4187. if (pragmaValue->HasAlt_pragma_value3()) {
  4188. values.push_back(TDeferredAtom(Ctx.Pos(), StringContent(Ctx, pragmaValue->GetAlt_pragma_value3().GetToken1().GetValue())));
  4189. }
  4190. else if (pragmaValue->HasAlt_pragma_value2()
  4191. && pragmaValue->GetAlt_pragma_value2().GetRule_id1().HasAlt_id2()
  4192. && "default" == Id(pragmaValue->GetAlt_pragma_value2().GetRule_id1(), *this))
  4193. {
  4194. pragmaValueDefault = true;
  4195. }
  4196. else if (withConfigure && pragmaValue->HasAlt_pragma_value5()) {
  4197. auto bindName = NamedNodeImpl(pragmaValue->GetAlt_pragma_value5().GetRule_bind_parameter1(), *this);
  4198. auto namedNode = GetNamedNode(bindName);
  4199. if (!namedNode) {
  4200. return {};
  4201. }
  4202. TDeferredAtom atom;
  4203. MakeTableFromExpression(Ctx, namedNode, atom);
  4204. values.push_back(atom);
  4205. } else {
  4206. Error() << "Expected string" << (withConfigure ? ", named parameter" : "") << " or 'default' keyword as pragma value for pragma: " << pragma;
  4207. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4208. return {};
  4209. }
  4210. }
  4211. if (prefix.empty()) {
  4212. if (!TopLevel && !hasLexicalScope) {
  4213. Error() << "This pragma '" << pragma << "' is not allowed to be used in actions or subqueries";
  4214. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4215. return{};
  4216. }
  4217. if (normalizedPragma == "refselect") {
  4218. Ctx.PragmaRefSelect = true;
  4219. Ctx.IncrementMonCounter("sql_pragma", "RefSelect");
  4220. } else if (normalizedPragma == "sampleselect") {
  4221. Ctx.PragmaSampleSelect = true;
  4222. Ctx.IncrementMonCounter("sql_pragma", "SampleSelect");
  4223. } else if (normalizedPragma == "allowdotinalias") {
  4224. Ctx.PragmaAllowDotInAlias = true;
  4225. Ctx.IncrementMonCounter("sql_pragma", "AllowDotInAlias");
  4226. } else if (normalizedPragma == "udf") {
  4227. if (values.size() != 1 || pragmaValueDefault) {
  4228. Error() << "Expected file alias as pragma value";
  4229. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4230. return {};
  4231. }
  4232. Ctx.IncrementMonCounter("sql_pragma", "udf");
  4233. success = true;
  4234. return BuildPragma(Ctx.Pos(), TString(ConfigProviderName), "ImportUdfs", values, false);
  4235. } else if (normalizedPragma == "file") {
  4236. if (values.size() != 2U || pragmaValueDefault) {
  4237. Error() << "Expected file alias and url as pragma values";
  4238. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4239. return {};
  4240. }
  4241. Ctx.IncrementMonCounter("sql_pragma", "file");
  4242. success = true;
  4243. return BuildPragma(Ctx.Pos(), TString(ConfigProviderName), "AddFileByUrl", values, false);
  4244. } else if (normalizedPragma == "folder") {
  4245. if (values.size() != 2U || pragmaValueDefault) {
  4246. Error() << "Expected folder alias as url as pragma values";
  4247. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4248. return {};
  4249. }
  4250. Ctx.IncrementMonCounter("sql_pragma", "folder");
  4251. success = true;
  4252. return BuildPragma(Ctx.Pos(), TString(ConfigProviderName), "AddFolderByUrl", values, false);
  4253. } else if (normalizedPragma == "library") {
  4254. if (values.size() != 1) {
  4255. Error() << "Expected non-empty file alias";
  4256. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4257. return{};
  4258. }
  4259. Ctx.Libraries.emplace(*values.front().GetLiteral());
  4260. Ctx.IncrementMonCounter("sql_pragma", "library");
  4261. } else if (normalizedPragma == "inferscheme" || normalizedPragma == "inferschema") {
  4262. Ctx.Warning(Ctx.Pos(), TIssuesIds::YQL_DEPRECATED_INFERSCHEME) << "PRAGMA InferScheme is deprecated, please use PRAGMA yt.InferSchema instead.";
  4263. Ctx.PragmaInferSchema = true;
  4264. Ctx.IncrementMonCounter("sql_pragma", "InferSchema");
  4265. } else if (normalizedPragma == "directread") {
  4266. Ctx.PragmaDirectRead = true;
  4267. Ctx.IncrementMonCounter("sql_pragma", "DirectRead");
  4268. } else if (normalizedPragma == "equijoin") {
  4269. Ctx.IncrementMonCounter("sql_pragma", "EquiJoin");
  4270. } else if (normalizedPragma == "autocommit") {
  4271. Ctx.PragmaAutoCommit = true;
  4272. Ctx.IncrementMonCounter("sql_pragma", "AutoCommit");
  4273. } else if (normalizedPragma == "tablepathprefix") {
  4274. if (values.size() == 1) {
  4275. if (!Ctx.SetPathPrefix(*values[0].GetLiteral())) {
  4276. return {};
  4277. }
  4278. } else if (values.size() == 2) {
  4279. if (!Ctx.SetPathPrefix(*values[1].GetLiteral(), *values[0].GetLiteral())) {
  4280. return {};
  4281. }
  4282. } else {
  4283. Error() << "Expected path prefix or tuple of (Provider, PathPrefix) or"
  4284. << " (Cluster, PathPrefix) as pragma value";
  4285. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4286. return {};
  4287. }
  4288. Ctx.IncrementMonCounter("sql_pragma", "PathPrefix");
  4289. } else if (normalizedPragma == "groupbylimit") {
  4290. if (values.size() != 1 || !TryFromString(*values[0].GetLiteral(), Ctx.PragmaGroupByLimit)) {
  4291. Error() << "Expected single unsigned integer argument for: " << pragma;
  4292. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4293. return {};
  4294. }
  4295. Ctx.IncrementMonCounter("sql_pragma", "GroupByLimit");
  4296. } else if (normalizedPragma == "groupbycubelimit") {
  4297. if (values.size() != 1 || !TryFromString(*values[0].GetLiteral(), Ctx.PragmaGroupByCubeLimit)) {
  4298. Error() << "Expected single unsigned integer argument for: " << pragma;
  4299. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4300. return {};
  4301. }
  4302. Ctx.IncrementMonCounter("sql_pragma", "GroupByCubeLimit");
  4303. }
  4304. else if (normalizedPragma == "simplecolumns") {
  4305. Ctx.SimpleColumns = true;
  4306. Ctx.IncrementMonCounter("sql_pragma", "SimpleColumns");
  4307. }
  4308. else if (normalizedPragma == "disablesimplecolumns") {
  4309. Ctx.SimpleColumns = false;
  4310. Ctx.IncrementMonCounter("sql_pragma", "DisableSimpleColumns");
  4311. } else if (normalizedPragma == "resultrowslimit") {
  4312. if (values.size() != 1 || !TryFromString(*values[0].GetLiteral(), Ctx.ResultRowsLimit)) {
  4313. Error() << "Expected single unsigned integer argument for: " << pragma;
  4314. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4315. return {};
  4316. }
  4317. Ctx.IncrementMonCounter("sql_pragma", "ResultRowsLimit");
  4318. } else if (normalizedPragma == "resultsizelimit") {
  4319. if (values.size() != 1 || !TryFromString(*values[0].GetLiteral(), Ctx.ResultSizeLimit)) {
  4320. Error() << "Expected single unsigned integer argument for: " << pragma;
  4321. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4322. return {};
  4323. }
  4324. Ctx.IncrementMonCounter("sql_pragma", "ResultSizeLimit");
  4325. } else if (normalizedPragma == "warning") {
  4326. if (values.size() != 2U || values.front().Empty() || values.back().Empty()) {
  4327. Error() << "Expected arguments <action>, <issueId> for: " << pragma;
  4328. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4329. return {};
  4330. }
  4331. TString codePattern = *values[1].GetLiteral();
  4332. TString action = *values[0].GetLiteral();
  4333. TWarningRule rule;
  4334. TString parseError;
  4335. auto parseResult = TWarningRule::ParseFrom(codePattern, action, rule, parseError);
  4336. switch (parseResult) {
  4337. case TWarningRule::EParseResult::PARSE_OK:
  4338. Ctx.WarningPolicy.AddRule(rule);
  4339. if (Ctx.Settings.WarnOnV0 && codePattern == "*") {
  4340. // Add exception for YQL_DEPRECATED_V0_SYNTAX
  4341. TWarningRule defaultForDeprecatedV0;
  4342. YQL_ENSURE(TWarningRule::ParseFrom(ToString(TIssueCode(TIssuesIds::YQL_DEPRECATED_V0_SYNTAX)),
  4343. "default", defaultForDeprecatedV0,
  4344. parseError) == TWarningRule::EParseResult::PARSE_OK);
  4345. Ctx.WarningPolicy.AddRule(defaultForDeprecatedV0);
  4346. }
  4347. break;
  4348. case TWarningRule::EParseResult::PARSE_PATTERN_FAIL:
  4349. case TWarningRule::EParseResult::PARSE_ACTION_FAIL:
  4350. Ctx.Error() << parseError;
  4351. return {};
  4352. default:
  4353. Y_ENSURE(false, "Unknown parse result");
  4354. }
  4355. Ctx.IncrementMonCounter("sql_pragma", "warning");
  4356. } else if (normalizedPragma == "greetings") {
  4357. if (values.size() > 1) {
  4358. Error() << "Not expect few arguments for: " << pragma;
  4359. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4360. return {};
  4361. } else if (values.empty()) {
  4362. values.emplace_back(TDeferredAtom(Ctx.Pos(), "Hello, world! And best wishes from the YQL Team!"));
  4363. }
  4364. Ctx.Info(Ctx.Pos()) << *values[0].GetLiteral();
  4365. } else if (normalizedPragma == "warningmsg") {
  4366. if (values.size() != 1) {
  4367. Error() << "Expected single string argument for: " << pragma;
  4368. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4369. return {};
  4370. }
  4371. Ctx.Warning(Ctx.Pos(), TIssuesIds::YQL_PRAGMA_WARNING_MSG) << *values[0].GetLiteral();
  4372. } else if (normalizedPragma == "errormsg") {
  4373. if (values.size() != 1) {
  4374. Error() << "Expected single string argument for: " << pragma;
  4375. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4376. return {};
  4377. }
  4378. Ctx.Error(Ctx.Pos()) << *values[0].GetLiteral();
  4379. } else if (normalizedPragma == "classicdivision") {
  4380. if (values.size() != 1 || !TryFromString(*values[0].GetLiteral(), Ctx.PragmaClassicDivision)) {
  4381. Error() << "Expected single boolean argument for: " << pragma;
  4382. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4383. return {};
  4384. }
  4385. Ctx.IncrementMonCounter("sql_pragma", "ClassicDivision");
  4386. } else if (normalizedPragma == "disableunordered") {
  4387. Ctx.Warning(Ctx.Pos(), TIssuesIds::YQL_DEPRECATED_PRAGMA)
  4388. << "Use of deprecated DisableUnordered pragma. It will be dropped soon";
  4389. } else if (normalizedPragma == "pullupflatmapoverjoin") {
  4390. Ctx.PragmaPullUpFlatMapOverJoin = true;
  4391. Ctx.IncrementMonCounter("sql_pragma", "PullUpFlatMapOverJoin");
  4392. } else if (normalizedPragma == "disablepullupflatmapoverjoin") {
  4393. Ctx.PragmaPullUpFlatMapOverJoin = false;
  4394. Ctx.IncrementMonCounter("sql_pragma", "DisablePullUpFlatMapOverJoin");
  4395. } else if (normalizedPragma == "enablesystemcolumns") {
  4396. if (values.size() != 1 || !TryFromString(*values[0].GetLiteral(), Ctx.EnableSystemColumns)) {
  4397. Error() << "Expected single boolean argument for: " << pragma;
  4398. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4399. return {};
  4400. }
  4401. Ctx.IncrementMonCounter("sql_pragma", "EnableSystemColumns");
  4402. } else {
  4403. Error() << "Unknown pragma: " << pragma;
  4404. Ctx.IncrementMonCounter("sql_errors", "UnknownPragma");
  4405. return {};
  4406. }
  4407. } else {
  4408. if (lowerPrefix == "yson") {
  4409. if (!TopLevel) {
  4410. Error() << "This pragma '" << pragma << "' is not allowed to be used in actions";
  4411. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4412. return {};
  4413. }
  4414. if (normalizedPragma == "autoconvert") {
  4415. Ctx.PragmaYsonAutoConvert = true;
  4416. success = true;
  4417. return {};
  4418. } else if (normalizedPragma == "strict") {
  4419. Ctx.PragmaYsonStrict = true;
  4420. success = true;
  4421. return {};
  4422. } else if (normalizedPragma == "disablestrict") {
  4423. Ctx.PragmaYsonStrict = false;
  4424. success = true;
  4425. return {};
  4426. } else {
  4427. Error() << "Unknown pragma: '" << pragma << "'";
  4428. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4429. return {};
  4430. }
  4431. } else if (std::find(Providers.cbegin(), Providers.cend(), lowerPrefix) == Providers.cend()) {
  4432. if (!Ctx.HasCluster(lowerPrefix)) {
  4433. Error() << "Unknown pragma prefix: " << prefix << ", please use cluster name or one of provider " <<
  4434. JoinRange(", ", Providers.cbegin(), Providers.cend());
  4435. Ctx.IncrementMonCounter("sql_errors", "UnknownPragma");
  4436. return {};
  4437. }
  4438. }
  4439. if (normalizedPragma != "flags") {
  4440. if (values.size() > 1) {
  4441. Error() << "Expected at most one value in the pragma";
  4442. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4443. return {};
  4444. }
  4445. } else {
  4446. if (pragmaValueDefault || values.size() < 1) {
  4447. Error() << "Expected at least one value in the pragma";
  4448. Ctx.IncrementMonCounter("sql_errors", "BadPragmaValue");
  4449. return {};
  4450. }
  4451. }
  4452. success = true;
  4453. Ctx.IncrementMonCounter("sql_pragma", pragma);
  4454. return BuildPragma(Ctx.Pos(), lowerPrefix, normalizedPragma, values, pragmaValueDefault);
  4455. }
  4456. success = true;
  4457. return {};
  4458. }
  4459. TNodePtr TSqlQuery::Build(const TRule_delete_stmt& stmt) {
  4460. TTableRef table = SimpleTableRefImpl(stmt.GetRule_simple_table_ref3(), Mode, *this);
  4461. if (!table.Check(Ctx)) {
  4462. return nullptr;
  4463. }
  4464. auto serviceName = to_lower(table.ServiceName(Ctx));
  4465. const bool isKikimr = serviceName == KikimrProviderName;
  4466. if (!isKikimr) {
  4467. Ctx.Error(GetPos(stmt.GetToken1())) << "DELETE is unsupported for " << serviceName;
  4468. return nullptr;
  4469. }
  4470. TSourcePtr source = BuildTableSource(Ctx.Pos(), table, false);
  4471. if (stmt.HasBlock4()) {
  4472. switch (stmt.GetBlock4().Alt_case()) {
  4473. case TRule_delete_stmt_TBlock4::kAlt1: {
  4474. const auto& alt = stmt.GetBlock4().GetAlt1();
  4475. TSqlExpression sqlExpr(Ctx, Mode);
  4476. auto whereExpr = sqlExpr.Build(alt.GetRule_expr2());
  4477. if (!whereExpr) {
  4478. return nullptr;
  4479. }
  4480. source->AddFilter(Ctx, whereExpr);
  4481. break;
  4482. }
  4483. case TRule_delete_stmt_TBlock4::kAlt2: {
  4484. const auto& alt = stmt.GetBlock4().GetAlt2();
  4485. auto values = TSqlIntoValues(Ctx, Mode).Build(alt.GetRule_into_values_source2(), "DELETE ON");
  4486. if (!values) {
  4487. return nullptr;
  4488. }
  4489. return BuildWriteColumns(Ctx.Pos(), table, EWriteColumnMode::DeleteOn, std::move(values));
  4490. }
  4491. default:
  4492. return nullptr;
  4493. }
  4494. }
  4495. return BuildDelete(Ctx.Pos(), table, std::move(source));
  4496. }
  4497. TNodePtr TSqlQuery::Build(const TRule_update_stmt& stmt) {
  4498. TTableRef table = SimpleTableRefImpl(stmt.GetRule_simple_table_ref2(), Mode, *this);
  4499. if (!table.Check(Ctx)) {
  4500. return nullptr;
  4501. }
  4502. auto serviceName = to_lower(table.ServiceName(Ctx));
  4503. const bool isKikimr = serviceName == KikimrProviderName;
  4504. if (!isKikimr) {
  4505. Ctx.Error(GetPos(stmt.GetToken1())) << "UPDATE is unsupported for " << serviceName;
  4506. return nullptr;
  4507. }
  4508. switch (stmt.GetBlock3().Alt_case()) {
  4509. case TRule_update_stmt_TBlock3::kAlt1: {
  4510. const auto& alt = stmt.GetBlock3().GetAlt1();
  4511. TSourcePtr values = Build(alt.GetRule_set_clause_choice2());
  4512. auto source = BuildTableSource(Ctx.Pos(), table, false);
  4513. if (alt.HasBlock3()) {
  4514. TSqlExpression sqlExpr(Ctx, Mode);
  4515. auto whereExpr = sqlExpr.Build(alt.GetBlock3().GetRule_expr2());
  4516. if (!whereExpr) {
  4517. return nullptr;
  4518. }
  4519. source->AddFilter(Ctx, whereExpr);
  4520. }
  4521. return BuildUpdateColumns(Ctx.Pos(), table, std::move(values), std::move(source));
  4522. }
  4523. case TRule_update_stmt_TBlock3::kAlt2: {
  4524. const auto& alt = stmt.GetBlock3().GetAlt2();
  4525. auto values = TSqlIntoValues(Ctx, Mode).Build(alt.GetRule_into_values_source2(), "UPDATE ON");
  4526. if (!values) {
  4527. return nullptr;
  4528. }
  4529. return BuildWriteColumns(Ctx.Pos(), table, EWriteColumnMode::UpdateOn, std::move(values));
  4530. }
  4531. default:
  4532. return nullptr;
  4533. }
  4534. }
  4535. TSourcePtr TSqlQuery::Build(const TRule_set_clause_choice& stmt) {
  4536. switch (stmt.Alt_case()) {
  4537. case TRule_set_clause_choice::kAltSetClauseChoice1:
  4538. return Build(stmt.GetAlt_set_clause_choice1().GetRule_set_clause_list1());
  4539. case TRule_set_clause_choice::kAltSetClauseChoice2:
  4540. return Build(stmt.GetAlt_set_clause_choice2().GetRule_multiple_column_assignment1());
  4541. default:
  4542. AltNotImplemented("set_clause_choice", stmt);
  4543. return nullptr;
  4544. }
  4545. }
  4546. bool TSqlQuery::FillSetClause(const TRule_set_clause& node, TVector<TString>& targetList, TVector<TNodePtr>& values) {
  4547. targetList.push_back(ColumnNameAsSingleStr(*this, node.GetRule_set_target1().GetRule_column_name1()));
  4548. TSqlExpression sqlExpr(Ctx, Mode);
  4549. if (!Expr(sqlExpr, values, node.GetRule_expr3())) {
  4550. return false;
  4551. }
  4552. return true;
  4553. }
  4554. TSourcePtr TSqlQuery::Build(const TRule_set_clause_list& stmt) {
  4555. TVector<TString> targetList;
  4556. TVector<TNodePtr> values;
  4557. const TPosition pos(Ctx.Pos());
  4558. if (!FillSetClause(stmt.GetRule_set_clause1(), targetList, values)) {
  4559. return nullptr;
  4560. }
  4561. for (auto& block: stmt.GetBlock2()) {
  4562. if (!FillSetClause(block.GetRule_set_clause2(), targetList, values)) {
  4563. return nullptr;
  4564. }
  4565. }
  4566. Y_DEBUG_ABORT_UNLESS(targetList.size() == values.size());
  4567. return BuildUpdateValues(pos, targetList, values);
  4568. }
  4569. TSourcePtr TSqlQuery::Build(const TRule_multiple_column_assignment& stmt) {
  4570. TVector<TString> targetList;
  4571. FillTargetList(*this, stmt.GetRule_set_target_list1(), targetList);
  4572. auto simpleValuesNode = stmt.GetRule_simple_values_source4();
  4573. const TPosition pos(Ctx.Pos());
  4574. switch (simpleValuesNode.Alt_case()) {
  4575. case TRule_simple_values_source::kAltSimpleValuesSource1: {
  4576. TVector<TNodePtr> values;
  4577. TSqlExpression sqlExpr(Ctx, Mode);
  4578. if (!ExprList(sqlExpr, values, simpleValuesNode.GetAlt_simple_values_source1().GetRule_expr_list1())) {
  4579. return nullptr;
  4580. }
  4581. return BuildUpdateValues(pos, targetList, values);
  4582. }
  4583. case TRule_simple_values_source::kAltSimpleValuesSource2: {
  4584. TSqlSelect select(Ctx, Mode);
  4585. TPosition selectPos;
  4586. auto source = select.Build(simpleValuesNode.GetAlt_simple_values_source2().GetRule_select_stmt1(), selectPos);
  4587. if (!source) {
  4588. return nullptr;
  4589. }
  4590. return BuildWriteValues(pos, "UPDATE", targetList, std::move(source));
  4591. }
  4592. default:
  4593. Ctx.IncrementMonCounter("sql_errors", "UnknownSimpleValuesSourceAlt");
  4594. AltNotImplemented("simple_values_source", simpleValuesNode);
  4595. return nullptr;
  4596. }
  4597. }
  4598. TNodePtr TSqlQuery::Build(const TSQLParserAST& ast) {
  4599. const auto& statements = ast.GetRule_sql_stmt_list();
  4600. TVector<TNodePtr> blocks;
  4601. if (Ctx.Settings.WarnOnV0) {
  4602. if (Ctx.Settings.V0WarnAsError->Allow()) {
  4603. Error() << "SQL v0 syntax is deprecated and no longer supported. Please switch to v1: https://clubs.at.yandex-team.ru/yql/2910";
  4604. return nullptr;
  4605. }
  4606. Ctx.Warning(Ctx.Pos(), TIssuesIds::YQL_DEPRECATED_V0_SYNTAX) <<
  4607. "SQL v0 syntax is deprecated and will stop working soon. Consider switching to v1: https://clubs.at.yandex-team.ru/yql/2910";
  4608. }
  4609. if (Ctx.Settings.V0Behavior == NSQLTranslation::EV0Behavior::Report) {
  4610. AddStatementToBlocks(blocks, BuildPragma(TPosition(), "config", "flags", {
  4611. TDeferredAtom(TPosition(), "SQL"),
  4612. TDeferredAtom(TPosition(), "0")
  4613. }, false));
  4614. }
  4615. if (!Statement(blocks, statements.GetRule_sql_stmt1().GetRule_sql_stmt_core2())) {
  4616. return nullptr;
  4617. }
  4618. for (auto block: statements.GetBlock2()) {
  4619. if (!Statement(blocks, block.GetRule_sql_stmt2().GetRule_sql_stmt_core2())) {
  4620. return nullptr;
  4621. }
  4622. }
  4623. ui32 topLevelSelects = 0;
  4624. for (auto& block : blocks) {
  4625. if (block->IsSelect()) {
  4626. ++topLevelSelects;
  4627. }
  4628. }
  4629. if ((Mode == NSQLTranslation::ESqlMode::SUBQUERY || Mode == NSQLTranslation::ESqlMode::LIMITED_VIEW) && topLevelSelects != 1) {
  4630. Error() << "Strictly one select/process/reduce statement must be used in the "
  4631. << (Mode == NSQLTranslation::ESqlMode::LIMITED_VIEW ? "view" : "subquery");
  4632. return nullptr;
  4633. }
  4634. if (!Ctx.PragmaAutoCommit && Ctx.Settings.EndOfQueryCommit && IsQueryMode(Mode)) {
  4635. AddStatementToBlocks(blocks, BuildCommitClusters(Ctx.Pos()));
  4636. }
  4637. return BuildQuery(Ctx.Pos(), blocks, true);
  4638. }
  4639. TNodePtr TSqlQuery::FlexType(TTranslation& ctx, const TRule_flex_type& node) {
  4640. const auto& stringType = NSQLTranslationV0::FlexType(node, ctx);
  4641. auto res = TryBuildDataType(Ctx.Pos(), TypeByAlias(stringType.first, !stringType.second));
  4642. if (!res) {
  4643. res = BuildBuiltinFunc(Ctx, Ctx.Pos(), "ParseType", {BuildLiteralRawString(Ctx.Pos(), stringType.first)});
  4644. }
  4645. return res;
  4646. }
  4647. bool TSqlTranslation::DefineActionOrSubqueryStatement(const TRule_define_action_or_subquery_stmt& stmt) {
  4648. auto kind = Ctx.Token(stmt.GetToken2());
  4649. const bool isSubquery = to_lower(kind) == "subquery";
  4650. if (!isSubquery && Mode == NSQLTranslation::ESqlMode::SUBQUERY) {
  4651. Error() << "Definition of actions is not allowed in the subquery";
  4652. return false;
  4653. }
  4654. auto actionName = NamedNodeImpl(stmt.GetRule_bind_parameter3(), *this);
  4655. TVector<TString> argNames;
  4656. if (stmt.HasBlock5() && !BindList(stmt.GetBlock5().GetRule_bind_parameter_list1(), argNames)) {
  4657. return false;
  4658. }
  4659. auto saveNamedNodes = Ctx.NamedNodes;
  4660. for (const auto& arg : argNames) {
  4661. PushNamedNode(arg, BuildAtom(Ctx.Pos(), arg, NYql::TNodeFlags::Default));
  4662. }
  4663. auto saveCurrCluster = Ctx.CurrCluster;
  4664. auto savePragmaClassicDivision = Ctx.PragmaClassicDivision;
  4665. auto saveMode = Ctx.Settings.Mode;
  4666. if (isSubquery) {
  4667. Ctx.Settings.Mode = NSQLTranslation::ESqlMode::SUBQUERY;
  4668. }
  4669. TSqlQuery query(Ctx, Ctx.Settings.Mode, false);
  4670. TVector<TNodePtr> blocks;
  4671. const auto& body = stmt.GetRule_define_action_or_subquery_body8();
  4672. bool hasError = false;
  4673. for (const auto& nestedStmtItem : body.GetBlock1()) {
  4674. const auto& nestedStmt = nestedStmtItem.GetRule_sql_stmt_core1();
  4675. if (!query.Statement(blocks, nestedStmt)) {
  4676. hasError = true;
  4677. break;
  4678. }
  4679. }
  4680. ui32 topLevelSelects = 0;
  4681. for (auto& block : blocks) {
  4682. if (block->IsSelect()) {
  4683. ++topLevelSelects;
  4684. }
  4685. }
  4686. if (isSubquery && topLevelSelects != 1) {
  4687. Error() << "Strictly one select/process/reduce statement must be used in the subquery";
  4688. return false;
  4689. }
  4690. auto ret = !hasError ? BuildQuery(Ctx.Pos(), blocks, false) : nullptr;
  4691. Ctx.CurrCluster = saveCurrCluster;
  4692. Ctx.PragmaClassicDivision = savePragmaClassicDivision;
  4693. Ctx.NamedNodes = saveNamedNodes;
  4694. Ctx.Settings.Mode = saveMode;
  4695. if (!ret) {
  4696. return false;
  4697. }
  4698. TNodePtr blockNode = new TAstListNodeImpl(Ctx.Pos());
  4699. blockNode->Add("block");
  4700. blockNode->Add(blockNode->Q(ret));
  4701. TNodePtr params = new TAstListNodeImpl(Ctx.Pos());
  4702. params->Add("world");
  4703. for (const auto& arg : argNames) {
  4704. params->Add(arg);
  4705. }
  4706. auto lambda = BuildLambda(Ctx.Pos(), params, blockNode);
  4707. PushNamedNode(actionName, lambda);
  4708. return true;
  4709. }
  4710. TNodePtr TSqlTranslation::EvaluateIfStatement(const TRule_evaluate_if_stmt& stmt) {
  4711. TSqlExpression expr(Ctx, Mode);
  4712. auto exprNode = expr.Build(stmt.GetRule_expr3());
  4713. if (!exprNode) {
  4714. return {};
  4715. }
  4716. auto thenNode = DoStatement(stmt.GetRule_do_stmt4(), true);
  4717. if (!thenNode) {
  4718. return {};
  4719. }
  4720. TNodePtr elseNode;
  4721. if (stmt.HasBlock5()) {
  4722. elseNode = DoStatement(stmt.GetBlock5().GetRule_do_stmt2(), true);
  4723. if (!elseNode) {
  4724. return {};
  4725. }
  4726. }
  4727. return BuildEvaluateIfNode(Ctx.Pos(), exprNode, thenNode, elseNode);
  4728. }
  4729. TNodePtr TSqlTranslation::EvaluateForStatement(const TRule_evaluate_for_stmt& stmt) {
  4730. TSqlExpression expr(Ctx, Mode);
  4731. auto itemArgName = NamedNodeImpl(stmt.GetRule_bind_parameter3(), *this);
  4732. auto exprNode = expr.Build(stmt.GetRule_expr5());
  4733. if (!exprNode) {
  4734. return{};
  4735. }
  4736. PushNamedNode(itemArgName, new TAstAtomNodeImpl(Ctx.Pos(), itemArgName, TNodeFlags::Default));
  4737. auto bodyNode = DoStatement(stmt.GetRule_do_stmt6(), true, { itemArgName });
  4738. PopNamedNode(itemArgName);
  4739. if (!bodyNode) {
  4740. return{};
  4741. }
  4742. TNodePtr elseNode;
  4743. if (stmt.HasBlock7()) {
  4744. elseNode = DoStatement(stmt.GetBlock7().GetRule_do_stmt2(), true);
  4745. if (!elseNode) {
  4746. return{};
  4747. }
  4748. }
  4749. return BuildEvaluateForNode(Ctx.Pos(), exprNode, bodyNode, elseNode);
  4750. }
  4751. google::protobuf::Message* SqlAST(const TString& query, const TString& queryName, TIssues& err, size_t maxErrors, google::protobuf::Arena* arena) {
  4752. YQL_ENSURE(arena);
  4753. #if defined(_tsan_enabled_)
  4754. TGuard<TMutex> grd(SanitizerSQLTranslationMutex);
  4755. #endif
  4756. NSQLTranslation::TErrorCollectorOverIssues collector(err, maxErrors, "");
  4757. NProtoAST::TProtoASTBuilder3<NALP::SQLParser, NALP::SQLLexer> builder(query, queryName, arena);
  4758. return builder.BuildAST(collector);
  4759. }
  4760. google::protobuf::Message* SqlAST(const TString& query, const TString& queryName, NProtoAST::IErrorCollector& err, google::protobuf::Arena* arena) {
  4761. YQL_ENSURE(arena);
  4762. #if defined(_tsan_enabled_)
  4763. TGuard<TMutex> grd(SanitizerSQLTranslationMutex);
  4764. #endif
  4765. NProtoAST::TProtoASTBuilder3<NALP::SQLParser, NALP::SQLLexer> builder(query, queryName, arena);
  4766. return builder.BuildAST(err);
  4767. }
  4768. TAstNode* SqlASTToYql(const google::protobuf::Message& protoAst, TContext& ctx) {
  4769. const google::protobuf::Descriptor* d = protoAst.GetDescriptor();
  4770. if (d && d->name() != "TSQLParserAST") {
  4771. ctx.Error() << "Invalid AST structure: " << d->name() << ", expected TSQLParserAST";
  4772. return nullptr;
  4773. }
  4774. TSqlQuery query(ctx, ctx.Settings.Mode, true);
  4775. TNodePtr node(query.Build(static_cast<const TSQLParserAST&>(protoAst)));
  4776. try {
  4777. if (node && node->Init(ctx, nullptr)) {
  4778. return node->Translate(ctx);
  4779. }
  4780. } catch (const NProtoAST::TTooManyErrors&) {
  4781. // do not add error issue, no room for it
  4782. }
  4783. return nullptr;
  4784. }
  4785. void SqlASTToYqlImpl(NYql::TAstParseResult& res, const google::protobuf::Message& protoAst,
  4786. TContext& ctx) {
  4787. YQL_ENSURE(!ctx.Issues.Size());
  4788. res.Root = SqlASTToYql(protoAst, ctx);
  4789. res.Pool = std::move(ctx.Pool);
  4790. if (!res.Root) {
  4791. if (ctx.Issues.Size()) {
  4792. ctx.IncrementMonCounter("sql_errors", "AstToYqlError");
  4793. } else {
  4794. ctx.IncrementMonCounter("sql_errors", "AstToYqlSilentError");
  4795. ctx.Error() << "Error occurred on parse SQL query, but no error is collected" <<
  4796. ", please send this request over bug report into YQL interface or write on yql@ maillist";
  4797. }
  4798. }
  4799. }
  4800. NYql::TAstParseResult SqlASTToYql(const google::protobuf::Message& protoAst,
  4801. const NSQLTranslation::TTranslationSettings& settings)
  4802. {
  4803. YQL_ENSURE(IsQueryMode(settings.Mode));
  4804. TAstParseResult res;
  4805. TContext ctx(settings, res.Issues);
  4806. SqlASTToYqlImpl(res, protoAst, ctx);
  4807. res.ActualSyntaxType = ESyntaxType::YQLv0;
  4808. return res;
  4809. }
  4810. NYql::TAstParseResult SqlToYql(const TString& query, const NSQLTranslation::TTranslationSettings& settings, NYql::TWarningRules* warningRules)
  4811. {
  4812. TAstParseResult res;
  4813. TContext ctx(settings, res.Issues);
  4814. NSQLTranslation::TErrorCollectorOverIssues collector(res.Issues, settings.MaxErrors, settings.File);
  4815. google::protobuf::Message* ast(SqlAST(query, "query", collector, settings.Arena));
  4816. if (ast) {
  4817. SqlASTToYqlImpl(res, *ast, ctx);
  4818. } else {
  4819. ctx.IncrementMonCounter("sql_errors", "AstError");
  4820. }
  4821. if (warningRules) {
  4822. *warningRules = ctx.WarningPolicy.GetRules();
  4823. ctx.WarningPolicy.Clear();
  4824. }
  4825. res.ActualSyntaxType = NYql::ESyntaxType::YQLv0;
  4826. return res;
  4827. }
  4828. class TTranslator : public NSQLTranslation::ITranslator {
  4829. public:
  4830. NSQLTranslation::ILexer::TPtr MakeLexer(const NSQLTranslation::TTranslationSettings& settings) final {
  4831. Y_UNUSED(settings);
  4832. return NSQLTranslationV0::MakeLexer();
  4833. }
  4834. NYql::TAstParseResult TextToAst(const TString& query, const NSQLTranslation::TTranslationSettings& settings,
  4835. NYql::TWarningRules* warningRules, NYql::TStmtParseInfo* stmtParseInfo) final {
  4836. Y_UNUSED(stmtParseInfo);
  4837. return SqlToYql(query, settings, warningRules);
  4838. }
  4839. google::protobuf::Message* TextToMessage(const TString& query, const TString& queryName,
  4840. NYql::TIssues& issues, size_t maxErrors, const NSQLTranslation::TTranslationSettings& settings) final {
  4841. return SqlAST(query, queryName, issues, maxErrors, settings.Arena);
  4842. }
  4843. NYql::TAstParseResult TextAndMessageToAst(const TString& query, const google::protobuf::Message& protoAst,
  4844. const NSQLTranslation::TSQLHints& hints, const NSQLTranslation::TTranslationSettings& settings) final {
  4845. Y_UNUSED(query);
  4846. Y_UNUSED(hints);
  4847. return SqlASTToYql(protoAst, settings);
  4848. }
  4849. TVector<NYql::TAstParseResult> TextToManyAst(const TString& query, const NSQLTranslation::TTranslationSettings& settings,
  4850. NYql::TWarningRules* warningRules, TVector<NYql::TStmtParseInfo>* stmtParseInfo) final {
  4851. Y_UNUSED(query);
  4852. Y_UNUSED(settings);
  4853. Y_UNUSED(warningRules);
  4854. Y_UNUSED(stmtParseInfo);
  4855. return {};
  4856. }
  4857. };
  4858. NSQLTranslation::TTranslatorPtr MakeTranslator() {
  4859. return MakeIntrusive<TTranslator>();
  4860. }
  4861. } // namespace NSQLTranslationV0