sql.cpp 213 KB

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